PageSourceSearch

https://bragx.com/static/js/main.js?v=1791095376

js bragx.com collected 2026-10-04 06:53:19 UTC 89,549 bytes, 2,632 lines download raw bytes

1$(document).ready(function () {
2  
3	String.prototype.trim = function() {
4		return this.replace(/^\s+/, '').replace(/\s+$/, '');
5	};
6
7	if (!('ontouchstart' in document)) {
8		$('body').addClass('no-touch');
9	}
10
11	$.fn.exists = function () {
12		return this.length > 0;
13	};
14
15	(function() {
16		var storage = {};
17		var recaptchaLoaded = false;
18
19		var pageContext = window['pageContext'];
20
21		var animationSpeed = 400;
22		if (pageContext && pageContext['animation']) {
23			animationSpeed = parseInt(pageContext['animation']) || 0;
24		}
25
26		var lazyLoadDefOptions = {
27			effect: 'fadeIn',
28			attribute: 'data-original',
29			placeholder: 'data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=',
30			threshold: 200
31		};
32
33		var defaultErrorMessage = 'Unexpected server response received. Please contact support.';
34		if (pageContext && pageContext['server_error']) {
35			defaultErrorMessage = pageContext['server_error'];
36		}
37
38		var listNonCachableBlocks = {
39			'list_videos_my_favourite_videos': 1,
40			'list_videos_my_uploaded_videos': 1,
41			'list_albums_my_favourite_albums': 1,
42			'list_albums_my_created_albums': 1,
43			'list_playlists_my_created_playlists': 1,
44			'list_dvds_my_created_channels': 1,
45			'list_videos_my_channel_videos': 1,
46			'list_members_subscriptions_my_subscriptions': 1,
47			'list_videos_videos_from_my_subscriptions': 1,
48			'list_albums_albums_from_my_subscriptions': 1,
49			'list_videos_my_purchased_videos': 1,
50			'list_albums_my_purchased_albums': 1,
51			'list_members_my_conversations': 1,
52			'list_members_my_friends': 1,
53			'list_messages_my_conversation_messages': 1
54		};
55
56		var utilitiesMergeOptions = function(def, contextKey) {
57			if (pageContext && pageContext[contextKey]) {
58				for (var prop in pageContext[contextKey]) {
59					if (pageContext[contextKey].hasOwnProperty(prop)) {
60						def[prop] = pageContext[contextKey][prop];
61					}
62				}
63			}
64			return def;
65		};
66
67		var utilitiesLoadSmileys = function($container) {
68			$container.find('img[data-src]').each(function () {
69				var originalSrc = $(this).attr('data-src');
70				if (originalSrc) {
71					this.src = originalSrc;
72					$(this).removeAttr('data-src');
73				}
74			});
75		};
76
77		var utilitiesScrollTo = function($obj, speed) {
78			if (typeof speed == 'undefined') {
79				speed = animationSpeed;
80			}
81			if ($obj.exists()) {
82				var windowTop = $(document).scrollTop();
83				var windowBottom = windowTop + $(window).height();
84				var objectTop = $obj.offset().top;
85				if (objectTop > windowTop && objectTop < windowBottom) {
86					return;
87				}
88			}
89			$.scrollTo($obj, speed, {offset: -100});
90		};
91
92		var utilitiesCountFormat = function(str, token, number) {
93			if (!str || !token) {
94				return '';
95			}
96			number = parseInt(number) || 0;
97			str = str.replace(/\[count](.*?)\[\/count]/gi, function(match, p1) {
98				if (match.indexOf(token) < 0) {
99					return match;
100				}
101				var defaultValue = '';
102				var values = p1.split('||');
103				for (var i = 0; i < values.length; i++) {
104					var temp = values[i].split(':', 2);
105					if (temp.length == 1) {
106						defaultValue = temp[0].trim();
107					} else {
108						var compareExamples = temp[0].split(',');
109						for (var j = 0; j < compareExamples.length; j++) {
110							var compareExample = compareExamples[j].trim();
111							if (compareExample.indexOf('//') == 0) {
112								if (number % 100 == parseInt(compareExample.substring(2))) {
113									return temp[1].trim().replace(token, '' + number);
114								}
115							} else if (compareExample.indexOf('/') == 0) {
116								if (number % 10 == parseInt(compareExample.substring(1))) {
117									return temp[1].trim().replace(token, '' + number);
118								}
119							} else if (number == parseInt(temp[0].trim())) {
120								return temp[1].trim().replace(token, '' + number);
121							}
122						}
123					}
124				}
125				return defaultValue;
126			}).replace(token, '' + number);
127			return str;
128		};
129
130		var utilitiesParseParameters = function(str) {
131			var result = {};
132			if (str) {
133				var params = str.split(';');
134				for (var i = 0; i < params.length; i++) {
135					var pair = params[i].split(':');
136					if (pair.length == 2) {
137						var paramNames = pair[0].split('+');
138						for (var j = 0; j < paramNames.length; j++) {
139							result[paramNames[j]] = decodeURIComponent(pair[1]).replace(/[+]/g,' ');
140						}
141					}
142				}
143			}
144			return result;
145		};
146
147		var utilitiesGetBlock = function (blockId, sender, args, params) {
148			var url = (args.url ? args.url : window.location.href);
149			if (url.indexOf('#') > 0) {
150				url = url.substring(0, url.indexOf('#'));
151			}
152			$.ajax({
153				url: url + (url.indexOf('?') >= 0 ? '&' : '?') + 'mode=async&function=get_block&block_id=' + blockId + (params ? '&' + $.param(params) : ''),
154				type: 'GET',
155				cache: false,
156				beforeSend: function () {
157					$(sender).block({message: null});
158					if (args.beforeSend) {
159						args.beforeSend(sender);
160					}
161				},
162				complete: function () {
163					$(sender).unblock();
164					if (args.complete) {
165						args.complete(sender);
166					}
167				},
168				success: function (html) {
169					storage[blockId] = params;
170					if (args.success) {
171						args.success(sender, html);
172					}
173				},
174				error: function () {
175					if (args.error) {
176						args.error(sender);
177					}
178				}
179			});
180		};
181
182		var utilitiesAjaxRequest = function(sender, params, successCallback) {
183			var url = window.location.href;
184			if (url.indexOf('#') > 0) {
185				url = url.substring(0, url.indexOf('#'));
186			}
187			$.ajax({
188				url: url + (url.indexOf('?') >= 0 ? '&' : '?') + 'mode=async&format=json&' + $.param(params),
189				type: 'GET',
190				beforeSend: function () {
191					$(sender).block({message: null});
192				},
193				complete: function () {
194					$(sender).unblock();
195				},
196				success: function (json) {
197					if (typeof json != 'object') {
198						json = JSON.parse(json);
199					}
200					if (json && successCallback) {
201						successCallback(json);
202					}
203				}
204			});
205		};
206
207		var utilitiesRecaptcha = function($container) {
208			if (!$container) {
209				$container = $(document);
210			}
211			if (typeof grecaptcha == 'object') {
212				$container.find('[data-recaptcha-key]').each(function() {
213					var $outer = $(this);
214					if (!$outer.attr('data-recaptcha-id')) {
215						$outer.html('');
216						var recaptchaId = grecaptcha.render($outer.get(0), {
217							sitekey: $outer.attr('data-recaptcha-key'),
218							theme: $outer.attr('data-recaptcha-theme') || 'light',
219							size: $outer.attr('data-recaptcha-size') || 'normal',
220							callback: function() {
221								var $errorContainer = $outer.parent().find('.field-error');
222								$errorContainer.fadeOut();
223								$outer.parent().find('.error').removeClass('error');
224							}
225						});
226						$outer.attr('data-recaptcha-id', recaptchaId);
227					}
228				});
229			}
230		};
231
232		var utilitiesAjaxForm = function($form, callbacks, withCredentials) {
233			var considerFormBlocking = function($form, isBlock) {
234				var $popupParent = $form.parents('.popup-holder');
235				if ($popupParent.exists()) {
236					$form = $popupParent;
237				}
238				isBlock ? $form.block({ message: null }) : $form.unblock();
239			};
240
241			$form.kvsProcessFormErrors = function(response) {
242				for (var i = 0; i < response['errors'].length; i++) {
243					var error = response['errors'][i];
244
245					var fieldName = error['field'];
246					var errorCode = error['code'];
247					var errorMessage = error['message'];
248
249					var $errorContainer = null;
250					if (fieldName) {
251						var $field = $form.find('[name="' + fieldName + '"]');
252						if ($field.length > 1) {
253							$field = $form.find('[data-name="' + fieldName + '"]');
254						}
255						if (!$field.exists()) {
256							$field = $form.find('[data-name="' + fieldName + '"] [type="text"]');
257						}
258						if (!$field.exists()) {
259							$field = $form.find('[data-name="' + fieldName + '"] select');
260						}
261						if (!$field.exists()) {
262							$field = $form.find('[data-name="' + fieldName + '"]');
263						}
264						if ($field.exists()) {
265							$field.addClass('error');
266							$field.parents('.file-control').find('[type="text"]').addClass('error');
267							$errorContainer = $field.parent().find('.field-error');
268							if (!$errorContainer.exists()) {
269								var fieldTitle = $field.parent().find('label').text();
270								if (fieldTitle) {
271									errorMessage += ' (' + fieldTitle + ')';
272								}
273							}
274							if (i==0) {
275								$field.focus();
276							}
277						} else {
278							errorMessage += ' (' + fieldName + ')';
279						}
280					}
281					if (!$errorContainer || !$errorContainer.exists()) {
282						$errorContainer = $form.find('.generic-error');
283					}
284
285					$errorContainer.empty().html(errorMessage).fadeIn();
286
287					if (fieldName == 'code' && errorCode != 'required') {
288						var $captcha = $form.find('.captcha-control img');
289						if ($captcha.exists()) {
290							$captcha.attr('src', $captcha.attr('src').replace(new RegExp('rand=\\d+'),'rand=' + new Date().getTime()));
291							$form.find('.captcha-control .textfield').val('');
292						}
293					}
294				}
295
296				if (typeof grecaptcha == 'object') {
297					$form.find('[data-recaptcha-key]').each(function() {
298						var recaptchaId = $(this).attr('data-recaptcha-id');
299						if (recaptchaId) {
300							if (grecaptcha.getResponse(recaptchaId)) {
301								grecaptcha.reset(recaptchaId);
302							}
303						}
304					});
305				}
306
307				if (callbacks && callbacks['error']) {
308					callbacks['error']($form);
309				}
310				utilitiesScrollTo($form, 0);
311				return $form;
312			};
313
314			$form.ajaxForm({
315				data: {
316					format: 'json',
317					mode: 'async'
318				},
319
320				xhrFields: {
321					withCredentials: !!withCredentials
322				},
323
324				beforeSerialize: function () {
325					var $autoPopulates = $form.find('[data-form-populate-from]');
326					$autoPopulates.each(function() {
327						var populateFromName = $(this).attr('data-form-populate-from');
328						if (populateFromName) {
329							var $populateFrom = $form.find('[name="' + populateFromName + '"]');
330							if ($populateFrom.exists()) {
331								$(this).val($populateFrom.val());
332							}
333						}
334					});
335					if (callbacks && callbacks['beforeSerialize']) {
336						callbacks['beforeSerialize']($form);
337					}
338				},
339
340				beforeSubmit: function (data) {
341					var confirmText = $form.attr('data-confirm') || '';
342					if (confirmText && !confirm(confirmText)) {
343						return false;
344					}
345
346					var result = true;
347					if (callbacks && callbacks['beforeSubmit']) {
348						result = callbacks['beforeSubmit']($form, data);
349					}
350					considerFormBlocking($form, result);
351					return result;
352				},
353
354				uploadProgress: function(event, position, total, percent) {
355					if (callbacks && callbacks['uploadProgress']) {
356						callbacks['uploadProgress']($form, percent);
357					}
358				},
359
360				success: function (response, statusText, xhr) {
361					$form.find('.generic-error').empty().hide();
362					considerFormBlocking($form, false);
363
364					if (xhr.getResponseHeader('Content-Type').indexOf('application/json') >= 0) {
365						if (typeof response != 'object') {
366							response = JSON.parse(response);
367						}
368
369						if (response['status'] == 'failure') {
370							$form.kvsProcessFormErrors(response);
371						} else if (response['status'] == 'success') {
372							if (callbacks && callbacks['success']) {
373								callbacks['success']($form, response['data']);
374							} else if (response['redirect']) {
375								window.location = response['redirect'];
376							} else {
377								if ($form.attr('data-success') == 'message' && $form.attr('data-message')) {
378									$.fancybox('<form><div class="success">' + $form.attr('data-message') + '</div></form>', {
379										topRatio: 0.3,
380
381										beforeClose: function() {
382											window.location.reload();
383											return true;
384										}
385									});
386								} else {
387									var $reloader = $('[data-reload-to]');
388									if ($reloader.exists()) {
389										window.location = $reloader.attr('data-reload-to');
390									} else {
391										window.location.reload();
392									}
393								}
394							}
395						} else {
396							$form.find('.generic-error').html(defaultErrorMessage).show();
397							utilitiesScrollTo($form, 0);
398							if (callbacks && callbacks['error']) {
399								callbacks['error']($form);
400							}
401						}
402
403					} else if (xhr.getResponseHeader('Content-Type').indexOf('text/html') >= 0) {
404						if (callbacks && callbacks['success']) {
405							callbacks['success']($form, response);
406						} else {
407							if ($(response).attr('data-fancybox') == 'message' || $(response).find('[data-fancybox="message"]').exists()) {
408								$.fancybox($(response), {
409									topRatio: 0.3,
410
411									beforeClose: function() {
412										var $redirectTo = this.inner.find('[data-fancybox-redirect-to]');
413										if ($redirectTo.exists()) {
414											window.location = $redirectTo.attr('data-fancybox-redirect-to');
415										} else {
416											window.location.reload();
417										}
418										return true;
419									}
420								});
421							} else if ($form.attr('data-success') == 'message' && $form.attr('data-message')) {
422								$.fancybox('<form><div class="success">' + $form.attr('data-message') + '</div></form>', {
423									topRatio: 0.3,
424
425									beforeClose: function() {
426										window.location.reload();
427										return true;
428									}
429								});
430							} else {
431								$form.empty().append(response);
432							}
433						}
434					} else {
435						$form.find('.generic-error').html(defaultErrorMessage).show();
436						utilitiesScrollTo($form, 0);
437						if (callbacks && callbacks['error']) {
438							callbacks['error']($form);
439						}
440					}
441				},
442
443				error: function () {
444					considerFormBlocking($form, false);
445					$form.find('.generic-error').html(defaultErrorMessage).show();
446					utilitiesScrollTo($form, 0);
447					if (callbacks && callbacks['error']) {
448						callbacks['error']($form);
449					}
450				},
451
452				complete: function() {
453					if (callbacks && callbacks['complete']) {
454						callbacks['complete']($form);
455					}
456				}
457			});
458
459			$form.find('input, select, textarea').each(function() {
460				var $field = $(this);
461
462				var hideErrorFunction = function() {
463					var $errorContainer = $field.parent().find('.field-error');
464					$errorContainer.fadeOut();
465					$field.removeClass('error');
466					$field.parents('fieldset').removeClass('error');
467					$field.parents('.file-control').find('[type="text"]').removeClass('error');
468				};
469
470				$field.change(hideErrorFunction);
471				if ($field.get(0).tagName.toLowerCase() == 'textarea' || $field.get(0).type == 'text' || $field.get(0).type == 'password') {
472					$field.keypress(hideErrorFunction);
473				}
474			});
475
476			$form.find('.file-control [type="file"]').change(function() {
477				var $input = $(this);
478				var value = $input.val();
479				if (value.lastIndexOf('/') >= 0) {
480					value = value.substring(value.lastIndexOf('/') + 1);
481				}
482				if (value.lastIndexOf('\\') >= 0) {
483					value = value.substring(value.lastIndexOf('\\') + 1);
484				}
485				var files = $input.prop("files");
486				if (files && files.length > 1) {
487					value = '';
488					for (var i = 0; i < files.length; i++) {
489						if (value) {
490							value += ', ';
491						}
492						if (i >= 3) {
493							value += '...';
494							break;
495						}
496						value += files[i].name;
497					}
498				}
499
500				var $container = $input.parents('.file-control');
501				if ($input.attr('multiple') && (!files || files.length == 1)) {
502					var $clone = $container.clone(true, true);
503					$clone.wrap('<form>').parent('form').trigger('reset');
504					$clone.unwrap();
505					$container.parent().append($clone);
506				}
507				$container.find('[type="text"]').val(($container.find('.button').html() || '') + ' ' + value);
508			});
509
510			$form.find('.list-selector').each(function() {
511				var $container = $(this);
512
513				$container.find('[type="text"]').focus(function() {
514					var $input = $(this);
515					var url = $container.attr('data-selector');
516					var name = $container.attr('data-name');
517					var selected = ($container.attr('data-selected') || '').split(',');
518
519					if (!$container.find('.list-selector-popup').exists()) {
520						if (url && name) {
521							$.ajax({
522								url: url,
523								type: 'GET',
524								beforeSend: function () {
525									$input.block({message: null});
526									$input.css({cursor: 'wait'});
527								},
528								complete: function () {
529									$input.unblock();
530									$input.css({cursor: 'text'});
531								},
532								success: function (html) {
533									var selectedIds = [];
534									var selectedLabels = [];
535									var filterValue = '';
536									var $popupContent = $('<div class="list-selector-popup">' + html + '</div>');
537
538									var $filterInput = $popupContent.find('[name="filter"]');
539									for (var i = 0; i < selected.length; i++) {
540										var id = selected[i].trim();
541										if (id) {
542											var $checkbox = $popupContent.find('input[type="checkbox"][value="' + id + '"],input[type="radio"][value="' + id + '"]');
543											var $label = $popupContent.find('label[for="' + $checkbox.attr('id') + '"]');
544											$checkbox.prop('checked', true);
545											selectedIds.push(id);
546											selectedLabels.push($label.html());
547										}
548									}
549
550									$container.append($popupContent);
551									$popupContent.find('input[type="checkbox"]').click(function() {
552										var $checkbox = $(this);
553										var i = 0;
554										var $label = $popupContent.find('label[for="' + $checkbox.attr('id') + '"]');
555										if ($label.html()) {
556											var value = $checkbox.prop('value');
557											if ($checkbox.prop('checked')) {
558												selectedIds.push(value);
559												selectedLabels.push($label.html());
560												$container.append($('<input type="hidden" name="' + name + '[]" value="' + value + '"/>'))
561											} else {
562												for (i = 0; i < selectedIds.length; i++) {
563													if (selectedIds[i] == value) {
564														selectedIds.splice(i, 1);
565														selectedLabels.splice(i, 1);
566														break;
567													}
568												}
569												$container.find('input[type="hidden"][value="' + value + '"]').remove();
570											}
571											var selectedText = '';
572											for (i = 0; i < selectedLabels.length; i++) {
573												if (selectedText != '') {
574													selectedText += ', ';
575												}
576												selectedText += selectedLabels[i];
577											}
578											$input.prop('value', selectedText);
579											$input.change();
580										}
581									}).focus(function() {
582										$filterInput.focus();
583									});
584
585									$popupContent.find('input[type="radio"]').change(function() {
586										var $checkbox = $(this);
587										var i = 0;
588										var $label = $popupContent.find('label[for="' + $checkbox.attr('id') + '"]');
589										if ($label.html()) {
590											var value = $checkbox.prop('value');
591											if ($checkbox.prop('checked')) {
592												$container.find('input[type="hidden"][name="' + name + '[]"]').remove();
593												selectedIds[0] = value;
594												selectedLabels[0] = $label.html();
595												$container.append($('<input type="hidden" name="' + name + '[]" value="' + value + '"/>'))
596											}
597											var selectedText = selectedLabels[0];
598											$input.prop('value', selectedText);
599											$input.change();
600										}
601									}).focus(function() {
602										$filterInput.focus();
603									});
604
605									$filterInput.focus().keyup(function() {
606										if ($filterInput.val() == filterValue) {
607											return;
608										}
609										filterValue = this.value.toLowerCase();
610
611										$container.find('.item').each(function() {
612											var $item = $(this);
613											if (filterValue == '') {
614												$item.show();
615											} else {
616												$item.toggle($item.find('label').html().toLowerCase().indexOf(filterValue) >= 0);
617											}
618										});
619									});
620
621									$(document).mouseup(function(e) {
622										if (!$container.is(e.target) && $container.has(e.target).length === 0)
623										{
624											$popupContent.hide();
625										}
626									});
627								}
628							});
629						}
630					} else {
631						$container.find('.list-selector-popup').show();
632						$container.find('[name="filter"]').focus();
633					}
634				});
635			});
636
637			$form.find('.smileys-support img').each(function() {
638				$(this).attr('title', $(this).attr('alt'));
639				$(this).click(function() {
640					var $textarea = $(this).parents('.smileys-support').find('textarea');
641					if (!$textarea.exists()) {
642						return;
643					}
644					var textarea = $textarea.get(0);
645					var smiley = $(this).attr('alt');
646
647					if (document.selection) {
648						textarea.focus();
649						var sel = document.selection.createRange();
650						sel.text = smiley;
651						textarea.focus();
652					} else if (textarea.selectionStart || textarea.selectionStart == '0') {
653						var startPos = textarea.selectionStart;
654						var endPos = textarea.selectionEnd;
655						var scrollTop = textarea.scrollTop;
656						textarea.value = textarea.value.substring(0, startPos) + smiley + textarea.value.substring(endPos, textarea.value.length);
657						textarea.focus();
658						textarea.selectionStart = startPos + smiley.length;
659						textarea.selectionEnd = startPos + smiley.length;
660						textarea.scrollTop = scrollTop;
661					} else {
662						textarea.value += smiley;
663						textarea.focus();
664					}
665				});
666			});
667
668			$form.find('[data-expand-id]').click(function() {
669				var $button = $(this);
670				var contentId = $button.attr('data-expand-id');
671				if (contentId) {
672					var $content = $('#' + contentId);
673					if ($button.hasClass('expand')) {
674						$content.slideDown(animationSpeed, function () {
675							$(window).trigger('scroll');
676						});
677						$button.removeClass('expand').addClass('collapse');
678					} else {
679						$content.slideUp(animationSpeed, function () {
680						});
681						$button.removeClass('collapse').addClass('expand');
682					}
683				}
684			});
685
686			$form.find('[data-action="choose"]').each(function() {
687				$(this).click(function() {
688					if ($(this).hasClass('disabled')) {
689						return;
690					}
691
692					var $form = $(this).parents('form');
693					var $radio = $(this).find('input');
694					$form.find('[data-action="choose"] [type="radio"]').prop('checked', false);
695					$radio.prop('checked', true);
696
697					if ($radio.prop('checked')) {
698						$form.find('[data-action="choose"]').removeClass('active');
699						$(this).addClass('active');
700
701						var $captchaControl = $form.find('.captcha-control');
702						if ($captchaControl.exists()) {
703							if ($radio.attr('name') == 'payment_option') {
704								$captchaControl.append($captchaControl.parent().find('[type="submit"]'));
705								$captchaControl.parent().find('label').removeClass('hidden');
706								$captchaControl.removeClass('hidden');
707							} else if ($radio.attr('name') == 'card_package_id') {
708								$captchaControl.parent().append($captchaControl.find('[type="submit"]'));
709								$captchaControl.parent().find('label').addClass('hidden');
710								$captchaControl.addClass('hidden');
711							}
712						}
713					}
714				});
715			});
716
717			if (recaptchaLoaded) {
718				utilitiesRecaptcha($form);
719			}
720		};
721
722		var utilitiesAjaxFancyBox = function ($sender, url, afterShowCallback) {
723			$.fancybox([{href: url, type: 'ajax'}], {
724				afterLoad: function(arg1) {
725					if (arg1 && typeof arg1.content == 'string') {
726						if (arg1.content.indexOf('<body>') >= 0 && arg1.content.indexOf('</body>') >= 0) {
727							window.location = url;
728							return false;
729						}
730					}
731					return true;
732				},
733
734				afterShow: function() {
735					if (!afterShowCallback) {
736						this.inner.find('[data-form="ajax"]').each(function () {
737							utilitiesAjaxForm($(this));
738						});
739						this.inner.find('[data-form="ajax-upload"]').each(function () {
740							initVideoUploadForm($(this));
741						});
742						this.inner.find('[data-fancybox="ajax"]').each(function() {
743							$(this).click(function(e) {
744								e.preventDefault();
745								utilitiesAjaxFancyBox($(this), this.href || $(this).attr('data-href'));
746							});
747						});
748					}
749					utilitiesLoadSmileys(this.inner);
750					if (afterShowCallback) {
751						afterShowCallback.call(this);
752					}
753				},
754
755				beforeClose: function() {
756					if (this.inner.find('[data-fancybox="refresh"]').exists()) {
757						if ($sender && $sender.attr('data-fancybox-refresh-id')) {
758							utilitiesReloadBlock($sender.attr('data-fancybox-refresh-id'), $sender, false, true);
759						} else {
760							window.location.reload();
761						}
762					} else if ($sender && $sender.attr('data-fancybox-refresh-id')) {
763						utilitiesReloadBlock($sender.attr('data-fancybox-refresh-id'), $sender, false, true);
764					}
765					return true;
766				},
767
768				helpers: {
769					overlay: {closeClick: false}
770				},
771
772				type: 'ajax',
773				topRatio: 0.3
774			});
775		};
776
777		var utilitiesReloadBlock = function(blockId, sender, scroll, animate) {
778			if (!blockId) {
779				window.location.reload();
780				return;
781			}
782			var params = null;
783			if (storage[blockId]) {
784				params = storage[blockId];
785			}
786
787			var args = {};
788			args.success = function (sender, html) {
789				storage[blockId] = params;
790				var animationOpacity = 0.1;
791				if (!animate) {
792					animationOpacity = 1;
793				}
794				if (scroll) {
795					utilitiesScrollTo($('#' + blockId));
796				}
797				$('#' + blockId).animate({opacity: animationOpacity}, animationSpeed, function () {
798					var div = document.createElement('div');
799					div.innerHTML = html;
800
801					var content = $(div).children().first();
802					$(content).css('opacity', animationOpacity);
803					$(this).replaceWith(content);
804					$('#' + blockId).animate({opacity: 1}, animationSpeed);
805					initAjaxLists($('#' + blockId));
806
807					if (typeof(Storage) !== 'undefined') {
808						var userId = '';
809						if (pageContext && pageContext['userId']) {
810							userId = pageContext['userId'] + ':';
811						}
812						sessionStorage.setItem(userId + location.href + '#' + blockId, $('#' + blockId).html());
813						sessionStorage.setItem(userId + location.href + '#' + blockId + ':params', JSON.stringify(params));
814					}
815				});
816			};
817
818			var errorTries = 0;
819			args.error = function () {
820				errorTries++;
821				var hasFromParameter = false;
822				for (var paramName in params) {
823					if (params.hasOwnProperty(paramName)) {
824						if (paramName.indexOf('from') == 0 && parseInt(params[paramName])>1) {
825							params[paramName] = parseInt(params[paramName]) - 1;
826							if (errorTries > 1) {
827								params[paramName] = 1;
828							}
829							hasFromParameter = true;
830						}
831					}
832				}
833				if (!hasFromParameter) {
834					params = null;
835				}
836
837				if (errorTries > 1) {
838					delete args.error;
839				}
840
841				utilitiesGetBlock(blockId, sender, args, params);
842			};
843
844			utilitiesGetBlock(blockId, sender, args, params);
845		};
846
847		var initMenu = function () {
848			$('.navigation button').click(function() {
849				$(this).parents('.navigation').toggleClass('open');
850			});
851		};
852
853		var initTabs = function () {
854			var $tabLinks = $('.tabs-menu li a');
855			if ($tabLinks.exists()) {
856				var tabLinks = {};
857				var tabQuery = '';
858				var currentActiveTab = '';
859				$tabLinks.each(function() {
860					if ($(this).attr('href').indexOf('#') == 0) {
861						var tabId = $(this).attr('href');
862						if (!currentActiveTab || tabId == window.location.hash) {
863							currentActiveTab = tabId;
864						}
865						tabLinks[tabId] = $(this);
866						tabQuery += ',' + tabId;
867					}
868				});
869
870				var $tabs = $(tabQuery ? tabQuery.substr(1) : '');
871				$tabs.hide();
872
873				if (currentActiveTab) {
874					// tabLinks[currentActiveTab].addClass('active');
875					// $(currentActiveTab).show();
876				}
877
878				$tabLinks.click(function(e) {
879					if ($(this).attr('href').indexOf('#') == 0) {
880						e.preventDefault();
881						var tabId = $(this).attr('href');
882						$tabLinks.removeClass('active');
883						$tabs.hide();
884						$(tabId).show();
885						if (tabLinks[tabId]) {
886							tabLinks[tabId].addClass('active');
887						}
888
889						$(window).trigger('scroll');
890					}
891				});
892			}
893		};
894
895		var initFancyBox = function () {
896			$('[data-fancybox="ajax"]').each(function() {
897				$(this).click(function(e) {
898					e.preventDefault();
899					utilitiesAjaxFancyBox($(this), this.href || $(this).attr('data-href'));
900				});
901			});
902
903			$('.block-album .images a.item, .block-screenshots a.item, .list-albums-images a, .list-videos-screenshots a').fancybox({
904				openEffect: 'none',
905				closeEffect: 'none',
906				prevEffect: 'none',
907				nextEffect: 'none',
908				helpers: {
909					title: {
910						type: 'inside'
911					},
912					buttons: {
913						position: 'bottom'
914					}
915				}
916			});
917
918			if (window.location.href.indexOf('?login') > 0) {
919				$('#login').click();
920			}
921			if (window.location.href.indexOf('?signup') > 0) {
922				$('#signup').click();
923			}
924		};
925
926		var initRating = function () {
927			var $ratingContainer = $('.rating-container');
928			var $links = $ratingContainer.find('.rate-like, .rate-dislike');
929			$links.click(function(e) {
930				e.preventDefault();
931				var $link = $(this);
932				if ($link.hasClass('disabled') || $link.hasClass('voted')) {
933					return;
934				}
935
936				var vote = parseInt($link.attr('data-vote')) || 0;
937				var videoId = $link.attr('data-video-id');
938				var albumId = $link.attr('data-album-id');
939				var playlistId = $link.attr('data-playlist-id');
940				var postId = $link.attr('data-post-id');
941				var modelId = $link.attr('data-model-id');
942				var csId = $link.attr('data-cs-id');
943				var dvdId = $link.attr('data-dvd-id');
944				var flagId = $link.attr('data-flag-id');
945				if (videoId || albumId || playlistId || modelId || csId || postId || dvdId) {
946					utilitiesAjaxRequest($link, {action: 'rate', video_id: videoId, album_id: albumId, playlist_id: playlistId, model_id: modelId, cs_id: csId, post_id: postId, dvd_id: dvdId, vote: vote}, function(json) {
947						if (json['status']=='success') {
948							$links.addClass('disabled');
949							$link.removeClass('disabled').addClass('voted');
950							$ratingContainer.find('.voters').html($ratingContainer.find('.voters').attr('data-success'));
951
952							var $scale = $ratingContainer.find('.scale');
953							var oldRating = parseFloat($scale.attr('data-rating'));
954							var oldRatingVotes = parseInt($scale.attr('data-votes'));
955							if (oldRatingVotes > 0) {
956								if (oldRating == 0) {
957									oldRatingVotes = 0;
958								}
959								var newRating = (oldRating * oldRatingVotes + vote) / (oldRatingVotes + 1) / 5 * 100;
960								if (newRating > 100) {
961									newRating = 100;
962								}
963								$ratingContainer.find('.scale').css({width: newRating + '%'});
964							}
965						} else {
966							$links.addClass('disabled');
967							$ratingContainer.find('.voters').html($ratingContainer.find('.voters').attr('data-error'));
968						}
969					});
970					if (flagId) {
971						utilitiesAjaxRequest($link, {action: 'flag', video_id: videoId, album_id: albumId, playlist_id: playlistId, postId: postId, dvdId: dvdId, flag_id: flagId}, function() {});
972					}
973				}
974			});
975		};
976
977		var initAddToFavourites = function () {
978			$('.btn-favourites li a').click(function(e) {
979				var $link = $(this);
980				var videoId = $link.attr('data-video-id');
981				var albumId = $link.attr('data-album-id');
982				var favType = $link.attr('data-fav-type') || 0;
983				var createPlaylistUrl = $link.attr('data-create-playlist-url');
984				var playlistId = $link.attr('data-playlist-id') || 0;
985				if ((videoId || albumId)) {
986					e.preventDefault();
987					if ($link.hasClass('delete')) {
988						utilitiesAjaxRequest($link.parents('li'), {action: 'delete_from_favourites', video_id: videoId, album_id: albumId, fav_type: favType, playlist_id: playlistId}, function(json) {
989							if (json['status']=='success') {
990								if (playlistId > 0) {
991									$link.parents('li').addClass('hidden');
992									$link.parents('ul').find('#add_playlist_' + playlistId).removeClass('hidden');
993								} else {
994									$link.parents('li').addClass('hidden');
995									$link.parents('ul').find('#add_fav_' + favType).removeClass('hidden');
996								}
997							}
998						});
999					} else {
1000						if (favType == 10 && !playlistId) {
1001							if (createPlaylistUrl) {
1002								utilitiesAjaxFancyBox($link, createPlaylistUrl, function () {
1003									var $form = this.inner.find('form');
1004									utilitiesAjaxForm($form, {
1005										success: function($form, newPlaylistData) {
1006											$.fancybox.close();
1007
1008											newPlaylistData = $(newPlaylistData);
1009											playlistId = newPlaylistData.attr('data-playlist-id');
1010											var playlistTitle = newPlaylistData.attr('data-playlist-title');
1011
1012											if (playlistId) {
1013												utilitiesAjaxRequest($link.parents('li'), {action: 'add_to_favourites', video_id: videoId, album_id: albumId, fav_type: favType, playlist_id: playlistId}, function(json) {
1014													if (json['status']=='success') {
1015														var $newItem = $link.parents('ul').find('#add_playlist_').clone(true, true);
1016														$newItem.find('a').each(function() {
1017															if ($(this).attr('data-playlist-id')) {
1018																$(this).attr('data-playlist-id', $(this).attr('data-playlist-id').replace('%ID%', playlistId));
1019															}
1020															if ($(this).attr('href')) {
1021																$(this).attr('href', $(this).attr('href').replace('%ID%', playlistId));
1022															}
1023															$(this).html($(this).html().replace('%1%', playlistTitle));
1024														});
1025														$newItem.attr('id', 'add_playlist_' + playlistId);
1026														$newItem.insertBefore($link.parents('li'));
1027														$newItem = $link.parents('ul').find('#delete_playlist_').clone(true, true);
1028														$newItem.find('a').each(function() {
1029															if ($(this).attr('data-playlist-id')) {
1030																$(this).attr('data-playlist-id', $(this).attr('data-playlist-id').replace('%ID%', playlistId));
1031															}
1032															if ($(this).attr('href')) {
1033																$(this).attr('href', $(this).attr('href').replace('%ID%', playlistId));
1034															}
1035															$(this).html($(this).html().replace('%1%', playlistTitle));
1036														});
1037														$newItem.attr('id', 'delete_playlist_' + playlistId);
1038														$newItem.removeClass('hidden');
1039														$newItem.insertBefore($link.parents('li'));
1040													}
1041												});
1042											}
1043										}
1044									});
1045								});
1046							}
1047						} else {
1048							utilitiesAjaxRequest($link.parents('li'), {action: 'add_to_favourites', video_id: videoId, album_id: albumId, fav_type: favType, playlist_id: playlistId}, function(json) {
1049								if (json['status']=='success') {
1050									if (playlistId > 0) {
1051										$link.parents('li').addClass('hidden');
1052										$link.parents('ul').find('#delete_playlist_' + playlistId).removeClass('hidden');
1053									} else {
1054										$link.parents('li').addClass('hidden');
1055										$link.parents('ul').find('#delete_fav_' + favType).removeClass('hidden');
1056									}
1057								}
1058							});
1059						}
1060					}
1061				}
1062			});
1063		};
1064
1065		var initErrorFlaggingForm = function () {
1066			var $blockFlagging = $('.block-flagging');
1067			if ($blockFlagging.exists()) {
1068				var $flaggingForm = $blockFlagging.find('form');
1069				if ($flaggingForm.exists()) {
1070					$flaggingForm.each(function () {
1071						utilitiesAjaxForm($(this), {
1072							success: function($form) {
1073								$form.find('.success').show();
1074								$form.find('.block-radios, .block-textarea').hide();
1075							}
1076						});
1077					});
1078				}
1079			}
1080		};
1081
1082		var initShareForm = function () {
1083			var $blockShare = $('.block-share');
1084			if ($blockShare.exists()) {
1085				if (typeof window['getEmbed'] == 'function') {
1086					$blockShare.find('.embed-code').val(window['getEmbed']());
1087				}
1088				$blockShare.find('.embed-button').click(function (e) {
1089					e.preventDefault();
1090					if (typeof window['getEmbed'] == 'function') {
1091						var embedSize = $(this).attr('data-embed-size');
1092						if (embedSize && embedSize.indexOf('x') > 0) {
1093							var embedWidth = parseInt(embedSize.substr(0, embedSize.indexOf('x')));
1094							var embedHeight = parseInt(embedSize.substr(embedSize.indexOf('x') + 1));
1095							$blockShare.find('.embed-code').val(window['getEmbed'](embedWidth, embedHeight));
1096						}
1097					}
1098				});
1099				$blockShare.find('.embed-code-custom-width, .embed-code-custom-height').on('keyup blur', function () {
1100					var $widthField = $blockShare.find('.embed-code-custom-width');
1101					var $heightField = $blockShare.find('.embed-code-custom-height');
1102					if (parseInt($widthField.val()) && parseInt($heightField.val())) {
1103						$blockShare.find('.embed-code-custom-width-label').html(parseInt($widthField.val()));
1104						$blockShare.find('.embed-code-custom-height-label').html(parseInt($heightField.val()));
1105						$blockShare.find('.embed-button-custom').attr('data-embed-size', parseInt($widthField.val()) + 'x' + parseInt($heightField.val()));
1106					}
1107				});
1108			}
1109		};
1110
1111		var initCommentForm = function () {
1112			var $blockComments = $('.block-comments');
1113			var $blockNewComment = $blockComments.find('.block-new-comment');
1114			if ($blockComments.exists() && $blockNewComment.exists()) {
1115				$blockComments.find('.toggle-button').click(function (e) {
1116					e.preventDefault();
1117					$(this).toggleClass('active');
1118					$blockNewComment.toggle();
1119					$blockComments.find('.success').hide();
1120					if ($blockNewComment.is(':visible')) {
1121						var $captcha = $blockNewComment.find('.captcha-control img');
1122						if ($captcha.exists()) {
1123							if ($captcha.attr('data-src')) {
1124								$captcha.attr('src', $captcha.attr('data-src').replace(new RegExp('rand=\\d+'),'rand=' + new Date().getTime()));
1125							} else {
1126								$captcha.attr('src', $captcha.attr('src').replace(new RegExp('rand=\\d+'),'rand=' + new Date().getTime()));
1127							}
1128						}
1129					}
1130
1131					utilitiesLoadSmileys($blockNewComment);
1132
1133				});
1134
1135				var $commentsForm = $blockComments.find('form');
1136				if ($commentsForm.exists()) {
1137					utilitiesAjaxForm($commentsForm, {
1138						success: function($form, newCommentData) {
1139							var $anonymousUsernameField = $form.find('[name="anonymous_username"]');
1140							var anonymousUsername = $anonymousUsernameField.val();
1141							if (anonymousUsername) {
1142								$.cookie('kt_anonymous_username', anonymousUsername, {path: '/', samesite: 'Lax'});
1143							}
1144
1145							$form.get(0).reset();
1146							$anonymousUsernameField.val(anonymousUsername || '');
1147
1148							var $captcha = $form.find('.captcha-control img');
1149							if ($captcha.exists()) {
1150								$captcha.attr('src', $captcha.attr('src').replace(new RegExp('rand=\\d+'),'rand=' + new Date().getTime()));
1151							}
1152
1153							if (typeof grecaptcha == 'object') {
1154								$form.find('[data-recaptcha-key]').each(function() {
1155									var recaptchaId = $(this).attr('data-recaptcha-id');
1156									if (recaptchaId) {
1157										grecaptcha.reset(recaptchaId);
1158									}
1159								});
1160							}
1161
1162							if ($blockComments.find('.toggle-button').exists())
1163							{
1164								$blockNewComment.hide();
1165								$blockComments.find('.toggle-button').removeClass('active');
1166							}
1167
1168							var commentsBlockId = $blockComments.attr('data-block-id');
1169							var $commentsList = $('.list-comments');
1170							if (newCommentData && newCommentData['approved'] && commentsBlockId && $commentsList.exists()) {
1171								var args = {
1172									success: function(sender, html) {
1173										if (typeof(Storage) !== 'undefined') {
1174											var userId = '';
1175											if (pageContext && pageContext['userId']) {
1176												userId = pageContext['userId'] + ':';
1177											}
1178											sessionStorage.removeItem(userId + location.href + '#' + commentsBlockId);
1179											sessionStorage.removeItem(userId + location.href + '#' + commentsBlockId + ':params');
1180										}
1181
1182										var resultElement = document.createElement('DIV');
1183										resultElement.innerHTML = html;
1184
1185										var $newItem = $(resultElement).find('.item[data-comment-id="' + (newCommentData['comment_id'] || newCommentData['entry_id']) + '"]').addClass('hidden');
1186										$commentsList.find('#' + commentsBlockId + '_items').prepend($newItem);
1187
1188										setTimeout(function() {
1189											$commentsList.show();
1190											$newItem.fadeIn();
1191										}, 200);
1192									}
1193								};
1194								utilitiesGetBlock(commentsBlockId, null, args);
1195							} else {
1196								$commentsForm.find('.success').show();
1197							}
1198						}
1199					});
1200				}
1201
1202				$commentsForm.find('[name="anonymous_username"]').val($.cookie('kt_anonymous_username') || '');
1203			}
1204		};
1205
1206		var initCommentActions = function () {
1207			$('.list-comments').on('click', '.comment-options a', function(e) {
1208				var $link = $(this);
1209				var $item = $(this).parents('.item');
1210				var $container = $(this).parents('.comment-options');
1211				var $rating = $container.find('.comment-rating');
1212				var $ratingLinks = $container.find('.comment-like, .comment-dislike');
1213				var commentId = $item.attr('data-comment-id');
1214
1215				if (($link.hasClass('comment-like') || $link.hasClass('comment-dislike'))) {
1216					e.preventDefault();
1217					if ($link.hasClass('disabled')) {
1218						return;
1219					}
1220					var increment = ($link.hasClass('comment-dislike') ? -1 : 1);
1221					utilitiesAjaxRequest($link, {action: 'vote_comment', vote: increment, comment_id: commentId}, function(json) {
1222						if (json['status'] == 'success') {
1223							$ratingLinks.fadeOut();
1224							if ($rating.exists()) {
1225								var ratingValue = parseInt($rating.html());
1226								if (!isNaN(ratingValue)) {
1227									ratingValue += increment;
1228									$rating.html(ratingValue);
1229									if (ratingValue > 0) {
1230										$rating.addClass('positive');
1231									} else if (ratingValue < 0) {
1232										$rating.addClass('negative');
1233										$item.addClass('dim-comment');
1234									} else if (ratingValue == 0) {
1235										$rating.removeClass('positive').removeClass('negative');
1236										$item.removeClass('dim-comment');
1237									}
1238								}
1239							}
1240						} else {
1241							$ratingLinks.addClass('disabled');
1242						}
1243					});
1244				} else if ($link.hasClass('comment-edit')) {
1245					e.preventDefault();
1246					$.fancybox($('.popup-edit-comment').clone(true, true), {
1247						afterShow: function () {
1248							var $form = this.inner.find('form');
1249							$form.find('[name="comment_id"], [name="entry_id"]').val(commentId);
1250
1251							var originalText = $item.find('.original-text').html() || '';
1252							originalText = originalText.replace(/<br>/gi, '\n').replace(/&gt;/gi, '>').replace(/&lt;/gi, '<').replace(/&#34;/gi, '"');
1253							originalText = originalText.replace(/<img.*?alt=['"](.*?)['"].*?>/gi, '$1');
1254							$form.find('[name="comment"], [name="entry"]').val(originalText);
1255
1256							utilitiesAjaxForm($form, {
1257								success: function() {
1258									$.fancybox.close();
1259									var $blockComments = $('.block-comments');
1260									var commentsBlockId = $blockComments.attr('data-block-id');
1261									if (commentsBlockId) {
1262										var args = {
1263											success: function(sender, html) {
1264												if (typeof(Storage) !== 'undefined') {
1265													var userId = '';
1266													if (pageContext && pageContext['userId']) {
1267														userId = pageContext['userId'] + ':';
1268													}
1269													sessionStorage.removeItem(userId + location.href + '#' + commentsBlockId);
1270													sessionStorage.removeItem(userId + location.href + '#' + commentsBlockId + ':params');
1271												}
1272
1273												var resultElement = document.createElement('DIV');
1274												resultElement.innerHTML = html;
1275
1276												var newCommentText = $(resultElement).find('.item[data-comment-id="' + commentId + '"] .comment-text').html() || '';
1277												$item.find('.comment-text').html(newCommentText);
1278											}
1279										};
1280										utilitiesGetBlock(commentsBlockId, null, args);
1281									}
1282								}
1283							});
1284							utilitiesLoadSmileys(this.inner);
1285						},
1286
1287						helpers: {
1288							overlay: {closeClick: false}
1289						},
1290
1291						topRatio: 0.3
1292					});
1293				}
1294			});
1295		};
1296
1297		var initAjaxLists = function ($container) {
1298			if (!$container) {
1299				$container = $(document);
1300
1301				if (typeof(Storage) !== 'undefined') {
1302					var ajaxIds = {};
1303					$container.find('[data-action="ajax"]').each(function() {
1304						var id = $(this).attr('data-block-id');
1305						if (!ajaxIds[id]) {
1306							ajaxIds[id] = true;
1307						}
1308					});
1309
1310					var userId = '';
1311					if (pageContext && pageContext['userId']) {
1312						userId = pageContext['userId'] + ':';
1313					}
1314
1315					for (var blockId in ajaxIds) {
1316						if (ajaxIds.hasOwnProperty(blockId)) {
1317							var html = sessionStorage.getItem(userId + location.href + '#' + blockId);
1318							if (!html) {
1319								html = sessionStorage.getItem(location.href + '#' + blockId);
1320							}
1321							if (html) {
1322								$('#' + blockId).html(html).find('[data-fancybox="ajax"]').each(function() {
1323									$(this).click(function(e) {
1324										e.preventDefault();
1325										utilitiesAjaxFancyBox($(this), this.href || $(this).attr('data-href'));
1326									});
1327								});
1328							}
1329							var params = sessionStorage.getItem(userId + location.href + '#' + blockId + ':params');
1330							if (!params) {
1331								params = sessionStorage.getItem(location.href + '#' + blockId + ':params');
1332							}
1333							if (params) {
1334								try {
1335									storage[blockId] = JSON.parse(params);
1336								} catch (e) {}
1337
1338								if (listNonCachableBlocks[blockId]) {
1339									$('#' + blockId).find('img.lazy-load').removeClass('lazy-load');
1340									utilitiesReloadBlock(blockId, blockId, false, false);
1341								}
1342							}
1343						}
1344					}
1345				}
1346			} else {
1347				$container.find('[data-fancybox="ajax"]').each(function() {
1348					$(this).click(function(e) {
1349						e.preventDefault();
1350						utilitiesAjaxFancyBox($(this), this.href || $(this).attr('data-href'));
1351					});
1352				});
1353			}
1354
1355			if ($.fn.Lazy) {
1356				var webP = new Image();
1357				webP.onload = webP.onerror = function() {
1358					if (webP.height == 2) {
1359						$container.find('img.lazy-load[data-webp]').each(function () {
1360							$(this).attr('data-original', $(this).attr('data-webp'));
1361						});
1362					}
1363
1364					$container.find('img.lazy-load').Lazy(utilitiesMergeOptions(lazyLoadDefOptions, 'lazyload'));
1365				};
1366				webP.src = 'data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA';
1367			}
1368
1369			if ($.fn.thumbs) {
1370				$container.find('img[data-cnt]').thumbs();
1371			}
1372			if ($.fn.videopreview) {
1373				$container.find('img[data-preview]').videopreview();
1374			}
1375
1376			$container.find('[data-action="ajax"], [data-action="inputpage"]').on('click keydown', function (e) {
1377				if (e.type == 'click') {
1378					e.preventDefault();
1379				}
1380
1381				var args = {};
1382				var $sender = $(this);
1383				var appendTo = $sender.attr('data-append-items-to');
1384				var maxQueries = parseInt($sender.attr('data-max-queries')) || 0;
1385
1386				var blockId = $sender.attr('data-block-id');
1387				if (!blockId) {
1388					return;
1389				}
1390				var containerId = $sender.attr('data-container-id');
1391
1392				if (maxQueries && appendTo) {
1393					var currentQueries = parseInt($('#' + appendTo).attr('data-current-queries')) || 0;
1394					if (currentQueries < maxQueries) {
1395						currentQueries++;
1396						if (currentQueries == maxQueries) {
1397							$('#' + containerId).remove();
1398						} else {
1399							$('#' + appendTo).attr('data-current-queries', currentQueries);
1400						}
1401					} else {
1402						return;
1403					}
1404				}
1405
1406				var params = utilitiesParseParameters($sender.attr('data-parameters'));
1407
1408				if ($sender.is('input')) {
1409					if (e.type == 'click') {
1410						return;
1411					}
1412					if (e.keyCode != 13 && e.key != 'Enter' && e.key != 'enter') {
1413						return;
1414					}
1415					var paginationVar = $sender.attr('data-pagination-var');
1416					var paginationValue = parseInt($sender.val());
1417					if (!paginationVar || !paginationValue) {
1418						return;
1419					}
1420					params[paginationVar] = paginationValue;
1421				}
1422
1423				var userId = '';
1424				if (pageContext && pageContext['userId']) {
1425					userId = pageContext['userId'] + ':';
1426				}
1427
1428				args.success = function (sender, html) {
1429					if (appendTo) {
1430						var resultElement = document.createElement('DIV');
1431						resultElement.innerHTML = html;
1432
1433						if (containerId) {
1434							var $newContainer = $(resultElement).find('#' + containerId);
1435							if ($newContainer.exists()) {
1436								$('#' + containerId).replaceWith($newContainer);
1437								initAjaxLists($newContainer);
1438							} else {
1439								$('#' + containerId).remove();
1440							}
1441						}
1442
1443						var $itemsToAppend = $(resultElement).find('#' + appendTo + ' .item');
1444						$itemsToAppend.css({display: 'none'});
1445						if ($('#' + appendTo).attr('data-append-to-beginning') == 'true') {
1446							$itemsToAppend.insertBefore($('#' + appendTo).find('.item').first());
1447						} else {
1448							$itemsToAppend.insertAfter($('#' + appendTo).find('.item').last());
1449						}
1450						$itemsToAppend.fadeIn().promise().done(function () {
1451							for (var paramName in params) {
1452								if (params.hasOwnProperty(paramName)) {
1453									if (paramName.indexOf('from') == 0 && parseInt(params[paramName])>1) {
1454										delete params[paramName];
1455										break;
1456									}
1457								}
1458							}
1459							if (!listNonCachableBlocks[blockId]) {
1460								if (typeof(Storage) !== 'undefined') {
1461									sessionStorage.setItem(userId + location.href + '#' + blockId, $('#' + blockId).html());
1462									sessionStorage.setItem(userId + location.href + '#' + blockId + ':params', JSON.stringify(params));
1463								}
1464							}
1465						});
1466						initAjaxLists($itemsToAppend);
1467
1468					} else {
1469						utilitiesScrollTo($('#' + blockId));
1470						$('#' + blockId).animate({opacity: 0.1}, animationSpeed, function () {
1471							var div = document.createElement('div');
1472							div.innerHTML = html;
1473
1474							var content = $(div).find('#' + blockId);
1475							$(content).css('opacity', '0.1');
1476							$(this).replaceWith(content);
1477							$('#' + blockId).animate({opacity: 1}, animationSpeed);
1478							initAjaxLists($('#' + blockId));
1479
1480							if (typeof(Storage) !== 'undefined') {
1481								sessionStorage.setItem(userId + location.href + '#' + blockId, $('#' + blockId).html());
1482								sessionStorage.setItem(userId + location.href + '#' + blockId + ':params', JSON.stringify(params));
1483							}
1484						});
1485					}
1486				};
1487
1488				utilitiesGetBlock(blockId, containerId ? $('#' + containerId) : $sender, args, params);
1489			});
1490
1491			$container.find('[data-rt]').mousedown(function() {
1492				var rotatorParams = $(this).attr('data-rt');
1493				if (rotatorParams) {
1494					var url = window.location.href;
1495					if (url.indexOf('#') > 0) {
1496						url = url.substring(0, url.indexOf('#'));
1497					}
1498					var img = new Image();
1499					img.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'mode=async&action=rotator_videos&pqr=' + rotatorParams;
1500					$(this).attr('data-rt', '');
1501				}
1502			});
1503
1504			$container.find('[data-playlist-item]').click(function(e) {
1505				e.preventDefault();
1506
1507				$container.find('[data-playlist-item]').removeClass('selected');
1508
1509				var $item = $(this);
1510				$item.addClass('selected');
1511
1512				var playlistItemUrl = $item.attr('data-playlist-item');
1513				if (playlistItemUrl) {
1514					storage['playlist_state'] = playlistItemUrl;
1515
1516					var args = {};
1517					args.url = playlistItemUrl;
1518					args.success = function (sender, html) {
1519						$('.player').html('').append($(html.trim()).find('.player-holder'));
1520						$('.player-holder').find('[data-fancybox="ajax"]').each(function() {
1521							$(this).click(function(e) {
1522								e.preventDefault();
1523								utilitiesAjaxFancyBox($(this), this.href || $(this).attr('data-href'));
1524							});
1525						});
1526						$('.player-holder').find('[data-form="ajax"]').each(function () {
1527							utilitiesAjaxForm($(this));
1528						});
1529						setTimeout(function() {
1530							utilitiesScrollTo($('.player'), 0);
1531						}, 0);
1532					};
1533					utilitiesGetBlock('video_view_video_view', $item, args);
1534				}
1535			});
1536			if (!storage['playlist_state']) {
1537				var $defaultItem = $container.find('[data-playlist-item]').first();
1538				if ($defaultItem.exists()) {
1539					$defaultItem.addClass('selected').click();
1540				}
1541			} else {
1542				$container.find('[data-playlist-item]').each(function() {
1543					if ($(this).attr('data-playlist-item') == storage['playlist_state']) {
1544						$(this).addClass('selected');
1545					}
1546				});
1547			}
1548
1549			$container.find('[data-fav-video-id]').click(function(e) {
1550				e.preventDefault();
1551				e.stopPropagation();
1552
1553				var $link = $(this);
1554				var videoId = $link.attr('data-fav-video-id');
1555				var favType = $link.attr('data-fav-type') || 0;
1556				utilitiesAjaxRequest($link, {action: 'add_to_favourites', video_id: videoId, video_ids: [videoId], fav_type: favType, playlist_id: 0}, function(json) {
1557					if (json['status'] == 'failure' && json['errors'] && json['errors'][0] && json['errors'][0]['code'] == 'not_logged_in') {
1558						if (pageContext && pageContext['loginUrl']) {
1559							utilitiesAjaxFancyBox($link, pageContext['loginUrl']);
1560						}
1561					} else {
1562						$link.addClass('fixed');
1563					}
1564				});
1565			});
1566			$container.find('[data-fav-album-id]').click(function(e) {
1567				e.preventDefault();
1568				e.stopPropagation();
1569
1570				var $link = $(this);
1571				var albumId = $link.attr('data-fav-album-id');
1572				var favType = $link.attr('data-fav-type') || 0;
1573				utilitiesAjaxRequest($link, {action: 'add_to_favourites', album_id: albumId, album_ids: [albumId], fav_type: favType}, function(json) {
1574					if (json['status'] == 'failure' && json['errors'] && json['errors'][0] && json['errors'][0]['code'] == 'not_logged_in') {
1575						if (pageContext && pageContext['loginUrl']) {
1576							utilitiesAjaxFancyBox($link, pageContext['loginUrl']);
1577						}
1578					} else {
1579						$link.addClass('fixed');
1580					}
1581				});
1582			});
1583
1584			function createDeleteCallback($form, $sender, blockId) {
1585				return function(json) {
1586					if (json['status'] == 'success') {
1587						utilitiesReloadBlock(blockId, $sender, true, true);
1588						if ($form.attr('data-refresh-block-ids')) {
1589							var blockIds = $form.attr('data-refresh-block-ids').split(',');
1590							for (var j = 0; j < blockIds.length; j++) {
1591								utilitiesReloadBlock(blockIds[j], $sender, false, true);
1592							}
1593						} else if ($sender.attr('data-redirect-url')) {
1594							window.location = $sender.attr('data-redirect-url');
1595						}
1596					} else {
1597						for (var i = 0; i < json['errors'].length; i++) {
1598							var error = json['errors'][i];
1599							var errorMessage = error['message'];
1600							if (errorMessage) {
1601								$form.find('.generic-error').empty().html(errorMessage).fadeIn();
1602							}
1603						}
1604						utilitiesScrollTo($('#' + blockId), 0);
1605					}
1606				};
1607			}
1608
1609			$container.find('[data-action="select"]').each(function() {
1610				$(this).click(function(e) {
1611					if ($(this).hasClass('disabled')) {
1612						return;
1613					}
1614
1615					var $form = $(this).parents('form');
1616					var $checkbox = $(this).find('input');
1617					if (!$(e.target).is($checkbox)) {
1618						$checkbox.prop('checked', !$checkbox.prop('checked'));
1619					}
1620
1621					var selectedNumber = parseInt($form.attr('data-selected-cnt')) || 0;
1622					if ($checkbox.prop('checked')) {
1623						$(this).addClass('active');
1624						selectedNumber++;
1625					} else {
1626						$(this).removeClass('active');
1627						selectedNumber = Math.max(selectedNumber - 1, 0);
1628					}
1629					$form.find('input[data-mode="selection"]').prop('disabled', selectedNumber == 0);
1630					$form.find('input[data-action="select_all"]').toggleClass('active', selectedNumber == $form.find('input[type=checkbox]').length - $form.find('input[type=checkbox][disabled]').length);
1631					$form.attr('data-selected-cnt', selectedNumber);
1632				});
1633			});
1634
1635			$container.find('[data-action="choose"]').each(function() {
1636				$(this).click(function() {
1637					if ($(this).hasClass('disabled')) {
1638						return;
1639					}
1640
1641					var $form = $(this).parents('form');
1642					var $radio = $(this).find('input');
1643					$radio.prop('checked', true);
1644
1645					if ($radio.prop('checked')) {
1646						$form.find('[data-action="choose"]').removeClass('active');
1647						$(this).addClass('active');
1648					}
1649				});
1650			});
1651
1652			$container.find('[data-action="delete"]').each(function() {
1653				$(this).click(function(e) {
1654					e.preventDefault();
1655
1656					if ($(this).hasClass('disabled')) {
1657						return;
1658					}
1659
1660					var $form = $(this).parents('form');
1661					var $button = $(this);
1662					var confirmText = $button.attr('data-confirm') || '';
1663					if (!confirmText || confirm(confirmText)) {
1664						var objectId = $button.attr('data-id');
1665						if (!objectId) {
1666							return;
1667						}
1668
1669						var blockId = $form.attr('data-block-id');
1670						var params = utilitiesParseParameters($form.attr('data-parameters'));
1671						params['function'] = 'get_block';
1672						params['block_id'] = blockId;
1673						params['delete'] = [objectId];
1674						utilitiesAjaxRequest($button, params, createDeleteCallback($form, $button, blockId));
1675					}
1676				});
1677			});
1678
1679			$container.find('[data-action="delete_mixed"]').each(function() {
1680				$(this).click(function(e) {
1681					e.preventDefault();
1682
1683					if ($(this).hasClass('disabled')) {
1684						return;
1685					}
1686
1687					var $form = $(this).parents('form');
1688					var $button = $(this);
1689					var confirmText = $button.attr('data-confirm') || '';
1690					if (!confirmText || confirm(confirmText)) {
1691						var videoId = $button.attr('data-video-id');
1692						var albumId = $button.attr('data-album-id');
1693						if (!videoId && !albumId) {
1694							return;
1695						}
1696
1697						var blockId = $form.attr('data-block-id');
1698						var params = utilitiesParseParameters($form.attr('data-parameters'));
1699						params['function'] = 'get_block';
1700						params['block_id'] = blockId;
1701						if (videoId) {
1702							params['delete_video_ids'] = [videoId];
1703						} else if (albumId) {
1704							params['delete_album_ids'] = [albumId];
1705						}
1706						utilitiesAjaxRequest($button, params, createDeleteCallback($form, $button, blockId));
1707					}
1708				});
1709			});
1710
1711			$container.find('form[data-controls]').each(function () {
1712				var $form = $(this);
1713				var blockId = $form.attr('data-block-id');
1714
1715				$form.find('input[type="button"]').each(function() {
1716					$(this).click(function(e) {
1717						e.preventDefault();
1718
1719						var $button = $(this);
1720						var confirmText = $button.attr('data-confirm') || '';
1721						if (confirmText) {
1722							confirmText = utilitiesCountFormat(confirmText, '%1%', parseInt($form.attr('data-selected-cnt')));
1723						}
1724						var params = {};
1725						if (!confirmText || confirm(confirmText)) {
1726							if ($button.attr('data-action') == 'select_all') {
1727								if ($button.hasClass('active')) {
1728									$form.find('input[type=checkbox]').each(function() {
1729										if (this.checked) {
1730											$(this).click();
1731										}
1732									});
1733								} else {
1734									$form.find('input[type=checkbox]').each(function() {
1735										if (!this.checked) {
1736											$(this).click();
1737										}
1738									});
1739								}
1740							} else if ($button.attr('data-action') == 'delete_multi') {
1741								params = utilitiesParseParameters($form.attr('data-parameters'));
1742								params['function'] = 'get_block';
1743								params['block_id'] = blockId;
1744								params['delete'] = [];
1745								$form.find('input[type=checkbox]').each(function() {
1746									if (this.checked) {
1747										params['delete'].push(this.value);
1748									}
1749								});
1750
1751								utilitiesAjaxRequest($button, params, createDeleteCallback($form, $button, blockId));
1752							} else if ($button.attr('data-action') == 'delete_mixed_multi') {
1753								params = utilitiesParseParameters($form.attr('data-parameters'));
1754								params['function'] = 'get_block';
1755								params['block_id'] = blockId;
1756								params['delete_video_ids'] = [];
1757								params['delete_album_ids'] = [];
1758								$form.find('input[type=checkbox]').each(function() {
1759									if (this.checked) {
1760										if (this.name == 'delete_video_ids[]') {
1761											params['delete_video_ids'].push(this.value);
1762										} else if (this.name == 'delete_album_ids[]') {
1763											params['delete_album_ids'].push(this.value);
1764										}
1765									}
1766								});
1767
1768								utilitiesAjaxRequest($button, params, createDeleteCallback($form, $button, blockId));
1769							} else if ($button.attr('data-action') == 'move_multi') {
1770								var playlistSelectorUrl = $button.attr('data-href');
1771								if (playlistSelectorUrl) {
1772									utilitiesAjaxFancyBox($button, playlistSelectorUrl, function () {
1773										var $inner_form = this.inner.find('form');
1774										utilitiesAjaxForm($inner_form, {
1775											beforeSubmit: function($inner_form) {
1776												$.fancybox.close();
1777
1778												var playlistId = parseInt($inner_form.find('[name="playlist_id"]:checked').val());
1779												if (playlistId) {
1780													params = utilitiesParseParameters($form.attr('data-parameters'));
1781													params['function'] = 'get_block';
1782													params['block_id'] = blockId;
1783													params['move_to_playlist_id'] = playlistId;
1784													params['delete'] = [];
1785													$form.find('input[type=checkbox]').each(function() {
1786														if (this.checked) {
1787															params['delete'].push(this.value);
1788														}
1789													});
1790
1791													utilitiesAjaxRequest($button, params, createDeleteCallback($form, $button, blockId));
1792												} else {
1793													var createPlaylistUrl = $inner_form.attr('data-create-playlist-url');
1794													if (createPlaylistUrl) {
1795														utilitiesAjaxFancyBox($button, createPlaylistUrl, function () {
1796															var $inner_form = this.inner.find('form');
1797															utilitiesAjaxForm($inner_form, {
1798																success: function($inner_form, newPlaylistData) {
1799																	$.fancybox.close();
1800
1801																	newPlaylistData = $(newPlaylistData);
1802																	playlistId = newPlaylistData.attr('data-playlist-id');
1803
1804																	if (playlistId) {
1805																		params = utilitiesParseParameters($form.attr('data-parameters'));
1806																		params['function'] = 'get_block';
1807																		params['block_id'] = blockId;
1808																		params['move_to_playlist_id'] = playlistId;
1809																		params['delete'] = [];
1810																		$form.find('input[type=checkbox]').each(function() {
1811																			if (this.checked) {
1812																				params['delete'].push(this.value);
1813																			}
1814																		});
1815
1816																		utilitiesAjaxRequest($button, params, createDeleteCallback($form, $button, blockId));
1817																	}
1818																}
1819															});
1820														});
1821													}
1822												}
1823												return false;
1824											}
1825										});
1826									});
1827								}
1828							} else if ($button.attr('data-action') == 'redirect') {
1829								var redirectUrl = $button.attr('data-redirect-url');
1830								if (!redirectUrl) {
1831									return;
1832								}
1833
1834								window.location = redirectUrl;
1835							} else if ($button.attr('data-action') == 'delete_playlist') {
1836								var playlistId = $button.attr('data-id');
1837								if (!playlistId) {
1838									return;
1839								}
1840
1841								params['action'] = 'delete_playlists';
1842								params['delete'] = [playlistId];
1843								utilitiesAjaxRequest($button, params, createDeleteCallback($form, $button, blockId));
1844							} else if ($button.attr('data-action') == 'delete_dvd') {
1845								var dvdId = $button.attr('data-id');
1846								if (!dvdId) {
1847									return;
1848								}
1849
1850								params['action'] = 'delete_dvds';
1851								params['delete'] = [dvdId];
1852								utilitiesAjaxRequest($button, params, createDeleteCallback($form, $button, blockId));
1853							}
1854						}
1855					});
1856				})
1857			});
1858		};
1859
1860		var initAjaxForms = function () {
1861			$('[data-form="ajax"]').each(function () {
1862				utilitiesAjaxForm($(this));
1863			});
1864		};
1865
1866		var initSubscriptions = function () {
1867			var $btnSubscriptions = $('[data-subscribe-to], [data-unsubscribe-to]');
1868			$btnSubscriptions.click(function(e) {
1869				e.preventDefault();
1870
1871				var $btn = $(this);
1872				if ($btn.hasClass('done')) {
1873					return;
1874				}
1875				var subscriptionTo = $btn.attr('data-subscribe-to') || $btn.attr('data-unsubscribe-to');
1876				var confirmation = $btn.attr('data-confirm');
1877				var subscriptionId = $btn.attr('data-id');
1878				if (subscriptionTo && subscriptionId) {
1879					var params = {action: 'subscribe'};
1880					if (!$btn.attr('data-subscribe-to')) {
1881						params['action'] = 'unsubscribe';
1882					}
1883					if (subscriptionTo == 'category') {
1884						params[params['action'] + '_category_id'] = subscriptionId;
1885					} else if (subscriptionTo == 'model') {
1886						params[params['action'] + '_model_id'] = subscriptionId;
1887					} else if (subscriptionTo == 'content_source') {
1888						params[params['action'] + '_cs_id'] = subscriptionId;
1889					} else if (subscriptionTo == 'user') {
1890						params[params['action'] + '_user_id'] = subscriptionId;
1891					} else if (subscriptionTo == 'playlist') {
1892						params[params['action'] + '_playlist_id'] = subscriptionId;
1893					} else if (subscriptionTo == 'dvd') {
1894						params[params['action'] + '_dvd_id'] = subscriptionId;
1895					}
1896					if (!confirmation || confirm(confirmation)) {
1897						utilitiesAjaxRequest($btn, params, function (json) {
1898							if (json['status'] == 'success') {
1899								$btn.addClass('done');
1900								var $buttonInfo = $btn.parents().first().find('.button-info');
1901								if ($buttonInfo.exists()) {
1902									if (params['action'] == 'subscribe') {
1903										$buttonInfo.html(parseInt($buttonInfo.html()) + 1);
1904									} else {
1905										$buttonInfo.html(parseInt($buttonInfo.html()) - 1);
1906									}
1907								}
1908							}
1909						});
1910					}
1911				}
1912			});
1913		};
1914
1915		var initSearch = function () {
1916			var selectedOptions, userId = '';
1917			if (typeof(Storage) !== 'undefined') {
1918				if (pageContext && pageContext['userId']) {
1919					userId = pageContext['userId'] + ':';
1920				}
1921
1922				selectedOptions = sessionStorage.getItem(userId + location.href + '#search_filter');
1923				if (!selectedOptions) {
1924					selectedOptions = sessionStorage.getItem(location.href + '#search_filter');
1925				}
1926				if (selectedOptions) {
1927					selectedOptions = JSON.parse(selectedOptions);
1928					for (var id in selectedOptions) {
1929						$('#' + id).prop('checked', true);
1930					}
1931					if (!selectedOptions.search_string_filter) {
1932						$('#search_string_filter').prop('checked', false);
1933					}
1934				} else {
1935					selectedOptions = {search_string_filter: true};
1936				}
1937			}
1938
1939			if (typeof $.Autocomplete == 'function' && $.Autocomplete.defaults.serviceUrl) {
1940				$('#search_form input[type="text"]').autocomplete({
1941					paramName: 'q',
1942					onSelect: function(suggestion) {
1943						if (suggestion && suggestion.data && suggestion.data.url) {
1944							window.location = suggestion.data.url;
1945						}
1946					}
1947				});
1948			}
1949
1950			$('#search_form').submit(function(e) {
1951				try {
1952					if (this['q'].value == '') {
1953						this['q'].focus();
1954						e.preventDefault();
1955						return;
1956					}
1957					if ($(this).attr('data-url')) {
1958						var value = this['q'].value.replace(/[-]/g, '[dash]').replace(/[ ]+/g, '-').replace(/[?]/g, '').replace(/[&]/g, '%26').replace(/[?]/g, '%3F').replace(/[/]/g, '%2F').replace(/\[dash\]/g, '--');
1959						window.location = $(this).attr('data-url').replace('%QUERY%', encodeURIComponent(value));
1960						e.preventDefault();
1961					}
1962				} catch (e) {}
1963			});
1964
1965			$('#search_form .search-button').click(function() {
1966				$(this).submit();
1967			});
1968
1969			$('[data-search-filter-ids] input, [data-search-filter-ids] button').click(function() {
1970				var $container = $(this).parents('[data-search-filter-ids]');
1971
1972				if ($(this).prop('type') == 'button' || $(this).prop('tagName').toLowerCase() == 'button') {
1973					$container.find('input[name*="[]"]').each(function () {
1974						var $input = $(this);
1975						$input.prop('checked', false);
1976
1977						if (selectedOptions) {
1978							if ($input.attr('id')) {
1979								if ($input.prop('checked')) {
1980									selectedOptions[$input.attr('id')] = true;
1981								} else {
1982									delete selectedOptions[$input.attr('id')];
1983								}
1984							}
1985							sessionStorage.setItem(userId + location.href + '#search_filter', JSON.stringify(selectedOptions));
1986						}
1987					});
1988				} else {
1989					if (selectedOptions) {
1990						if ($(this).attr('id')) {
1991							if ($(this).prop('checked')) {
1992								selectedOptions[$(this).attr('id')] = true;
1993							} else {
1994								delete selectedOptions[$(this).attr('id')];
1995							}
1996						}
1997						sessionStorage.setItem(userId + location.href + '#search_filter', JSON.stringify(selectedOptions));
1998					}
1999				}
2000
2001				var blockIds = $container.attr('data-search-filter-ids').split(',');
2002
2003				var params = {};
2004				var paramGroups = {};
2005				$container.find('input').each(function () {
2006					var $input = $(this);
2007					if ($input.prop('type') == 'hidden' || ($input.prop('type') == 'checkbox' && $input.prop('checked')) || ($input.prop('type') == 'radio' && $input.prop('checked'))) {
2008						if ($input.prop('name').indexOf('[]') > 0) {
2009							var paramName = $input.prop('name').replace('[]', '');
2010							if ($input.attr('data-group-id')) {
2011								var groupMap = paramGroups[paramName] || {};
2012								var group = groupMap[$input.attr('data-group-id')] || [];
2013								group.push($input.prop('value'));
2014								groupMap[$input.attr('data-group-id')] = group;
2015								paramGroups[paramName] = groupMap;
2016							} else {
2017								params[paramName] = $input.prop('value') + (params[paramName] ? ',' + params[paramName] : '');
2018							}
2019						} else {
2020							params[$input.prop('name')] = $input.prop('value');
2021						}
2022					}
2023				});
2024
2025				for (var groupName in paramGroups) {
2026					if (paramGroups.hasOwnProperty(groupName)) {
2027						var groupedArray = [];
2028						for (var groupId in paramGroups[groupName]) {
2029							if (paramGroups[groupName].hasOwnProperty(groupId)) {
2030								groupedArray.push('(' + paramGroups[groupName][groupId].join(',') + ')');
2031							}
2032						}
2033						params[groupName] = groupedArray.join('|');
2034					}
2035				}
2036
2037
2038				for (var paramName in params) {
2039					if (params.hasOwnProperty(paramName)) {
2040						if (params[paramName] == 'all') {
2041							delete params[paramName];
2042						}
2043					}
2044				}
2045
2046				for (var i = 0; i < blockIds.length; i++) {
2047					storage[blockIds[i]] = params;
2048					utilitiesReloadBlock(blockIds[i], $container, false, true);
2049				}
2050			});
2051		};
2052
2053		var initVideoUploadForm = function($uploadForms) {
2054			if (!$uploadForms) {
2055				$uploadForms = $('[data-form="ajax-upload"]');
2056			}
2057			$uploadForms.each(function () {
2058				var $form = $(this);
2059				var redirectUrl = $form.attr('data-redirect-url');
2060				var continueForm = $form.attr('data-continue-form');
2061				var lastPercent = 0;
2062
2063				var progressFunction = function(percent, uploadData) {
2064					percent = Math.min(parseFloat(percent) || 0, 100);
2065					if (percent > lastPercent) {
2066						$form.addClass('uploading');
2067						if (!$form.find('.progressbar').exists()) {
2068							$form.append($('<div class="progressbar"><div class="progress"></div><div class="text"></div></div>'))
2069						}
2070						$form.find('.progressbar .progress').stop(true, true).animate({width: percent + '%'});
2071						$form.find('.progressbar .text').html(parseInt(percent) + '%');
2072						if (percent > 55) {
2073							$form.find('.progressbar').addClass('half-done');
2074						}
2075						lastPercent = percent;
2076						if (percent != 100 && continueForm) {
2077							$('#' + continueForm).show();
2078						}
2079					}
2080
2081					if (uploadData && uploadData['filename']) {
2082						$form.unblock().addClass('uploading-finished');
2083						if (redirectUrl) {
2084							window.location = redirectUrl.replace('%HASH%', uploadData['filename']);
2085						} else if (continueForm) {
2086							var $continueForm = $('#' + continueForm);
2087							$continueForm.show();
2088							$continueForm.find('input[type="submit"]').enable(true);
2089							$continueForm.find('input[name="file"]').val(uploadData['filename'] + '.mp4');
2090							$continueForm.find('input[name="file_hash"]').val(uploadData['filename']);
2091							$continueForm.find('input[name="files"]').val(uploadData['filename']);
2092
2093							var $previewImage = $('[data-preview-src]');
2094							if ($previewImage.exists()) {
2095								$previewImage.attr('src', $previewImage.attr('data-preview-src').replace('%HASH%', uploadData['filename']));
2096							}
2097
2098							var $previewInfo = $('[data-info-src]');
2099							if ($previewInfo.exists()) {
2100								if (uploadData['dimensions'] && uploadData['duration_string'] && uploadData['size_str
2100ing']) {
2101									$previewInfo.html($previewInfo.attr('data-info-src').replace('%1%', uploadData['dimensions'][0] + 'x' + uploadData['dimensions'][1]).replace('%2%', uploadData['duration_string']).replace('%3%', uploadData['size_string']));
2102								}
2103								if (uploadData['files_count'] && uploadData['files_size_string']) {
2104									$previewInfo.html(utilitiesCountFormat(utilitiesCountFormat($previewInfo.attr('data-info-src').replace('%2%', uploadData['files_size_string']), '%1%', uploadData['files_count']), '%3%', uploadData['files_skipped']));
2105								}
2106							}
2107						}
2108					}
2109				};
2110
2111				utilitiesAjaxForm($form, {
2112					success: function($form, uploadData) {
2113						progressFunction(100, uploadData);
2114					},
2115
2116					beforeSerialize: function($form) {
2117						var md5filename = '';
2118						if ($form.find('[name="url"]').val() || $form.find('[name="content"]').val() || $form.find('[name="content[]"]').val() || $form.find('[name="upload_option"]:checked').val() == 'embed') {
2119							for (var i = 0; i < 32; i++) {
2120								md5filename += '' + Math.floor((Math.random() * 10));
2121							}
2122							$form.find('[name="filename"]').val(md5filename);
2123						} else {
2124							$form.find('[name="filename"]').val(md5filename);
2125						}
2126					},
2127
2128					beforeSubmit: function($form) {
2129						lastPercent = 0;
2130
2131						var action = $form.find('[name="action"]').val();
2132						var uploadType = $form.find('[name="upload_option"]:checked').val() || 'file';
2133						var hash = $form.find('[name="filename"]').val();
2134						var $fileInput, files;
2135
2136						if (action == 'upload_files') {
2137							$fileInput = $form.find('[name="content[]"]');
2138							files = [];
2139
2140							var totalsize = 0;
2141							var filesLoaded = 0, sizeLoaded = 0;
2142							$fileInput.each(function() {
2143								for (var i = 0; i < this.files.length; i++) {
2144									files.push(this.files[i]);
2145									totalsize += this.files[i].size || 0;
2146								}
2147							});
2148
2149							var uploadSendFileFunction = function (index) {
2150								if (index - 1 > filesLoaded || index - 1 > files.length) {
2151									return;
2152								}
2153
2154								var data = new FormData();
2155								data.append('filename', hash);
2156								data.append('files', files.length.toString());
2157								data.append('index', index);
2158								if (index > 0) {
2159									data.append('content', files[index - 1]);
2160								}
2161
2162								$.ajax({
2163									type: 'POST',
2164									url: $form.attr('action'),
2165									xhr: function() {
2166										var xhr = new window.XMLHttpRequest();
2167										xhr.withCredentials = true;
2168										xhr.upload.addEventListener('progress', function(event) {
2169											if (event.lengthComputable) {
2170												progressFunction((sizeLoaded + event.loaded) / totalsize * 100);
2171											}
2172										},false);
2173										return xhr;
2174									},
2175
2176									success: function (response) {
2177										if (typeof response != 'object') {
2178											response = JSON.parse(response);
2179										}
2180										if (response['status'] == 'success') {
2181											if (index > 0) {
2182												filesLoaded++;
2183												sizeLoaded += files[index - 1].size || 0;
2184												if (files.length > filesLoaded) {
2185													progressFunction(sizeLoaded / totalsize * 100);
2186													uploadSendFileFunction(filesLoaded + 1);
2187												} else {
2188													progressFunction(100);
2189													uploadSendFileFunction(0);
2190												}
2191											} else {
2192												progressFunction(100, response['data']);
2193											}
2194										} else {
2195											$form.kvsProcessFormErrors(response).removeClass('uploading').unblock().find('.progressbar').hide().remove();
2196										}
2197									},
2198
2199									error: function (xhr) {
2200										if (xhr.status == 0) {
2201											setTimeout(function () {
2202												uploadSendFileFunction(index);
2203											}, 10 * 1000);
2204											return;
2205										}
2206										$form.find('.generic-error').html(defaultErrorMessage).show();
2207										$form.removeClass('uploading').unblock().find('.progressbar').hide().remove();
2208									},
2209
2210									data: data,
2211									processData: false,
2212									contentType: false
2213								});
2214							};
2215
2216							setTimeout(function () {
2217								$form.block({message: null});
2218								uploadSendFileFunction(filesLoaded + 1);
2219							}, 0);
2220							return false;
2221						} else if (action == 'upload_file') {
2222							if (uploadType == 'file') {
2223								$fileInput = $form.find('[name="content"]');
2224								if ($fileInput.exists()) {
2225									files = $fileInput.get(0).files;
2226									if (files && files.length == 1) {
2227										var chunkSize = 9 * 1024 * 1024;
2228										if (pageContext && pageContext['upload_chunk_size']) {
2229											chunkSize = parseInt(pageContext['upload_chunk_size']);
2230										}
2231										var filesize = files[0].size || 0;
2232										var chunks = Math.floor(filesize / chunkSize);
2233										var chunksLoaded = 0;
2234										if (filesize % chunkSize > 0) {
2235											chunks++;
2236										}
2237
2238										var uploadSliceFunction = function (file, start, end) {
2239											var slice = file['mozSlice'] ? file['mozSlice'] : (file['webkitSlice'] ? file['webkitSlice'] : (file['slice'] ? file['slice'] : function () {
2240											}));
2241											return slice.bind(file)(start, end);
2242										};
2243
2244										var uploadSendChunkFunction = function (index) {
2245											if (index - 1 > chunksLoaded) {
2246												return;
2247											}
2248
2249											var data = new FormData();
2250											data.append('filename', hash);
2251											data.append('upload_option', 'file');
2252											data.append('chunks', chunks.toString());
2253											data.append('index', index);
2254											data.append('size', filesize.toString());
2255											if (index > 0) {
2256												data.append('content', uploadSliceFunction(files[0], (index - 1) * chunkSize, Math.min(index * chunkSize, filesize)));
2257											}
2258
2259											$.ajax({
2260												type: 'POST',
2261												url: $form.attr('action'),
2262												xhr: function() {
2263													var xhr = new window.XMLHttpRequest();
2264													xhr.withCredentials = true;
2265													xhr.upload.addEventListener('progress', function(event) {
2266														if (event.lengthComputable) {
2267															progressFunction((chunkSize * chunksLoaded + event.loaded) / filesize * 100);
2268														}
2269													},false);
2270													return xhr;
2271												},
2272
2273												success: function (response) {
2274													if (typeof response != 'object') {
2275														response = JSON.parse(response);
2276													}
2277													if (response['status'] == 'success') {
2278														if (index > 0) {
2279															chunksLoaded++;
2280															if (chunks > chunksLoaded) {
2281																progressFunction((chunkSize * chunksLoaded) / filesize * 100);
2282																uploadSendChunkFunction(chunksLoaded + 1);
2283															} else {
2284																progressFunction(100);
2285																uploadSendChunkFunction(0);
2286															}
2287														} else {
2288															progressFunction(100, response['data']);
2289														}
2290													} else {
2291														$form.kvsProcessFormErrors(response).removeClass('uploading').unblock().find('.progressbar').hide().remove();
2292													}
2293												},
2294
2295												error: function (xhr) {
2296													if (xhr.status == 0) {
2297														setTimeout(function () {
2298															uploadSendChunkFunction(index);
2299														}, 10 * 1000);
2300														return;
2301													}
2302													$form.find('.generic-error').html(defaultErrorMessage).show();
2303													$form.removeClass('uploading').unblock().find('.progressbar').hide().remove();
2304												},
2305
2306												data: data,
2307												processData: false,
2308												contentType: false
2309											});
2310										};
2311
2312										setTimeout(function () {
2313											$form.block({message: null});
2314											uploadSendChunkFunction(chunksLoaded + 1);
2315										}, 0);
2316										return false;
2317									}
2318								}
2319							} else if (uploadType == 'url') {
2320								var $urlInput = $form.find('[name="url"]');
2321								if ($urlInput.exists()) {
2322									var url = $urlInput.val();
2323									if (url) {
2324										var uploadSendUrlFunction = function () {
2325											$.ajax({
2326												type: 'POST',
2327												url: $form.attr('action'),
2328												xhrFields: {
2329													withCredentials: true
2330												},
2331
2332												success: function (response) {
2333													if (typeof response != 'object') {
2334														response = JSON.parse(response);
2335													}
2336													if (response['status'] == 'success') {
2337														if (response['data']['state'] == 'uploading') {
2338															progressFunction(response['data']['percent'], response['data']);
2339															setTimeout(uploadSendUrlFunction, 1000);
2340														} else {
2341															progressFunction(100, response['data']);
2342														}
2343													} else {
2344														$form.kvsProcessFormErrors(response).removeClass('uploading').unblock().find('.progressbar').hide().remove();
2345													}
2346												},
2347
2348												error: function (xhr) {
2349													if (xhr.status == 0) {
2350														setTimeout(function () {
2351															uploadSendUrlFunction();
2352														}, 10 * 1000);
2353														return;
2354													}
2355													$form.find('.generic-error').html(defaultErrorMessage).show();
2356													$form.removeClass('uploading').unblock().find('.progressbar').hide().remove();
2357												},
2358
2359												data: {
2360													upload_option: 'url',
2361													filename: hash,
2362													url: url,
2363													upload_v2: 'true'
2364												}
2365											});
2366										};
2367
2368										setTimeout(function () {
2369											$form.block({message: null});
2370											uploadSendUrlFunction();
2371										}, 0);
2372										return false;
2373									}
2374								}
2375							}
2376						}
2377						return true;
2378					}
2379
2380				}, true);
2381
2382				$form.find('[name="upload_option"]').change(function() {
2383					var $radio = $(this);
2384					if ($radio.prop('checked')) {
2385						var disabledProp = 'disabled';
2386						if ($radio.val() == 'file') {
2387							$form.find('[name="content"]').parents('.file-control').find('input').removeAttr(disabledProp).click();
2388							$form.find('[name="url"]').attr(disabledProp, disabledProp).val('').change();
2389							$form.find('[name="embed"]').attr(disabledProp, disabledProp).val('').change().parents('.row').find('label').removeClass('required');
2390							$form.find('[name="duration"]').attr(disabledProp, disabledProp).val('').change().parents('.row').find('label').removeClass('required');
2391							$form.find('[name="screenshot"]').parents('.file-control').find('input').attr(disabledProp, disabledProp).val('').change().parents('.row').find('label').removeClass('required');
2392						} else if ($radio.val() == 'url') {
2393							$form.find('[name="content"]').parents('.file-control').find('input').attr(disabledProp, disabledProp).val('').change();
2394							$form.find('[name="url"]').removeAttr(disabledProp).focus();
2395							$form.find('[name="embed"]').attr(disabledProp, disabledProp).val('').change().parents('.row').find('label').removeClass('required');
2396							$form.find('[name="duration"]').attr(disabledProp, disabledProp).val('').change().parents('.row').find('label').removeClass('required');
2397							$form.find('[name="screenshot"]').parents('.file-control').find('input').attr(disabledProp, disabledProp).val('').change().parents('.row').find('label').removeClass('required');
2398						} else if ($radio.val() == 'embed') {
2399							$form.find('[name="url"]').attr(disabledProp, disabledProp).val('').change();
2400							$form.find('[name="content"]').parents('.file-control').find('input').attr(disabledProp, disabledProp).val('').change();
2401							$form.find('[name="embed"]').removeAttr(disabledProp).focus().parents('.row').find('label').addClass('required');
2402							$form.find('[name="duration"]').removeAttr(disabledProp).parents('.row').find('label').addClass('required');
2403							$form.find('[name="screenshot"]').parents('.file-control').find('input').removeAttr(disabledProp).parents('.row').find('label').addClass('required');
2404						}
2405					}
2406				});
2407
2408				var params = {mode: 'async', format: 'json', action: $form.find('[name="action"]').val()};
2409				$form.attr('action', ($form.attr('action') || '') + (($form.attr('action') || '').indexOf('?') >=0 ? '&' : '?') + $.param(params));
2410			});
2411		};
2412
2413		var initProfile = function() {
2414			$('[data-action="message"],[data-action="add_to_friends"]').click(function(e) {
2415				e.preventDefault();
2416
2417				var $btn = $(this);
2418				if ($btn.hasClass('done')) {
2419					return;
2420				}
2421
2422				var popupClass = '.popup-send-message';
2423				if ($btn.attr('data-action') == 'add_to_friends') {
2424					popupClass = '.popup-add-to-friends';
2425				}
2426				$.fancybox($(popupClass).clone(true, true), {
2427					afterShow: function () {
2428						var $form = this.inner.find('form');
2429						utilitiesAjaxForm($form, {
2430							success: function() {
2431								$btn.addClass('done');
2432								$.fancybox.close();
2433								if ($btn.attr('data-action') == 'add_to_friends') {
2434									window.location.reload();
2435								}
2436							}
2437						});
2438						utilitiesLoadSmileys(this.inner);
2439					},
2440
2441					helpers: {
2442						overlay: {closeClick: false}
2443					},
2444
2445					topRatio: 0.3
2446				});
2447			});
2448		};
2449
2450		var initMessages = function () {
2451			var $messageForm = $('#send_message_form');
2452			if ($messageForm.exists()) {
2453				utilitiesLoadSmileys($messageForm);
2454				utilitiesAjaxForm($messageForm, {
2455					success: function($form, newMessageData) {
2456						var editing = false;
2457						if ($form.find('[name="message_id"]').val() == newMessageData['message_id']) {
2458							editing = true;
2459						}
2460						$form.get(0).reset();
2461						$form.find('[name="message_id"]').val('');
2462
2463						var messagesBlockId = $form.attr('data-block-id');
2464						var $messagesList = $('.list-messages');
2465						if (newMessageData && messagesBlockId && $messagesList.exists()) {
2466							var args = {
2467								success: function(sender, html) {
2468									var resultElement = document.createElement('DIV');
2469									resultElement.innerHTML = html;
2470
2471									if (editing) {
2472										$messagesList.find('.item[data-message-id="' + newMessageData['message_id'] + '"]').replaceWith($(resultElement).find('.item[data-message-id="' + newMessageData['message_id'] + '"]'));
2473									} else {
2474										var $newItem = $(resultElement).find('.item[data-message-id="' + newMessageData['message_id'] + '"]').addClass('hidden');
2475										$messagesList.find('#' + messagesBlockId + '_items').append($newItem);
2476
2477										setTimeout(function() {
2478											$messagesList.show();
2479											$newItem.fadeIn();
2480										}, 200);
2481									}
2482								}
2483							};
2484							utilitiesGetBlock(messagesBlockId, null, args);
2485						}
2486					}
2487				});
2488			}
2489
2490			$('[data-action="delete_conversation"], [data-action="ignore_conversation"]').click(function(e) {
2491				e.preventDefault();
2492
2493				var $button = $(this);
2494				var confirmText = $button.attr('data-confirm') || '';
2495				if (!confirmText || confirm(confirmText)) {
2496					var userId = $button.attr('data-user-id');
2497					if (!userId) {
2498						return;
2499					}
2500
2501					var blockId = $button.attr('data-block-id');
2502					var params = {};
2503					params['function'] = 'get_block';
2504					params['block_id'] = blockId;
2505					params['action'] = $button.attr('data-action');
2506					params['conversation_user_id'] = userId;
2507					utilitiesAjaxRequest($button, params, function(json) {
2508						if (json['status'] == 'success') {
2509							window.location.reload();
2510						}
2511					});
2512				}
2513			});
2514
2515			$(document).on('click', '.list-messages [data-edit-message-id]', function(e) {
2516				e.preventDefault();
2517
2518				var $button = $(this);
2519				var messageId = $button.attr('data-edit-message-id');
2520				if (!messageId) {
2521					return;
2522				}
2523
2524				var $form = $('#send_message_form');
2525				if ($form.find('[name="message_id"]').val()) {
2526					return;
2527				}
2528				$form.find('[name="message_id"]').val(messageId);
2529				utilitiesScrollTo($form);
2530
2531				var $item = $button.parents('.item[data-message-id="' + messageId + '"]');
2532				$item.addClass('editing');
2533
2534				var originalText = $item.find('.original-text').html() || '';
2535				originalText = originalText.replace(/<br>/gi, '\n').replace(/&gt;/gi, '>').replace(/&lt;/gi, '<').replace(/&#34;/gi, '"');
2536				originalText = originalText.replace(/<img.*?alt=['"](.*?)['"].*?>/gi, '$1');
2537				originalText = originalText.trim();
2538				$form.find('[name="message"]').val(originalText).focus();
2539			});
2540		};
2541
2542		var initStats = function() {
2543			var sendStatsReq = function(action) {
2544				var statsUrl = window.location.href;
2545				if (statsUrl.indexOf('#') > 0) {
2546					statsUrl = statsUrl.substring(0, statsUrl.indexOf('#'));
2547				}
2548				if (statsUrl.indexOf('?') >= 0) {
2549					statsUrl += '&';
2550				} else {
2551					statsUrl += '?';
2552				}
2553
2554				if (action == 'js_stats' && pageContext) {
2555					if (pageContext['disableStats']) {
2556						return;
2557					}
2558					if (pageContext['videoId']) {
2559						statsUrl += 'video_id=' + pageContext['videoId'] + '&';
2560					}
2561					if (pageContext['albumId']) {
2562						statsUrl += 'album_id=' + pageContext['albumId'] + '&';
2563					}
2564				}
2565
2566				var img = new Image();
2567				img.src = statsUrl + 'mode=async&action=' + action + '&rand=' + new Date().getTime();
2568			};
2569
2570			$.cookie('kt_tcookie', '1', {expires: 7, path: '/', samesite: 'Lax'});
2571			if ($.cookie('kt_tcookie') == '1') {
2572				sendStatsReq('js_stats');
2573			}
2574
2575			if (pageContext && pageContext['userId']) {
2576				var reporter = function() {
2577					sendStatsReq('js_online_status');
2578				};
2579				reporter();
2580				setInterval(reporter, 60 * 1000);
2581			}
2582		};
2583
2584		var initAutoscroll = function() {
2585			var $autoscroll = $('[data-autoscroll="true"]');
2586			if ($autoscroll.exists()) {
2587				utilitiesScrollTo($autoscroll.first());
2588			}
2589		};
2590
2591		var initRecaptcha = function() {
2592			$(document).on('recaptchaloaded', function() {
2593				recaptchaLoaded = true;
2594				utilitiesRecaptcha();
2595			});
2596		};
2597
2598		var initMethods = [
2599			initMenu,
2600			initTabs,
2601			initFancyBox,
2602			initRating,
2603			initAddToFavourites,
2604			initErrorFlaggingForm,
2605			initShareForm,
2606			initCommentForm,
2607			initCommentActions,
2608			initAjaxLists,
2609			initAjaxForms,
2610			initSubscriptions,
2611			initSearch,
2612			initVideoUploadForm,
2613			initProfile,
2614			initMessages,
2615			initStats,
2616			initAutoscroll,
2617			initRecaptcha
2618		];
2619
2620		for (var i = 0; i < initMethods.length; i++) {
2621			if (typeof initMethods[i] == 'function') {
2622				try {
2623					initMethods[i].call(this);
2624				} catch (e) {
2625					if (console && console.error) {
2626						console.error(e);
2627					}
2628				}
2629			}
2630		}
2631	})();
2632});

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.