var THEME_DIR = '/wp-content/themes/album2/'; 
var offset = 0;
var type_id = 4;
var level = 0;
var parid = 0;
navlevel = 'allcities';
var page = 0;
var lpage = 0; 
var tpage = 0;	  
var list_page = 0;
var tab = 0;
function setlimit(){
	limit = 12;
   if ($(window).width()>300){
   	limit = 6;
   }
   if ($(window).width()>500){
   	limit = 12; 
   }   
   if ($(window).width()>1024){
   	limit = 16;
   }   	
   if ($(window).width()>1280){
   	limit = 15;
   }
 
}
setlimit();
 
cursor_el = $('.cursor'); 
loaded = false;

var onImgLoad = function(selector, callback){
    $(selector).each(function(){
        if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
            callback.apply(this);
        }
        else {
            $(this).on('load', function(){
                callback.apply(this);
            });
        }
    });
}; 


  var spn = function (scls){
  		$('.spinner').detach();
		spn1 = '<svg viewBox="0 0 50 50" class="spinner">  <circle class="ring" cx="25" cy="25" r="22.5" />  <circle class="line" cx="25" cy="25" r="22.5" /></svg>';
		spn2 = '<svg viewBox="0 0 45 45" class="spinner" style="opacity: 0.5s">  <circle class="ring" cx="25" cy="25" r="22.5" />  <circle class="line" cx="25" cy="25" r="22.5" /></svg>';
		$(scls).append(spn1);     
		$('#deg').change();
	} 

function render() {
	spn('.clubs');
    $.ajax({
        url: '/wp-content/themes/album2/get_all_ids.php',
        type: "POST",
        dataType: 'json',
        data: { id: type_id },
        success: function(ids) {
            window.ids = ids;
            window.ri = 0; 
			
            window.ids_count = ids.length;
            get_clubs(ids[0][0],ids[0][1],true);
			$('#deg').change();
        }
    });
    setTimeout(function(){  $('.spn').detach();},2000);
}
$(document).on( 'click', '.fa-gauge-high', function(){

	render();
});

$(document).on( 'click', '.fa-ruler-horizontal', function(){
	spn('.clubs');
    $.ajax({
        url: '/wp-content/themes/album2/get_all_ids.php',
        type: "POST",
        dataType: 'json',
        data: { id: type_id },
        success: function(ids) {
            window.ids = ids;
            window.ri = 0; 
            $('.spn').detach();
            window.ids_count = ids.length;
            window.ri = 0;
            help_text("Линейный просмотр стелками ← | →");
            window.lineview = true;
           // get_clubs(ids[0][0],ids[0][1],true);
        }
    });
});

$(document).keydown(function(e) {
   	if (window.lineview){
   		ids = window.ids;
	   	if (e.keyCode == 37){   		
	   		window.ri=window.ri-2;  
	   		type_id = ids[window.ri][0];	
	   		get_clubs(ids[window.ri][0],ids[window.ri][1],false);
	   		get_branch(ids[window.ri][1]);
	    	get_selected_level(ids[window.ri][1],ids[window.ri][0]);
			get_select(ids[window.ri][1]);
	   	}

	   	if (e.keyCode == 39){
	 		type_id = ids[window.ri][0];
	   		get_clubs(ids[window.ri][0],ids[window.ri][1],false);
	   		get_branch(ids[window.ri][1]);
	    	get_selected_level(ids[window.ri][1],ids[window.ri][0]);
			get_select(ids[window.ri][1]);
	   	}

	   	updateProgress(window.ri, window.ids_count);
	}
});

function page_update()
{
	var id = type_id;
	var srch = $('.lside input.find').val();
	$('.find').val('');
	
	// вывод клубов 
	if (level >= 0 && level < 4)
	{
		$('.clubs').load( THEME_DIR + 'get_clubs.php', {id: id, start: level, limit: limit} );
	}
	
	// вывод альбомов
	else if (level == 4)
	{
		$('.clubs').load( THEME_DIR + 'get_albums.php', {id: id, limit: limit} );
	}
	
	// вывод фотографий
	else if ((level == 5)||(level == -1))
	{
		//$('.clubs').load( THEME_DIR + 'get_child_photo.php' , {id: id, size: 'medium'} );
		$('.clubs').load('/wp-content/themes/album2/get_child_photo.php', {id: id, size: 'medium'}, function() {
			lazyLoad();
		
			if (typeof myDropzone == 'undefined') {
				myDropzone = new Dropzone(".dropzone", {
					url: "/upload", // Укажите URL для загрузки
					maxFilesize: 6, // MB
					acceptedFiles: "image/*",
					autoProcessQueue: true,
					retryChunks: true,
					retryChunksLimit: 3,
					init: function() {
						this.on("sending", function(file, xhr, formData) { 
							formData.append("name", type_id); // Отправляем данные вместе с файлом
						});
		
						this.on("totaluploadprogress", function(uploadProgress, totalBytesSent) {
							var w = 10 * uploadProgress;
							$('.dz-fullprogress').css('width', w + 'px'); 
						});
		
						this.on("success", function(file, response) {
							post_id = response;
							$('.dz-fullprogress').show('fast');
							
							$.ajax({
								url: '/wp-content/themes/album2/get_photo.php',
								type: "POST",
								dataType: 'json',
								data: {id: post_id},
								success: function(data) {
									$('.dropzone').removeClass('dz-started');
									$('.dz-preview').hide('fast', function() {
										$('.dz-preview').detach();
									});
		
									jQuery.each(data, function(key, val) {
										var imgurl = val;
										imgurl = '<img src="' + imgurl + '">';
										var html = get_album_img(post_id, imgurl, 'pending');
										$(html).insertAfter(".dropzone");  
									});
								}
							});
		
							// Прокрутка страницы вверх
							$('body').scrollTop(0);
						});
		
						this.on("error", function(file, errorMessage) {
							console.log("Ошибка загрузки файла:", errorMessage);
							// Удаляем файл из очереди, чтобы загрузка следующих файлов продолжилась
							this.removeFile(file);
						});
					}
				});
			}
		
			$('#deg').change();
		});
		
		

		
	}
	
	// вывод ленты
	list_page = 0;

	$('.list').load( THEME_DIR + 'get_list.php', {id: id, start: level}, function(){
		$('.breadcrumbs a[data-id=' + id + ']').addClass('bc-activ');
	});
	
	// обновление меню
	if (level < 5)
	{
		$('.select_item').hide();
		$('.select_item[data-level=' + level + '][parid =' + type_id + ']').show();
		$('.select_item[data-level=' + level + '][data-id =' + type_id + ']').addClass('l-active');

		var $el = $(this).parent();
		if ($el.length>0){
		  type_id = $el.attr('id');
		  var preid = $el.attr('data-pid');} 
		
		  var name = $.trim($el.text());
		  var old_level = level;
		  if (old_level == 0)
			  $('.lmenu_item[data-level=' + old_level + ']').removeClass('lmenu-single').addClass('lmenu-first');
			else
			  $('.lmenu_item[data-level=' + old_level + ']').removeClass('lmenu-last').addClass('lmenu-center');
		  
		  level = 4;
		  for (var pi = level; pi > old_level; pi--) {
			  if (i==level){
				$('.lmenu_item[data-level=' + pi + '] span').text(name);
				$('.lmenu_item[data-level=' + pi + ']').attr('id', type_id);
				$('.lmenu_item[data-level=' + pi + ']').addClass('lmenu-last').show();
			  }
			  else {
				$('.lmenu_item[data-level=' + pi + '] span').text($.trim($('.select_item[data-id=' + preid + ']').text()));
				$('.lmenu_item[data-level=' + pi + ']').attr('id', preid);
				$('.lmenu_item[data-level=' + pi + ']').removeClass('lmenu-last').addClass('lmenu-center').show();
				preid = $('.select_item[data-id=' + preid + ']').attr('parid');
			  };
		  };
	}

 
}

function get_selected_level(slevel, ids,clean = false){ 
	 	

		if (slevel<5){
		
			$.get(THEME_DIR + 'get_selected_level.php', {parent_ids: ids, slevel: slevel, typeid: type_id}, function(data){ 
			
				content= data;  
				if (clean){
					$('.select_item[data-pid='+window.create_id+']').detach();
				}
				if ($('.select_item[parid = '+type_id+']').length==0){
			     	$('.select').prepend(data);} 
				if (slevel <= level+1){
					id = '';
					//get_selected_level(slevel+1, '4');
				}
				$('li[parid = '+type_id+']').show();
				update_menu_height();
				$('#deg').change();
				$('.select>div').slideUp('fast').detach(); 

			});
	   
		}

};

function file_exsist(url){ 
 	var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}

function menuUpdate($obj) {
    // Use const for variables that do not change
    const typeId = $obj.attr('id');
    const newLevel = $obj.data('level');

    // Remove classes from all menu items
    $('.lmenu_item').removeClass('lmenu-single lmenu-last lmenu-first lmenu-center');

    let currentId = typeId;

    // Find the parent ID of the current item if the new level is greater than 4
    while (newLevel > 4) {
        const $el = $('.select_item[id="' + currentId + '"]');
        currentId = $el.attr('parid');
    }

    // Update the menu items based on their level
    for (let ui = 4; ui >= 0; ui--) {
        const $menuItems = $('.lmenu_item[data-level=' + ui + ']');
        if (ui > newLevel) {
            $menuItems.hide();
        } else {
            const $el = $('.select_item[id="' + currentId + '"]');
            const name = $el.children('.sm-note').text().trim();
            const parentId = $el.attr('parid');

            if (ui !== 0) {
                $menuItems.attr('id', currentId).data('pid', parentId).find('span').text(name);
            }

            if (ui === newLevel || (ui === 4 && newLevel === 5)) {
                $menuItems.addClass('lmenu-last').show();
            } else if (ui === 0) {
                $menuItems.addClass('lmenu-first').show();
            } else {
                $menuItems.addClass('lmenu-center').show();
            }

            currentId = parentId;
        }
    }

    // Additional logic for level 5
    if (newLevel === 5) {
        $('.select_item').hide();
        const parentId = $('.lmenu-last').attr('id');
        $('.select_item[data-level="' + (newLevel - 1) + '"][parid="' + parentId + '"]').show();
        $('.select_item').removeClass('l-active');
        $('.select_item[data-level="' + (newLevel - 1) + '"][data-id="' + typeId + '"]').addClass('l-active');
    }
}

// получение элементов левой колонки
function get_select(level)
{
	if (level < 5)
	{
		
		$('.select_item').hide();
		$('.select_item[parid =' + type_id + ']').show();

	}
}
//Внутренняя история 
var int_history = [];
	int_history[0]=[4,0,0]; //['type_id','level','parent_id']		 
	window.history.pushState({ 'type_id': 4, 'level': 0,'parid':0,'page':0}, '', './');  
	int_history_index=0;
 
// получение списка клубов
firstload = true;
$(document).on('click', '.help_text', function(){
	help_text_hide();
});

async function get_clubs(id, level, needrender = false) {
    $('.gsearch').hide('fast');
	help_text_hide();
//    $('.dz-fullprogress,.uploadcount').hide();
    if (firstload) {
        $('.clubs').empty();
        dummy = '<div class="club_icon album load_efx"></div>';
        dummy2 = '<div class="club_icon album"></div>';
        for (var ci = 1; ci <= 15; ci++) {
            $('.clubs').append(dummy);
        }
        firstload = false;
    }
    spn('.clubs');
    if (editor && (level >= 3)) {
        add_enable = true;
        //$('.add').slideDown('slow'); //$('.add').css('opacity','1'); $('.addhint').attr('title','Добавить раздел');
    }

    if (editor && (level < 3)) {
        add_enable = false; //$('.add').slideUp('slow'); //$('.add').css('opacity','0.5');  //$('.addhint').attr('title','Зайдите в клуб, чтобы добавить альбом');
    }


    var srch = $('.lside input.find').val();
    $('ul.pnums').show();

    limit = 15;
    try {
        const response = await fetch(THEME_DIR + 'get_clubs.php', {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ id: id, level: level })
        });
        const data = await response.text();

        $('.clubs').html(data);
        imgcentered('.album');
		lazyLoad(); 
        $('h3 span').addClass('dashicons');
        $('h3 span').addClass('dashicons-camera');
		$('#ddeg').change();
        qq = $('.album').length;
        get_pagenav(qq, 0);
        for (var ci = qq; ci < limit; ci++) {
            $('<div class="album_img"></div>').insertBefore(".clubs h3");
        }
        window.ri++;
		$('#deg').change();
        if (needrender===true) {
            id = window.ids[ri]??-1;
			set_rels(id);
            if (id == -1) return
            updateProgress(window.ri, window.ids_count);
            await get_clubs(id[0], id[1], true);
            
        }
    } catch (error) {
        console.error('Ошибка:', error);
    }
}


    var updateProgress = function(current = 0,end = 100) {
    	
    	progress = $(window).width()*0.9/end*current;
        percent = parseFloat((current/end*100).toFixed(3));
    	$('.uploadcount').html('('+current+'/'+end+') '+percent+'%');

    	$('.dz-fullprogress, .uploadcount').show();
		if (percent==100){
			setTimeout(function(){ $('.dz-fullprogress, .uploadcount').hide('fast'); },2000);
		}
        $('.dz-fullprogress').width(progress);
        if (progress >= 100) {
            $('.wfade, .message').hide();
            if (level !== 0) {
                imgcentered('.album');
            }
        }
    };
	async function cash_clubs(x, y, z) {
	
		if (level === 0) {
			window.progress = 0;
			window.progLength = 4;
	
			for (let i = 0; i < window.progLength; i++) {
				await loadClubs(id); // Adjust ID as needed
			}
		} else {
			window.progress = 4;
			window.progLength = 4;
			updateProgress(); // Adjust as necessary
			await get_clubs(type_id, level);// Adjust ID as needed based on `type_id`
		}
	}
	
	async function loadClubs(id) {
		try {
			const response = await fetch(THEME_DIR + 'get_clubs.php', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify({
					id: id,
					start: y,
					end: z,
					limit: limit,
					page: page
				})
			});
	
			if (!response.ok) {
				throw new Error('Network response was not ok');
			}
	
			// Assuming response is JSON
			const data = await response.json();
			// Process your data here, e.g., update the DOM or store it
			// For example:
			document.querySelector('.clubs').innerHTML += data.htmlContent; // Adjust based on your response
	
			window.progress = (window.progress || 0) + 1;
			updateProgress(window.progress * 100 / window.progLength, 100);
		} catch (error) {
			console.error('Error fetching clubs:', error);
		}
	}
// получение списка альбомов
function get_albums(x, page)
{
	if (editor && (level==3))
		 {add_enable=true;  
		 	$('.add').slideDown('slow'); //$('.add').css('opacity','1'); $('.addhint').attr('title','Добавить раздел');
	     } 

	if (editor && (level!=3))
		 {add_enable=false; $('.add').slideUp('slow'); //$('.add').css('opacity','0.5');  //$('.addhint').attr('title','Зайдите в клуб, чтобы добавить альбом');
	               } 	
	spn('.clubs');

	$('.clubs').load( THEME_DIR + 'get_albums.php', {id: x, page: page},function(){

	} );
}

$('.lside').click(function(){

});
function get_child(){
  spn('.clubs');

  $('.clubs').load('/wp-content/themes/album2/get_child_photo.php', {id: type_id,level:level, size:'medium', limit:limit, page: page}, function()
	{ 	
		help_text_hide();
		$('body').scrollTop(0);
		imgcentered('.album_img');
		qq = $('.album_img').length+1;
		myDropCreate();	 
		lazyLoad(); 
	    height = $('.album_img').height();
        hh = $('.clubs').height();
        count  = hh/height/5;

		get_pagenav(parseInt(count), page);
	});

}

function myDropCreate(){
	    get_slide_arr();
		if ($('.dropzone').length == 0 ){
			return;
		}
		if (typeof myDropzone != 'undefined' ){
			window.myDropzone = undefined;
		}

		window.myDropzone = new Dropzone(".dropzone");
		window.myDropzone.dtype_id = type_id;

		
		myDropzone.options.maxFilesize = 6;
 		myDropzone.options.acceptedFiles= "image/*";
			
		myDropzone.options.autoProcessQueue = true;
		myDropzone.options.uploadMultiple = false;
		myDropzone.options.parallelUploads = 1;

		myDropzone.options.resizeWidth = 1024;
		
		
		myDropzone.on("sending", function(file, xhr, formData) { 
			formData.append("type_id", this.dtype_id);// отправляем данные вместе с файлом
			
		});
		
		//Прогресс пакетной загрузки 
		oldprogress = 0; 
		oldupl = 0;
		di = 0;
		ilength = 0;
		myDropzone.on("totaluploadprogress", function(uploadprogress, totalBytesSent) {
		     //  $('.dz-fullprogress').css('width',10*progress+'px'); 
		   	    // To access all files count
				$('.dz-fullprogress').show(); 
				$('.uploadcount').show();

				all = this.files.length;
				// To access only accepted files count
				acc = this.getAcceptedFiles().length;
				// To access all rejected files count
				rej = this.getRejectedFiles().length;
				// To access all queued files count
				que = this.getQueuedFiles().length;
				// To access all uploading files count
				upl = this.getUploadingFiles().length;
				
				window.upl2 = all - que;
				window.oldupl = upl2;
		   	    $('.not_found').hide();
		   	    $('.uploadcount').html(upl2+'/'+all);
		   	    if (que==0){
		   	   // setTimeout(function(){ $('.dz-fullprogress').hide('fast'); get_slide_arr(); $('.uploader').hide('fast'); $('.uploadcount').hide('fast')}, 1000);
		   	    }


				if ((uploadprogress>25)&&(uploadprogress<45)){
					uploadprogress = uploadprogress -20;
				}

				if ((uploadprogress>45)&&(uploadprogress<65)){
					uploadprogress = uploadprogress+ 20;
				}

				if ((uploadprogress>65)&&(uploadprogress<85)){
					uploadprogress = uploadprogress+ 20;
				}

				if ((uploadprogress>85)&&(uploadprogress<90)){
					uploadprogress = uploadprogress+ 20;
				}

		   	    if (ilength == 0) { ilength = $('.dz-image').length; };
		   	    procent = upl2/all*100;
		   		if (upl2 < all) {
				    oldupl = upl2;
				} 
		});
 
		myDropzone.on("complete", function(file)
		{		
				$('.not_found').detach();

				procent = (upl2+1)/all*100;
				$('.dz-fullprogress').css('width',0.87*screen.width/100*(procent)+'px');

		   		if (upl2 < all) {

				    oldupl = upl2;
				    $('.uploadcount').show();
				    $('.dz-fullprogress').show();
				 
				} 

				if (upl2 == all){
				    $('.dz-fullprogress').fadeOut('slow');
				    $('.uploadcount').fadeOut('slow');
				} 
			//cleanStr = file.xhr.response.replace(/[\r\n]+/g, '');
			
			//cleanStr0 = cleanStr.split('}{')[0]+'}'
			parsedObj = JSON.parse( file.xhr.response);
			if (typeof parsedObj["300"]=='undefined'){
				return;
			}
			src = parsedObj["300"]["src"];
			id  = parsedObj["300"]['id']; 
			photo_arr[id] = [];
			photo_arr[id]['url']  = src; 
			photo_arr[id]['desc'] = ''; 
			imgurl = '<img src="'+src+'">';

            if (admin){ pclass="" }
            else {
               	pclass = "pending";
            }			
            if (parseInt(id)!=-1){
				html = get_album_img(id, imgurl, pclass+' My_photo');
			} else {
				html = '';
			}
			$('.spinner').detach();
			imgcentered('.album');
			di = di+1;
			if (this.dtype_id == type_id){
				$(html).insertAfter( ".uploader" ); 
			}

			$('.dropzone').removeClass('dz-started');
			$('.dz-preview').hide('fast', function(){ $('.dz-preview').detach();}); 
	
		});
	
}

// получение списка последних постов
function get_list(x,y,z)
{
	list_page = 0;
	$('.list').load( THEME_DIR + 'get_list.php', {id: x, start: y, end: z, page: lpage}, function(){
		$('.breadcrumbs a[data-id=' + x + ']').addClass('bc-activ');
		get_slide_arr2();
	});
	
}

function get_wall(x,y,z)
{
	list_page = 0;
	uid = $('.wall').attr('uid');
	$('.wall').load( THEME_DIR + 'wall.php', {id: x, uid: uid, end: z, page: wpage}, function(){
		$('.breadcrumbs a[data-id=' + x + ']').addClass('bc-activ');
	});
	
}

//корзина
function get_trash(x,y,z)  
{
	list_page = 0;
	

	$('.trash').load( THEME_DIR + 'get_trash.php', {id: x, start: y, end: z, page: tpage}, function(){
		$('.breadcrumbs a[data-id=' + x + ']').addClass('bc-activ');
		$('.album').addClass('deleted');
		$('.spn').detach();
		$('#deg').change();
	});
	
}


// подгрузка контента при достижении низа страницы
$(document).ready(function()
{
	var list_InProcess = false;
	var list_IsEnd = false;
	
	var loading = "<img src='" + THEME_DIR + "img/loading.gif' alt='Loading' /><span>Загрузка..</span>";
	$.cookie("limit", limit);
	$(window).resize(function(){
		setlimit(); 
		//  $.cookie("limit", limit);
		//$('.pnums .active').click();  
	});

	lazyLoad(); 

  

	deg = localStorage.getItem('deg');
	inv = localStorage.getItem('inv');
	if (inv == 'invert(1)') {
		$('#inv').prop('checked','checked');
	}
	$('#deg').val(deg);
	$('#deg').change();
	
	var savedTheme = localStorage.getItem('theme');
	if (savedTheme) {
		$('#theme-css').attr('href', THEME_DIR + savedTheme +'?t='+Math.random(10000000));
	}

	$('.th-darkgrey').click(function() {
		
		var theme = 'darkgrey.css';
		$('#theme-css').attr('href',THEME_DIR + theme);
		localStorage.setItem('theme', theme);
	});

	$('.th-white').click(function() {		
		var theme = 'white.css';
		$('#theme-css').attr('href',THEME_DIR + theme);
		localStorage.setItem('theme', theme);
	});

	$('.th-gold').click(function() {
		$('#theme-css').attr('href', '');
		localStorage.removeItem('theme');
	}); 

	

	$(window).scroll(function(e){
		if (screen.width<=480){
         if (window.scrollY>30){
         	//$('.lside').css('top','-10px');
         } else
         {
         	//$('.lside').css('top','22px');
         }
        }
	});
    	
	
	$(window).scroll(function() 
	{
		if ($(window).scrollTop() == $(document).height() - $(window).height()) 
		{
			// если лента
			if (!list_InProcess && !list_IsEnd && $('.n-list').hasClass('n-active'))
			{
				list_InProcess = true;
				list_page++;
				
			}
		}
	});
});


// инициализация страницы
$(document).ready(function()   
{	if (window.location.pathname=='/'){    
	main_ind(); 
	spn('.select');

	get_selected_level(0, '4'); 

	get_clubs(type_id, level, 5, page);
//	get_list(type_id, level, 5);
}


});



/* ФУНКЦИИ ДЛЯ РАБОТЫ С МЕНЮ В ЛЕВОЙ КОЛОНКЕ */


function update_menu_height()

{	
//	top = window.history.state.sel_top;
	stop = window.sel_tops[type_id];
	if (typeof stop =='undefined'){
		stop='0px';
	}
	var height = $('ul.select').height();

	h = 0; 
	wh = $(window).height();
	elh = $('.select_item').eq(0).height();
	ofs = $('.lmenu-sub')[0].offsetTop;
	len = $('.select_item:visible').length+1;
	$('.select_item:visible').each(function( i, val ) {
    		elh = $(this).height();
    	
    		if (i<=(parseInt((screen.height - ofs)/elh ))+1){   
    			h = h + elh;  
    		} 
    	
    //  alert($(this).height()); 
    }); 
	if (screen.width<480){
		if ($('.select_item:visible').length>1){
		h = wh - $('.club-menu').height() - 40;   }
		else {h = elh;} 

	}

	if ((screen.width>=480) && (screen.width<=768)){
	h = h -  2*elh ;   }

	if ((screen.width>=768) && (screen.width<=1024)){ 
	    if (len>6){h = h } else {

	    }

	    if (len=3){h = h +  elh} else {

	    }
     }
	if (h<elh) {h = elh;}
	$('.select').css('top',stop); 
 	$('.slider').css('height', h + 'px');  
	//$('.lmenu_item span').simplemarquee({speed: 30,cycles: 200,space: 15,delayBetweenCycles: 320,handleHover: false,handleResize: false});
}


/* ------------------------------- */
/* -------- СКРОЛЛ МЕНЮ -------- */
/* ------------------------------- */


	// сдвиг слайдера на значение amount
	function slider_move(amount)
	{
		var offset = $('ul.select').position();
		var top = offset.top;
		
		// скролл вверх
		if (amount > 0)
		{
			if (top + amount > 0) top = 0; else top += amount;
		}
		
		// скролл вниз
		else
		{
			var slider_height = $('.slider').height();
			var menu_height = $('ul.select').height();
			
			if (top + amount < slider_height - menu_height) top = slider_height - menu_height; else top += amount;
		}
		
		$('ul.select').css('top', top + 'px');
	}

	$(document).on('click', 'div, li', function(){
		//setTimeout($('.content').removeClass('static'),1000);
	});

	$(document).on('click', '.usr', function(){
	//	$('.ulist').slideToggle();
		if ($(this).hasClass('active')){
			$(this).removeClass('active'); 
		}
		else{
			$(this).addClass('active');
		}
	});

	$(document).on('keyup', '#gsearch', function(e){	
	    var findText = $('#gsearch').val().toLowerCase(); // Convert to lowercase for case-insensitive comparison
	    if (findText.length<2){findText='';}
	    if (findText=='  '){findText='';}
	    if (findText==' '){findText='';}

	    if (findText==''){
	    	 $(".select_item, .club_icon").show();
	    	return
	    }

	    $(".select_item, .club_icon,.album_icon").each(function() {
	        var selectItemText = $(this).find(".sm-note").text().toLowerCase();
	        var clubItemText = $(this).find(".big-note").text().toLowerCase();

	        var containsWord = findText.split(' ').some(function(word) {
	            return selectItemText.includes(word) || clubItemText.includes(word);
	        });

	        if (!containsWord) {
	            $(this).hide();
	        } else {
	            $(this).show();
	        }
	    });

    	if (ajax != undefined){
    			ajax.abort();
    	} 

		var code = e.keyCode || e.which;
	 	if(code == 13) {    
	 
		title = $(this).val();
		spn('.gsearch'); 
		$('.gsearch').show(); 
		//ajax.abort();
		if (title != ''){
			 ajax =    
			$.ajax({
	        url: '/wp-content/themes/album2/gsearch.php',
	        type: "POST",        
	        data: {title: title},
	        success: function(data){  
	          if (title != ''){
	            $('.gsearch').html(data);
	            $('.gsearch').show('fast');
	          } 
	          else{
	          	$('.gsearch').hide('fast');
	          }
	        }
	        });
        }
        else
        {
        	$('.gsearch').hide('fast');
        }
       }
	});

	$(document).on('click', '#gsearch', function(){
		$('.gsearch').hide('fast');
		if ($(this).hasClass('active')){
			$(this).removeClass('active'); 
		}
		else{
			$(this).addClass('active');
		}
	});
    var ajax;
   
   
   $(document).on('click', '.cash', function(e){
   	    delete_cash();
      	
   });



    
    function  delete_cash(){
		
		$.ajax({
			url: '/wp-content/themes/album2/delete_cash.php',
			type: 'POST',
			data: {id: type_id}, 
			success: function()
			{	cash_clubs(type_id, level, 5, page);	
				$('.dz-fullprogress,.uploadcount').hide();
				if (level<5){
					get_clubs(type_id,level,5);			
				} else{
					get_child();		
				}
			}
		}); 

		//message('','Обновление кэша','bar','nobut','',function(){});
	
	}

   $(document).on('click', '.post_title', function(){
	    type_id = $(this).attr('data-id');
	    level = $(this).attr('level');
	    
	    get_clubs(type_id, level, 5);
	    get_branch(level);
	    get_selected_level(level,type_id);
		get_select(level);
	    //setTimeout($('.lmenu_item[data-id='+type_id+']').mouseup()
	    $('.gsearch').slideUp('fast');
	    $('#gsearch').val('');
	   // get_selected_level();
	  	update_menu_height(); 
	});	
	
	
	// скролл вверх
	$(document).on( 'click, mousemove', '.lprev', function()
	{
		slider_move(107);
	});
	
	
	// скролл вниз
	$(document).on( 'click, mousemove', '.lnext', function()
	{ 
		slider_move(-107);
	});

	function prev(){
	  if (int_history_index!=int_history.length-1){
		int_history_index++;
		type_id = int_history[int_history_index][0];
		level   = int_history[int_history_index][1];
		preid = int_history[int_history_index][2];
		//$('.breadcrumbs a[data-id=' + type_id + ']').eq(0).click(); 

		$obj = $('header'); 
		$obj.attr('id',type_id);
		$obj.data('level',level);
        $obj.attr('parid',parid);

        main_ind(); 
		page_update();
		//menu_update($obj);
		get_branch(level);
		get_selected_level();
		update_menu_height(); 

	  } 

		if (level == 0)
		    {
		   	$('.lmenu-first').addClass('lmenu-single'); 
		   	$('.lmenu-first').removeClass('lmenu-last'); 
		   	$('.lmenu-first').removeClass('lmenu-first'); 
		   }		
	}

	$(document).on( 'mouseup', '.next', function()
	{ 
		prev();	
	}); 

	function nprev() {
	  const photoIds = Object.keys(photo_arr);
	 
 	    

	    //window.img_ind   =  photoIds.indexOf(window.img_id)-1;
	    if (img_ind < 0){
	     	img_ind  = photoIds.length-1;
	    }

		img_id_n = $('.album_img').eq(window.img_ind+1).attr('id');
		img_id_p = $('.album_img').eq(window.img_ind-1).attr('id');	 

	    window.img_ind_n =  window.img_ind+1;
	    window.img_ind_p =  window.img_ind-1; 

	 //   img_id = photoIds[img_ind];
	     img_id = $('.album_img').eq(img_ind).attr('id');

		if (window.img_ind_n>photoIds.length-1){
	    	img_ind_n = 0;
	    }
	    if (img_ind_p < 0){
	    	img_ind_p = photoIds.length-1;
	    }



		$('.lightbox__content').css('background-image', "url('" + photo_arr[window.img_id]['url'] + "')");
	 	url  = photo_arr[window.img_id]['url'].replace('300', '1024');
		
	 	desc = photo_arr[window.img_id]['desc'].replace('300', '1024');
		help_text(desc);
	 	url_n  = photo_arr[window.img_id_n]['url'].replace('300', '1024');	 	
	 	url_p  = photo_arr[window.img_id_p]['url'].replace('300', '1024');
	 	
	 	get_single(url,desc,url_p,url_n);
	 
	}

	// Функция для перелистывания на следующую фотографию
	function nnext() {
	  const photoIds = Object.keys(photo_arr);


	 //   window.img_ind   =  photoIds.indexOf(window.img_id)+1;
	    window.img_ind++;
		if (window.img_ind > photoIds.length){
		  	window.img_ind = 0; 
		}	  

	    window.img_ind_n =  window.img_ind+1;
	    window.img_ind_p =  window.img_ind-1; 
		img_id_n = $('.album_img').eq(window.img_ind+1).attr('id');
		img_id_p = $('.album_img').eq(window.img_ind-1).attr('id');
	    
		img_id = $('.album_img').eq(img_ind).attr('id');

		if (window.img_ind_n>photoIds.length){
	    	img_ind_n = 0;
	    }
	    if (img_ind_p < 0){
	    	img_ind_p = photoIds.length-1;
	    }

		
		$('.lightbox__content').css('background-image', "url('" + photo_arr[window.img_id]['url'] + "')");

	 	url  = photo_arr[window.img_id]['url'].replace('300', '1024');


	 	desc = photo_arr[window.img_id]['desc'].replace('300', '1024');
		help_text(desc);
	 	url_n  = photo_arr[window.img_id_n]['url'].replace('300', '1024');	 	
	 	url_p  = photo_arr[window.img_id_p]['url'].replace('300', '1024');
	 	
	 	get_single(url,desc,url_p,url_n);
	 
	}

    function next(){
		window.img_ind--;
    	if (int_history_index>0){
		int_history_index--;
		//$('.select_item[parid=' + type_id + ']').addClass('l-active');
		type_id = int_history[int_history_index][0];
		
		level   = int_history[int_history_index][1]; 
		preid = int_history[int_history_index][2];

		$obj = $('header'); 
		$obj.attr('id',type_id);
		$obj.data('level',level);
        $obj.attr('parid',parid);
        main_ind();

		page_update();
		get_branch(level);
		get_selected_level();
		update_menu_height();  
		/*page_update();*/
		
	 
	
	   } 
	   if (level == 0)
	    {
	   	$('.lmenu-first').addClass('lmenu-single'); 
	   	$('.lmenu-first').removeClass('lmenu-last'); 
	   	$('.lmenu-first').removeClass('lmenu-first'); 

	   }
    }


	$(document).on( 'click', '.prev', function()
	{ 
		next();
	   
	});
	
	window.sel_tops = [];
	// скролл колесиком
	$(function()
	{
		function slider_scroll(event)
		{   window.history.state.sel_top = $('.select').css('top');
			window.sel_tops[type_id] = $('.select').css('top');
			$('.slider').unbind( 'mousewheel DOMMouseScroll', slider_scroll);
			
			event.preventDefault();
			
			if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) slider_move(202);
			else slider_move(-202);
			
			setTimeout(function(){ $('.slider').bind( 'mousewheel DOMMouseScroll', slider_scroll); }, 550);
		}
		
		function window_not_scroll(event)
		{
			event.preventDefault();
		}
		
		$('.slider').bind( 'mousewheel DOMMouseScroll', slider_scroll);
		
		$('.slider').bind( 'mousewheel DOMMouseScroll', window_not_scroll);
	});


/* -------------------------------- */
/* -------- /СКРОЛЛ МЕНЮ -------- */
/* -------------------------------- */
  var mclasses = new Array( 'allcities', 'city', 'sportstype', 'kindofsport','sportclubs');

function get_menu(x)
{


  $('.club-menu').activity({segments: 12, width: 5.5, space: 6, length: 13, color: '#252525', speed: 1.5});
  $(".club-menu").load( THEME_DIR + 'get_menu.php', {id: x}); 

};


function get_branch(level){

      first = `<li class="lmenu_item lmenu-first" data-level="0" id="4" style="cursor: pointer;">
							<div class="lighter"></div>
							<span>Россия</span>
				</li>`; 
  $.ajax({
    url: THEME_DIR + 'get_branch.php',
    type: 'post',
    dataType: 'json',
    data: {id: type_id},
    success: function(data) 
	{  
      $bi = 0;
     // (".club-menu").append(data);
      html = ''; 
      jQuery.each(data, function(key, val){
	      	if ($bi==0) {mtype = 'lmenu-single'; str_branch = val['str_branch'];  document.title = '2-fc.com ' + str_branch;} 
	      	else {mtype = '';}

	      	
	      	
	      	mlevel = $bi+1;
	      	if (key!=0){
	      	   
	           html = '<li class="lmenu_item'+mtype+'" id="'+val['id']+'" data-pid="' + val['parent'] + '" data-level="'+val.level+'" data-id="'+key+'" style="display: block;"><div class="lighter"></div><span>'+val['title']+'</span></li>'+html;
	        } 

	        if (key==0) {length = val['length'];}
	        $(".club-menu").eq($bi).html();
	        $bi=$bi+1;   
       });
      

       $(".club-menu").html(first+html);
    },  
	beforeSend: function()
	{   	
	 //	$('.club-menu').activity({segments: 12, width: 5.5, space: 6, length: 13, color: '#252525', speed: 1.5});
	}


  });
  $('.lmenu_item').show();
 // $('.lmenu li.lmenu_item:not([style*="display: none"]):last').addClass('lmenu-last')
};


function main_ind(	){ 
 	spn('.clubs'); 
	
	$('.list>div').css('opacity','0.9');  
	spn('.list');
	$('.list>div:not(.list_block)').css('position','fixed');
	$('.list>div:not(.list_block)').css('margin-top','120px');
}; 


function freshhistory(){

	if (tab == ''){ tab = 'clubs'}
	if (page == 0){page == '';}
	pp = parseInt(page)+1;

    if (type_id != 4){

      history.pushState({ 'type_id': type_id, 'level': level,'parid':parid, 'page': page, 'sel_top':$('.select').css('top')}, '', '/'+type_id+'/'+tab+'/');    
    }
    else {
      history.pushState({ 'type_id': type_id, 'level': level,'parid':parid, 'page': page, 'sel_top':$('.select').css('top')}, '', '/');       	
    }
}

// клики по элементу нижнего меню
$(document).on( 'click', '.select_item', function()
{	
	spn('.clubs');
	main_ind(); 
	
	$('.find').val('');  
	page = 0;
	lpage = 0;
	tpage = 0;

	type_id = $(this).attr('id');
	$('body')[0].scrollTop = 0;
    var old_level = level;
	level = parseInt($(this).attr('data-level')); 
	parid =	$(this).attr('parid');

	var name = $(this).find('.sm-note').text();

	//level = $el.attr('data-level'); 

	freshhistory();
	if ((level < 5)&&(level !== -1))
	{

		if (old_level == 0)

		$('.club-menu').append('');

		html = `<li class='lmenu_item' data-level='`+level+`' parid='`+parid+`' id='`+type_id+`'>
                <div class='lighter'></div>
                    <span>`+name+`</span>
		  </li>`;
		$('.club-menu').append(html);
	
		$('.lmenu_item[data-level=' + level + ']').show();
		get_selected_level(level, type_id); 
		get_select(level); 
	}
	 

	if ($('.n-clubs').hasClass('n-active')){
	    if (level == 5) {get_slide_arr();} }
	else { 
		get_slide_arr2()
	}

	if ((level < 5)&&(level !== -1)){
		if ($('.clubs').css('display')!='none'){
		get_clubs(type_id, level, 5);}
		$('.l-active').removeClass('l-active');
		update_menu_height();
	}
	/*
	if (level == 4){
		if ($('.list').css('display')!='none'){
		get_albums(type_id);} $('.l-active').removeClass('l-active');
	
	}*/
	if ((level == 5)||(level == -1)){
		$(this).children('.after').click(); 

	} else {
	if ($('.list').css('display')!='none'){
		spn('.list'); 
	    get_list(type_id, level, 5);
	} 
	
	if ($('.trash').css('display')!='none'){
    	spn('.trash');
		get_trash(type_id, level, 5);
	
	}
}  
});

$(document).on( 'click', ".select_item[data-level='4'] .after,.select_item[data-level='3'] .after,"+
						 ".select_item[data-level='2'] .after,.select_item[data-level='1'] .after", function(event)
{    
	event.preventDefault();
	event.stopPropagation();
	$('body').scrollTop(0);
	main_ind(); 
    page = 0;
    lpage = 0;
    tpage = 0;
	var $el = $(this).parent();
	type_id = $el.attr('id');
	
	$('.select_item').removeClass('l-active');
	$el.addClass('l-active');
	freshhistory(); 
	if ($('.clubs').css('display')!='none'){
	if (level + 1 < 4) get_clubs(type_id, level + 1, 5); else get_albums(type_id);}
	
	if ($('.list').css('display')!='none'){
	    get_list(type_id, level, 5);} 
	
	if ($('.trash').css('display')!='none'){
		get_trash(type_id, level, 5);
	}	
});

$(document).on( 'click', '.select_item[data-level="5"] .after,.select_item[data-level="-1"] .after', function(event)
{
	event.preventDefault();
	event.stopPropagation();	
	var $el = $(this).parent();
	type_id = $el.attr('id');
 	page = 0;
    lpage = 0
    tpage = 0;
	$('.select_item').removeClass('l-active');
	$el.addClass('l-active');
	freshhistory();
	main_ind(); 
    get_child();
   
});


// клик по хлебной крошке
$(document).on( 'click', '.breadcrumbs a', function()
{
	type_id = $(this).attr('id');
	level = $(this).data('level');
	tpage = 0;
	get_branch(level);
	$('.l-active').removeClass('l-active');

	freshhistory();
	
	main_ind(); 
	page_update();
	get_selected_level(level, type_id);
	get_select(level);
	//menu_update($(this));
	update_menu_height(); 

});

club_check = false;
// клик по клубу
$(document).on( 'click', '.club_icon', function()
{
if (club_check == false){
	club_check = true;

	main_ind(); 
	page = 0;
    lpage = 0;
    tpage = 0;
	$('.find').val(''); 
	var $el = $(this);
	parid = type_id;
	type_id = $el.attr('id');
	var preid = $el.attr('data-pid');
	
	

	var name = $.trim( $(this).parent().children('.big-note').children('span').text());
	var old_level = level;
	

	level = $(this).attr('data-level');
	
	$('.select_item').hide();
	get_selected_level(4, type_id); 
	get_branch(level);

	update_menu_height();
	if (level<5){
	   get_clubs(type_id,level,5);	}
	else{

	}
	/*	
	if (level==4) {
		get_albums(type_id);}
	else {
		get_clubs(type_id,level,5);	
	}
    */
	freshhistory();
	setTimeout(function(){club_check = false;}, 1000);
}

});



// создание/изменение элемента

  function get_create_sel(x,y){
    //$(".lightbox__create_selector").attr("disabled","disabled");
      jQuery.ajax({
        url: '/wp-content/themes/album2/get_create_select.php',
        type: "POST",
        dataType: 'json',
        data: {id: x,par: y},
        success: function(data){  
          $(".lightbox__create_selector").empty();
          $(".lightbox__create_selector").append("<option>выберите элемент</option>");
          switch (y){
            case 0:
              jQuery.each(data, function(key, val){
                $(".lightbox__create_selector").append('<option value='+key+'>'+val+'</option>');
              });
            break;
            case 1: 
              jQuery.each(data, function(key, val){
                if (key==0){
                  created_parentid=val;
                }
                else {
                  $(".lightbox__create_selector").append('<option value='+key+'>'+val+'</option>');
                }
              });
            break;
              create_level=create_level-1;
          };
          //$(".lightbox__create_selector").attr("disabled","");
        }
      });
  }
 

//добавление нового элемента дерева
function create_branch() {
    const lightboxContent = $('.lightbox__content');
    lightboxContent.empty();

    const create_elem = 0;
    const created_parentid = 4;
    const create_level = 7;

    lightboxContent.append(`
        <button class='lightbox__button-exit dashicons dashicons-no-alt'></button>
        <button class='lightbox__create-elem'>Cоздать</button>
        <button class='lightbox__change-elem'>Изменить</button>
        <div class='lightbox__create_selector_cont'>
            <select class='lightbox__create_selector'></select>
            <button class='lightbox__but_back'>вернуться</button>
        </div>
        <textarea class='lightbox__create_name-input'></textarea>
        <button class='lightbox__change-elemname' style='display:none;'>Изменить название</button>
        <div class='lightbox__create_load'>
            <form action='/wp-content/themes/album2/create_upload.php' class='createDropzone'></form>
        </div>
    `);

    const createrDropzone = new Dropzone('.createDropzone', {
        maxFilesize: 6, // мб
        acceptedFiles: 'image/*',
        maxFiles: 1,
        uploadMultiple: false,
        parallelUploads: 1,
        resizeWidth: 1200
    });

    createrDropzone.on('maxfilesexceeded', function (file) {
        this.removeFile(file);
    });

    createrDropzone.on('sending', function (file, xhr, formData) {
        formData.append('name', $('.lightbox__create_name-input').val());
        formData.append('parent_id', type_id); // У вас здесь переменная type_id, проверьте, что она определена где-то в коде.
        formData.append('create', create_elem);
        formData.append('create', create_level);
	//	formData.append('text', file.name.replace('.jpg','')); 
    });

    get_create_sel(created_parentid, 0);
    showlightbox(false);
}

  $(document).on('change','.lightbox__create_selector',function(){ //изменение селектора в создании элемента
    created_parentid = $(this).val();
    get_create_sel(created_parentid,0);
  });

  $(document).on('click','.lightbox__but_back',function(){ //клик по кнопке вернуться
    if (created_parentid==4){
      create_level=7;
      get_create_sel(4,0);
    }
    else {
      get_create_sel(4,0);
    }
  });


  $(document).on('click','.lightbox__create-elem',function(){ //клик по кнопке создать (элемент)
      $('.lightbox').hide();
      spn('.clubs'); 
  });

  $(document).on('click','.lightbox__change-elem',function(){ //клик по кнопке изменить (элемент)
      $('.lightbox__change-elemname').show();
      create_elem=1;
  });



$(document).on('click','.create_elem',function(){ //клик по кнопке создать (в меню)
  create_branch();


});
// создание/изменение элемента (конец)


img_ind = 0; 
function get_slide_arr(){

	  	light_phid = [];
		light_phtit = [];
		light_phimg = [];


        $('.clubs .album_img img').each(function(key, val){
   			light_phid[key] = $(val).parents('.album_img').attr('data-id'); 
            light_phtit[key] = '';  

            light_phtit[key] = '';  
 
            src = $(this).attr('data-src')
            if (typeof src == 'undefined'){
				src = $(this).attr('src');
			}
            if  (src.indexOf('-300')>-1){src = src.replace('-300','-1024');}
            else{src = src.replace('.jpg','-1024.jpg');}


            //srcsmall = $(val).attr('src');   
            light_phimg[key] ='<img  src="'+src+'" srcset="'+src+'">'; 

        });
}

function get_slide_arr2(){
		light_phid = [];
		light_phimg = [];
		light_phtit = []; 
   		length = $('.list .album_img').length;
   		$('.list .album_img img').each(function(key, val){
   			light_phid[key] = val.parentElement.id; 
            light_phtit[key] = '';  
            srcs = val.srcset.split(',');  

            src = srcs[srcs.length-1];
            src = src.split(' ')[1];
            //src = val.src;   
            light_phimg[key] ='<img srcset="'+srcs+'">'; 
     			
   		});

 
}

function get_slide_arr3(){
		light_phid = [];
		light_phimg = [];
		light_phtit = []; 
   		length = $('.wall .album_img').length;
   		$('.wall .album_img img').each(function(key, val){
   			light_phid[key] = val.parentElement.id; 
            light_phtit[key] = '';  
            srcs = val.srcset.split(',');  
            src = srcs[srcs.length-1];
            src = src.split(' ')[1];
            //src = val.src;   
            light_phimg[key] ='<img srcset="'+srcs+'">'; 
     			
   		});

 
}

$(document).ready(function(){    

var lastClickTime = 0;


$(document).on( 'error','img', function(){
  $(this).hide(); // скрываем изображение, если возникла ошибка загрузки
});

        
$(document).on('mousemove','buff', function(event){
	$('.img_n').eq(1).detach();
	$('.img_p').eq(1).detach();
}); 
window.mouseinbuff = false;
$(document).on('mouseenter','buff img',function(){
  window.mouseinbuff = true;
});

$(document).on('mouseleave','buff img,buff',function(){
  window.mouseinbuff = false;
});



$('.lightbox').on('mousewheel', function(event){
	$('.img_n').eq(1).detach();
	$('.img_p').eq(1).detach();
   var currentTime = new Date().getTime();
   
   //if ((true)&&( $(window).height()-event.offsetY<150)&&( $(window).scrollTop()+$(window).height()-event.offsetY>0)&&( event.offsetX>$(window).width()/2-250)&&( event.offsetX<$(window).width()/2+250) ) { 
   if (mouseinbuff){
  	   event.preventDefault();
       event.stopPropagation();  

   }
   
   if ((currentTime - lastClickTime > 200)&&(mouseinbuff)) { // ограничение на 0.5 секунды
  	   event.preventDefault();
       event.stopPropagation();  
	   if (event.deltaY == -1){
	  	   nnext();
	   }
	   
	   if (event.deltaY == 1){
	  	   nprev();
   	   }	

       $('li[data-num='+window.page+']').click();
       lastClickTime = currentTime;
   }
});

  $(document).on('click','.album  svg, .select_item svg',function(e){ 
  	e.stopPropagation();
  	

  	if ((!$('.mvactive').hasClass('mvactive'))||((batch=='deleteall'))){	  	
	  	if ($(this).hasClass('selected')){
	  		$(this).removeClass('selected');
	  	}
	  	else{
	  		$(this).addClass('selected');
	  	}
    }
    
	if ($(this).parent().parent().attr('data-level')=='-1'){
		window.hist_id = $(this).parent().parent().attr('id');
	}

    if (($('.mvactive').hasClass('mvactive'))&&((batch!='deleteall'))){	  
    	parid = $(this).parent().parent().attr('data-id');
		
	  	window.selected.forEach(function(change_id, i) {            	        
	          $('[data-id='+change_id+']').detach();          
	          $.ajax({  	type: 'POST',
					url: '/wp-content/themes/album2/change_parent.php',
					data: {id: change_id, parent_id: parid},
					success: function(response)
					{	 delete_cash(); }
			  });
	    });
	    $('.mvactive').removeClass('mvactive');
    }

  });
  
  window.selected = [];
 
$(document).on('click', ".selectall", function(){
	if ($('.n-active').hasClass('n-clubs')){
		$('.clubs svg').toggleClass('selected');
	}
	if ($('.n-active').hasClass('n-trash')){
		$('.trash svg').toggleClass('selected');
	} 
});

  $(document).on( 'click', ".moveall", function(){
		if (($(this).hasClass('mvactive'))||(batch!='deleteall')){
			$(this).removeClass('mvactive');
			window.selected = [];
		}
		
		if (!$(this).hasClass('mvactive')||(batch=='deleteall')){
			$(this).addClass('mvactive');
			
			$('.selected').parent().parent().each(function() {              
		          change_id =  $(this).attr('data-id');
		          $('[data-id'+change_id+']').hide();          
		    	  window.selected.push(change_id);
	   		});
	   		window.selected = [...new Set(window.selected)];
		}
  });



  $(document).on('click','.album_icon',function(){ //смена альбомов на фотографии и ативация дропзоны
      	parid = type_id;
      	type_id=this.id;
     	page = 0; 
        lpage = 0;
        tpage = 0;
     	light_phid = [];
		light_phtit = [];   
     	main_ind(); 
     	//level = 5; 
		level = $(this).attr('data-level');
     	spn('.clubs');
     //	get_list(type_id, level, 5);
     	$('.select_item[data-id=' + type_id + ']').addClass('l-active');
     	if (type_id!=4){freshhistory();}
     	get_slide_arr();

      	$('.find').val('');
      $(document).ready(function(){
         get_child();

      });
		
  });

});

$(document).on('keyup','.find',function(){
	srch = $(this).val();
	if (srch!=''){
		$els=$('.select_item[parid=' + type_id + '] .sm-note');
		$('.select_item').hide();
		$els.each(function() {
		  if ($(this).text().toLowerCase().indexOf(srch.toLowerCase())!=-1){
		  	  $(this).parents('.select_item').show();
		  }
		});
	} else {
		$('.select_item[parid=' + type_id + ']').show();
	}
	update_menu_height();
});

$(document).on('click','.load_hid',function(){ //скрытие/расскрытие формы закрузки
    if ($(".uploader").hasClass("hidden")) {
      $(".uploader").show();
      $(".uploader").removeClass("hidden");
    }
    else {
      $(".uploader").addClass("hidden");
      $(".uploader").hide();
    }
});

light_phid = 0;
$(document).on('click','.album_img img',function(){
	$('.ligtbox__img_right,.ligtbox__img_left').show();
});

$(document).on('click','.album_img',function(){ //покз фотографии в большом формате


  if ($('.dz-fullprogress:visible').length==1){
  	return;
  }
  src = $(this).find('img').attr('data-src');
  src1 = $(this).find('img').attr('src');
  src = src??src1;
  
  window.scrollTop = $('body')[0].scrollTop; 
  $('body').scrollTop(0);

  
  $('.lightbox__content').css('background-image', "url('" + src + "')");
  spn(".lightbox");
  $('.find').val('');

  img_id = this.id;
  parid = type_id;
  history.pushState({ 'type_id': this.id, 'level': level+1,'parid':type_id}, '', '/'+this.id+'/');  
	
  // img_ind = light_phid.indexOf(img_id); 
  if ($('.n-list').hasClass('n-active')){
  	window.img_ind = parseInt($(this).attr('img_ind'));
  }
  else{
	window.img_ind = parseInt($(this).attr('img_ind'));
  }

  
  load_single_photo(img_id); 
  
});


function light_slide(){
   	if (light_phid.length == 0){
   		get_slide_arr();
   	}
   	if (img_ind < 1){ 
		img_ind = (light_phid.length - 1);
	};	

	if (img_ind > light_phid.length - 1){
		img_ind = 2;
	};	
	$(".lightbox__edit-no").click();
	get_single_photo(img_ind);
	//parid = type_id;
 	type_id = light_phid[img_ind];    
}

$(document).on('click','.ligtbox__img_right',function(){//нажатие на кнопку вперед
	
	nnext();
	history.pushState({ 'type_id': type_id, 'level': 6,'parid':parid, 'page': page}, '', '/'+ type_id+'/');    
});

$(document).on('click','.lightbox__img_photo',function(){
	if (img_ind<0){
		img_ind = 1;
	}
	img_ind++;

	light_slide(); 

	history.pushState({ 'type_id': type_id, 'level': 6,'parid':parid, 'page': page}, '', '/'+ type_id+'/');    
})

$(document).on('click','.lightbox__img_photo',function(){//нажатие на кнопку вперед
	img_ind--; 
	light_slide();	
	freshhistory();
});


$(document).on('click','.ligtbox__img_left',function(){//нажатие на кнопку назад
	if (img_ind<0){
		img_ind = 1;
	}
	nprev();
	img_ind--;

	history.pushState({ 'type_id': type_id, 'level': 6,'parid':parid, 'page': page}, '', '/'+type_id+'/');    
});

$(document).on('swipe','.lightbox__img img',function(){//нажатие на кнопку назад
	img_ind++;
	freshhistory();

	light_slide();
}); 



$(document).on('click','.lightbox__edit-ok',function(){//нажатие на подтверждени изменений
  $(".lightbox__title-input").hide();
  $(".lightbox__edit-ok").hide();
  $(".lightbox__edit-no").hide();
  $(".lightbox__edit").show();
  $(".lightbox__title-text").empty();
  //light_phtit[img_ind] = $(".lightbox__title-input").val(); 
  photo_arr[window.img_id]['desc'] =  $(".lightbox__title-input").val(); 
  $(".lightbox__title-text").append('<p>'+$(".lightbox__title-input").val()+'</p>');
  $(".lightbox__title-text").show();
  $(".lightbox__edit").show();
  jQuery.ajax({
    url: '/wp-content/themes/album2/update_img_title.php',
    type: "POST",
    dataType: 'json',
    data: {id:img_id,title:$(".lightbox__title-input").val()},
    success: function(){}
  });
});
$(document).on('click','.lightbox__edit-no',function(){ //нажатие на отмену изменений
  $(".lightbox__title-input").hide();
  $(".lightbox__edit-ok").hide();
  $(".lightbox__edit-no").hide();
  $(".lightbox__title-text").show();
  $(".lightbox__edit").show();
});

$(document).on('click','.lightbox__edit',function(){ //нажатие на редактирование коментария к фото
  $(".lightbox__edit").hide();
  $(".lightbox__title-text").hide();
  $(".lightbox__title-input").show();
  $(".lightbox__edit-ok").show();
  $(".lightbox__edit-no").show();
  
});

$(document).on('click','.tab',function(){ // клик по табе
  $(".pcenter").hide();
  $(".tab").removeClass('n-active');  
  $(this).addClass('n-active');
  pcenter = $(this).attr('class').split(' ')[0].split('-')[1];
  $('.'+pcenter).show();   
  
  get_slide_arr2(); 
  $('.mtab a').html($(this).find('.robots').html());
  if ($(window).width()<1024) {
  	 $('.nav').slideUp('fast');
  }
});
  

 $(document).on('click','.n-clubs',function(){
	 tab = 'clubs';
	 freshhistory();

 });


edit_el = '';
create_id = 0;




// отменить изменение / добавление элемента (закрытие lightbox)
$(document).on( 'click', '.lightbox__button-exit', function()
{
	type_id = parid;
	$('.ligtbox__img_right,.ligtbox__img_left').hide();

	$('.help_text').hide();
	freshhistory();
	$('.lightbox__edit').hide();
	$('.lightbox').hide();
	sedit = false;   
	$('.lslide').css('background','unset');
	$('body').removeClass('single');
	if ($('.n-list').hasClass('n-active')){
	
	}
	else {
	
		level = 5;
	}
//	$('body')[0].scrollTop = 0; 
	$('body')[0].scrollTop = window.scrollTop;
});

$(document).on( 'click','.lightbox *', function(e)
{
  e.stopPropagation();
});

/* ДОБАВЛЕНИЕ ЭЛЕМЕНТОВ */

// начать добавление элемента
$(document).on( 'click', '.add', function()
{
	
	if ((ulevel == 1) && (level<3))
		 {
	           
	   		$( ".helper .hint").hide();
	   		$('.helper').fadeIn(160,function(){$(this).removeClass('hidden')});
		    htop = 0;
	   		$( ".helper .hint[bind='.select_item']" ).each(function() {
			 	 help_elem = $(this).attr('bind')+':visible';
			 	 help_elem = $(help_elem);
			 	  $(this).show();
			 	 coord_el = $(this);
			 	 SetCoords(help_elem, coord_el);
			}); 
    		return;
	      } 	

	$('.lightbox__content').empty();


	create_elem = 0;
	if (level!=5) { created_parentid = type_id;} 
	else { created_parentid = $('.l-active').attr('parid'); }
	if (level< 5) { next_level = parseInt(level)+1; } else{
		next_level = 5;
	}
	if (typeof created_parentid == 'undefined'){
		created_parentid = type_id;
	}
	$('.lightbox__content').append(get_add());
	type_id = parseInt(type_id);
	autoy = $('#'+type_id).text().replace(/[^0-9]/g,'');
	if (autoy.length > 3){
		autoy = autoy[0]+autoy[1]+autoy[2]+autoy[3];
	}
	if (autoy>''){
	$('.lightbox__create_name-input').val(autoy+'.');}

	$('.create_level').val(next_level);
	
	if (typeof createrDropzone == 'undefined' ){
		window.createrDropzone = undefined;
	}
	window.createrDropzone = new Dropzone('.createDropzone', {
		maxFilesize: 6, // мб
		acceptedFiles: 'image/*',
		maxFiles: 1,
        uploadMultiple: false,
        parallelUploads: 1,
		autoQueue: false, // отключаем запуск скрипта при переносе файла
	});
	
	createrDropzone.on('success', function(file,response) { 
	    //добавить элемент
		create_id = response;
		create_level = $('.create_level').val();
		set_rels(create_id);  

		$('.spinner').detach();
		$('.lightbox__change-elemname').slideDown('slow');
		
		res = file.xhr.response.replace('[{\"length\":null,\"str_branch\":null}]','');
    	parsedObj = JSON.parse( res);
		src = parsedObj["300"]["src"];
		id  = parsedObj["300"]['id']; 
		photo_arr[id] = [];
		photo_arr[id]['url']=src;
		photo_arr[id]['desc']='';
		imgurl = '<img src="'+src+'">';

		
		img_id = parsedObj['300']['id']; 

		

		//} else{
		//	imgurl = nopic(create_id);
		//}

		name = $('.lightbox__create_name-input').val();
		create_level = $('.create_level').val();
		id = 0;
		
		if (level!=5) { created_parentid = type_id;} 
		else { created_parentid = $('.l-active').attr('parid'); }				

		html = get_select_item('', create_level, created_parentid , create_id, name, src); 		 
        innerHtml = $('.select').html();       
        $('.select').html(html + innerHtml);      
					// }	
		update_menu_height();

		if (create_level == 4) { divclass='club_icon';}
		if (create_level == 5) { divclass='album_icon';}
					//Анимация добавления
		if ((create_level == 5)||(create_level == 4)){ 
			
			html = get_album(divclass, create_id, name, imgurl, 0, created_parentid, create_level);		 
			
			$('.clubs').prepend(html);		
			//get_clubs(type_id,level,5);	
			$('.spinner').detach();
		}		
		$('.dz-fullprogress,.uploadcount').hide();
	});
	
	function nopic(id) {
	  let hash = md5(id);
	  let imageNumber = (parseInt(hash.slice(-2), 16) % 12) + 1;
	  let imageUrl = '/wp-content/themes/album2/img/nophoto'+imageNumber+'.jpg';
	  return imageUrl;
	}

	$('.lightbox__create-elem').click(function() {
		if (createrDropzone.files.length >0){
			createrDropzone.enqueueFiles(createrDropzone.getFilesWithStatus(Dropzone.ADDED));
		}
		else{
			if (parseInt(type_id)===0){
				message('','Не выбрана ветка, нужно выбрать ветку  в меню куда грузить','err','close','yes'); 
				return;
			} 
			if (level == 5){
				create_id = parid;
			} else{
				create_id = type_id;
			}
			
   		 	$.ajax({
					type: 'POST',
					url: '/wp-content/themes/album2/create_upload.php', 
					data: {
						name: $('.lightbox__create_name-input').val(),
						create:0, 
						parent_id: create_id, 
						level: $('.create_level').val()[0]
					},
					success: function(response)
					{	

							id = response;
							imgurl = nopic(id);
	
						    //html = get_album_img(id, imgurl,' My_photo');

						    slevel = parseInt($('.create_level').val());
						    if (slevel  < 5) {divclass='club_icon'; iconclass = "fa-solid fa-folder-tree";}             				
            				if (slevel == 5) {divclass='album_icon'; iconclass = "fa-solid fa-folder"; } 
				            if (slevel>4) {play = "  <div class='play_club fas fa-play'></div>"; }
				            imgurl1 = '<img src='+imgurl+'>';
							html = get_album(divclass+' My_photo', id, $('.lightbox__create_name-input').val(), imgurl1,0,type_id, slevel);
							chtml = $('.clubs').html();
						    $('.clubs').html(html + chtml);


						    html = get_select_item('', $('.create_level').val(), type_id , id,$('.lightbox__create_name-input').val(),  imgurl); 	

	                        innerHtml = $('.select').html();       
	                        $('.select').html(html + innerHtml);   
	                        update_menu_height();
	                     
						$('.spinner').detach();
						$('.lightbox').hide(); 
					}
			    });
		}
	});
	
	createrDropzone.on('maxfilesexceeded', function(file) { this.removeFile(file); });
	createrDropzone.on('sending', function(file, xhr, formData) { 
		formData.append('name', $('.lightbox__create_name-input').val()); // отправляем данные вместе с файлом
		formData.append('parent_id', type_id); // отправляем данные вместе с файлом 
		formData.append('create', create_elem); // отправляем данные вместе с файлом
		formData.append('level', $('.create_level').val()); // отправляем данные вместе с файлом
	});

	$('.lightbox__create_name-input').focus(); 
	showlightbox(false);
});

/* ИЗМЕНЕНИЕ ЭЛЕМЕНТОВ */

  var sedit = false;
// начать изменение элемента
window.hist_ids = [];
$(document).on('click', '.hist_add', function(e) {
    // Retrieve the hist_title and hist_id
    let hist_desc = $('.l-active .sm-note').text();
    let hist_id = $(this).parent().attr('id');
    let guid = $(this).parent().find('img').attr('src').replace('https://2-fc.com/wp-content/uploads/','');

    
    window.hist_ids.push({ ttl: hist_desc, ID: hist_id, guid: guid });
    
    window.hist_ids.sort((a, b) => {
        if (a.ttl < b.ttl) return -1;
        if (a.ttl> b.ttl) return 1;
        return 0;
    });
    
    e.stopPropagation();
});
$(document).on( 'click', '.histadd', function(e){

	histids = JSON.stringify(window.hist_ids);
	$.ajax({
		url: '/wp-content/themes/album2/add_histids.php',
		type: 'POST',
		data: {hist_id: hist_id, histids: histids}, 
		success: function(data)
		{	
			window.hist_ids = [];

		}
	
	});
		
});

$(document).on( 'click', '.edit_club', function(e)
{
	e.preventDefault();
	e.stopPropagation();
	sedit = true;
	edit_el = $(this).parent();
	$('.lightbox__content').empty();
	$('.dz-fullprogress,.uploadcount').hide();
	create_elem = 1;
	created_parentid = $(this).parent().attr('parid');

	html =  get_edit_club();

	$('.lightbox__content').append(html);
	create_level = $(this).parent().attr('data-level');
	$('.create_level').val(create_level);
	
	var createrDropzone = new Dropzone('.createDropzone', {
		maxFilesize: 6, // мб
		acceptedFiles: 'image/*',
		maxFiles: 1,
        uploadMultiple: false,
        parallelUploads: 1

	});
	
	createrDropzone.on('maxfilesexceeded', function(file) { this.removeFile(file); });
	createrDropzone.on('sending', function(file, xhr, formData) { 
		spn('.lightbox__content');
		formData.append('name', $('.lightbox__create_name-input').val()); // отправляем данные вместе с файлом
		formData.append('parent_id', created_parentid); // отправляем данные вместе с файлом
		formData.append('create', create_elem); // отправляем данные вместе с файлом
		formData.append('level', create_level);
		formData.append('type_id', edit_el.attr('id'));
		$('.lightbox__change-elemname').slideUp('slow');
	});

	createrDropzone.on('success', function(file, xhr, formData) { 
		 //Изменить элемент 
		$('.spinner').detach();
		$('.lightbox__change-elemname').slideDown('slow');
    	
    	res = file.xhr.response.replace('[{\"length\":null,\"str_branch\":null}]','');
    	parsedObj = JSON.parse( res);
		src = parsedObj["300"]["src"];
		id  = parsedObj["300"]['id']; 
			
		imgurl = '<img src="'+src+'">';

		
		img_id = parsedObj['id']; 

		if (src){ 

		    len = edit_el.parents('ul').length;

		    imgurl = '<img src="'+src+'">';
		    id = edit_el.attr('id');
		    edit_el.find('img').replaceWith(imgurl);			
		    $('[data-id='+id+'] img').replaceWith(imgurl);			
			editels = $('.select_item#'+id+' img, id'+id+' img'); 

			if (editels.length>0){
				editels.replaceWith(imgurl);
			}

		}
		$('.lightbox__change-elemname').slideDown('fast');

	});
	if ($(this).parent().hasClass('select_item')) name =  $(this).parent().children(('.sm-note')).text();
	else name = $(this).parent().children('.big-note').children('span').text();
	
	$('.lightbox__create_name-input').val(name); 
	showlightbox(false);
	$('.lightbox__create_name-input').focus();
 
});

$(document).on( 'click', '#enter', function(e){
	e.preventDefault();
	e.stopPropagation();
	$('.lightbox__content').load( THEME_DIR + 'get_login.php', {}, function(){showlightbox(false);} );		
	showlightbox(false);
});

$(document).on( 'click', '#reg', function(e){
	e.preventDefault();
	e.stopPropagation();
	$('.lightbox__content').load( THEME_DIR + 'get_register.php', {}, function(){showlightbox(false);} );	
	
});

$(document).on( 'click', '#lost', function(e){
	e.preventDefault();
	e.stopPropagation();
	$('.lightbox__content').load( THEME_DIR + 'get_lost.php', {}, function(){showlightbox(false);} );	
	showlightbox(false);
});

// повернуть вправо
$(document).on('click', '.rotate_right',function(e){
	e.preventDefault(); 
	e.stopPropagation();
	created_parentid = $(this).parent().attr('id');
	parent_a =  $(this).parent().children('a');
	img = parent_a.children('img');

	$.ajax({
		url: '/wp-content/themes/album2/photo_rotate.php',
		type: 'POST',
		dataType: 'json',
		data: {id: created_parentid, deg: 90}, 
		success: function(data)
		{	
			
			src = data['src_medium']+'?rdate='+ new Date().getTime(); 
			img.attr('src',src);
			img.attr('srcset',src);

		}
	});

});


// повернуть влево
$(document).on('click', '.rotate_left',function(e){
	e.preventDefault(); 
	e.stopPropagation();
	created_parentid = $(this).parent().attr('id');
	parent_a =  $(this).parent().children('a');
	img = parent_a.children('img');

	$.ajax({
		url: '/wp-content/themes/album2/photo_rotate.php',
		type: 'POST',
		dataType: 'json',
		data: {id: created_parentid, deg: -90}, 
		success: function(data)
		{	
			
			src = data['src_medium']+'?rdate'+ new Date().getTime();
			img.attr('src',src);
			img.attr('srcset',src);

		}
	});

});

function JSONobj(response, i = 0){	
	cleanStr = response.replace(/[\r\n]+/g, '');
	cleanStr = cleanStr.split('}{')[0]+'}';
	cleanStr = cleanStr.replace('[{"length":null,"str_branch":null}]','');
	cleanStr = cleanStr.replace('}}','}');
    const json = JSON.parse(cleanStr);
    return json; 
}

// подтвердить изменение элемента
$(document).on( 'click', '.lightbox__change-elemname', function()
{	
	if ((parseInt(type_id)===0)||(parseInt(created_parentid)===0)){
				message('','Не выбрана ветка, нужно выбрать ветку  в меню куда грузить','err','close','yes'); 
				return;
			} 
	edit_id = edit_el.attr('id');
    $.ajax({
		type: 'POST',
		url: '/wp-content/themes/album2/create_upload.php', 
		data: {
			name: $('.lightbox__create_name-input').val(),
			create:2, 
			parent_id: created_parentid, 
			type_id: edit_id,
			level: $('.create_level').val()[0]
		},
		success: function(response)
		{	
			$(`[data-id=${edit_id}]`).attr('data-level',$('.create_level').val()[0]);
			ename = $('.lightbox__create_name-input').val();
			edit_el.children('div.big-note').children('span').text(ename);
			edit_el.children('div.sm-note').text(ename);
			edit_el.attr('data-level', $('.create_level').val());
			$('.lightbox').hide(); 
		}
    });

	
    

});

$(document).on( 'click', '.cover_club', function(e)
{   cover_id = $('.l-active').attr('id');
    if (typeof cover_id == 'undefined'){
    cover_id = $('.lmenu_item:last-child').attr('id')}
	e.stopPropagation();
	created = $(this).parent().attr('data-id');	
	paren = $('#'+cover_id).attr('data-pid');
	url = $(this).parent().find('img').attr('data-src');
	if (typeof url == 'undefined') {
		url = $(this).parent().find('img').attr('src');
	}
	$('.l-active img').attr('src',url);
	$('.select_item[data-id='+cover_id+']').find('img').attr('src',url);
    $.ajax({
		url: '/wp-content/themes/album2/cover_elem.php',
		type: 'POST',
		dataType: 'json',
		data: {id: created, cover_id: cover_id,parent: paren, url: url}, 
			success: function(data)
			{
				
			}
	}); 
});


$(document).keydown(function(event) {
    if (event.ctrlKey) {        
        batch = 'deleteall';
    } 
    if (event.ctrlKey && event.keyCode == 32){
    	$('.after').show()
    }
});

$(document).keyup(function(event) {
        $('.after').hide()
        batch = '';     
});

/* УДАЛЕНИЕ ЭЛЕМЕНТОВ */


// начать удаление элементов
$(document).on( 'click', '.delete_club', function(e)
{
	e.preventDefault();
	e.stopPropagation();
	window.del_parentid = $(this).parent().attr('id'); 
	
	
	if ((batch!='deleteall')){
		message('Вы действительно хотите удалить?','Подтвердите','que','yes,no',delete_el);

    }
    else {

		   $(`[data-id=${del_parentid}]`).remove();
		   update_menu_height(); 
			
		   if (level!=-1){
				$.ajax({
						url: '/wp-content/themes/album2/delete_elem.php',
						type: 'POST',
						dataType: 'json',
						data: {id: window.del_parentid, type_id: type_id}, 
						complete: function(data)
						{
							//get_clubs(type_id,level,5);			
							
						}
					}); 			
			} else{
				$.ajax({
					url: '/wp-content/themes/album2/delete_histid.php',
					type: 'POST',
					dataType: 'json',
					data: {delete_id: window.del_parentid, hist_id: type_id}, 
					complete: function(data)
					{
						//get_clubs(type_id,level,5);			
						
					}
				}); 
			}
			
				
		     }; 
    }
);

var ph_play = 0;
var counter = 0;

$('.lrm-user-modal.is-visible').click(function(e){
	e.stopPropagation();

});

function photoPlay() {
    window.counter = -1;
    clearInterval(ph_play);

    $('.photo_big').attr('src', '');

    if (player_paused === false) {
        ph_play = setInterval(function() {
            window.counter += 1;

            if (window.counter > frames - 1) {
                window.counter = 1;
            } else if (window.counter < 0) {
                window.counter = frames;
            }

            // Hide UI elements and clear image sources at specific intervals
            if (window.counter % 4 === 0) {
                $('.photo_big').attr('src', '');
                $('.buffer').attr('src', '');
                $('ptools').hide('fast');
                help_text_hide();
            }
            // Get ordered keys from the photo array
            //let keys = Object.keys(photo_arr).map(Number);
			img_id = $('.album_img').eq(window.counter).attr('id');
			img_id_next = $('.album_img').eq(window.counter+1).attr('id');
          //  keys.sort((a, b) => a - b);
		    

			text = photo_arr[img_id].desc;
			if (text!=''){
				help_text(text);
			}
            if (window.counter % 20 === 0) {
                const text = $('.lmenu_item span').eq(ll - 2).text() + ' ' + $('.lmenu_item span').eq(ll - 1).text();
                help_text(text);
            }


            // Access the objects based on the counter value
            let src1 = photo_arr[img_id].url.replace('-300','-1024') || '';
            let src2 = photo_arr[img_id_next].url.replace('-300','-1024') || photo_arr[$('.album_img').eq(0).attr(0)] || '';
			
            if (src1 !== '') {
                $('.photo_big').attr('src', src1);
                $('.buffer').attr('src', src2);

                // Apply transformations with reduced randomness
                let scalePhoto = 1 + 0.2 * Math.random(); // Scale between 1 and 1.2
                let rotatePhoto = 10 * Math.random() - 5;  // Rotation between -5 and 5 degrees
                let scaleBuffer = 1 + 0.2 * Math.random(); // Scale between 1 and 1.2
                let rotateBuffer = 10 * Math.random() - 5;  // Rotation between -5 and 5 degrees

                // Randomize positions
                let leftPhoto = 50 * Math.random(); // Left position between 0 and 100px
                let leftBuffer = 100 * Math.random() - leftPhoto;

                $('.photo_big').css({
                    'transform': `scale(${scalePhoto}) rotate(${rotatePhoto}deg)`,
                    'left': `${leftBuffer}px`,
                    'opacity': Math.random()
                });

                $('.buffer').css({
                    'transform': `scale(${scaleBuffer}) rotate(${rotateBuffer}deg)`,
                    'left': `${leftPhoto}px`,
                    'opacity': '1'
                });

                imgcentered('.photo_player');
            }

        }, 3200);
    }
}


$(document).on( 'click', '.play_club', function(e){
	   e.preventDefault();
	   e.stopPropagation();
		$('.pnums').hide();
	    parentid = type_id;
		$('.photo_player').show();
		$('.uploadcount').hide();
		
		//			club_srcs = data.split(',');
			//		frames = club_srcs.length;
				//	counter = 0;
					player_paused = false;
					photoPlay();	

		/*
	    $.ajax({
				url: '/wp-content/themes/album2/get_club_srcs.php',
				type: 'POST',				
				data: {id: parentid,nlevel: level }, 
				success: function(data)
				{
					$('.spinner').detach();
					club_srcs = data.split(',');
					frames = club_srcs.length;
					counter = 0;
					player_paused = false;
					photoPlay();	

				} 
			}); 			
		*/
});

$(document).on( 'click', '.hplay', function(e){
	   e.preventDefault();
	   e.stopPropagation();

	if (level<4)
		 {
	           
	   		$( ".helper .hint").hide();
	   		$('.helper').fadeIn(160,function(){$(this).removeClass('hidden')});
		    htop = 0;
	   		$( ".helper .hint[bind='.select_item']" ).each(function() {
			 	 help_elem = $(this).attr('bind')+':visible';
			 	 help_elem = $(help_elem);
			 	  $(this).show();
			 	 coord_el = $(this);
			 	 SetCoords(help_elem, coord_el);
			}); 
    		return;
	      } 	

	   player_paused = false;
	    ll = $('.lmenu_item span').length;
	    text = $('.lmenu_item span').eq(ll-2).text() + ' ' + $('.lmenu_item span').eq(ll-1).text() ;
	    help_text(text);
		$('.photo_player').show();

//		club_srcs = data.split(',');
//		frames = club_srcs.length;
		counter = 0;
		photoPlay();	

	   /* $.ajax({
				url: '/wp-content/themes/album2/get_club_srcs.php',
				type: 'POST',
				
				data: {id: type_id, nlevel: level}, 
				success: function(data)
				{
					$('.spinner').detach();
					club_srcs = data.split(',');
					frames = club_srcs.length;
					counter = 0;
					photoPlay();					 				
				} 
			}); 		*/	
		
});
$(document).on( 'click', '.photo_player .fa-stop', function(e){


})

$(document).on('click','.fa-comment', function(event) {
    event.preventDefault();

    

    // Scroll to comment section within the Lightbox
    setTimeout(function() {
        $('body').animate({
            scrollTop: $('.lightbox_comments').offset().top
        }, 1000); // Duration of the scroll in milliseconds
    }, 500); // Delay to ensure Lightbox is fully opened
});


$(document).on( 'click', '.photo_player .fa-play', function(e){
	$(this).hide();
 	player_paused = false;
	$('.fa-pause').show();
	photoPlay();
})

$(document).on( 'click', '.photo_player .fa-pause', function(e){
	clearInterval(ph_play);
	player_paused = true;
	$('.photo_player .fa-play').show();
	$(this).hide();
})


$(document).on( 'mousemove', '.photo_player img', function(e){
 	$('ptools').show();
});


var player_paused = true;

$(document).on( 'click', '.wclose', function(e){
  clearInterval(ph_play);
  paused = true;
  $('.pnums').show();
  $('.uploadcount').show();
  $('.photo_player').hide();
  help_text_hide();
  $('.photo_big').css('opacity','0');
});
function deleteById(arr, idToDelete) {
	return arr.filter(item => item.id !== idToDelete);
}

function delete_el(){
	if (!$('.n-trash').hasClass('n-active')){
		if (parseInt(level)!=-1)
		{	
			if (typeof vkalbums!='undefined'){
				vkalbums = deleteById(vkalbums, del_parentid);
			}

			$.ajax({
				url: '/wp-content/themes/album2/delete_elem.php',
				type: 'POST',
				dataType: 'json',
				data: {id: del_parentid,type_id: type_id}, 
				success: function()
				{
					//get_clubs(type_id,level,5);			
				}
			});
		}
		else{
			$.ajax({
				url: '/wp-content/themes/album2/delete_histid.php',
				type: 'POST',
				dataType: 'json',
				data: {delete_id: window.del_parentid, hist_id: type_id}, 
				complete: function(data)
				{
					//get_clubs(type_id,level,5);			
					
				}
			}); 	
		}
		$('.message .close').click();
		$('[data-id=' + parseInt(del_parentid)+']').hide('fast', function(){ 
			$('[data-id="' +del_parentid+'"]').remove(); 
			update_menu_height();
		}); 
		//get_clubs(type_id,level,5);	
		
		$('.message').fadeOut('fast');
		$('.wfade').fadeOut('fast');
	} else {
		$('.message').removeClass('deleteinfo');
		var del_parentids = [];
		del_parentids.push(del_parentid);
		$(`[data-id=${del_parentid}]`).css('opacity','0.1');
		clean_trash(del_parentids)
	}
}

function clean_trash(del_parentids) {
	window.total_size = 0;
	window.delete_count = 1;
	//$(`[data-id=${del_parentid}]`).detach();

	message("<p style='color:#ff8800;font-size:20px;'>Получаем данные</p>", 'Информация об удаление', '', 'close');
	$('.message').addClass('deleteinfo');
    $.ajax({
        url: '/wp-content/themes/album2/clean_trash.php',
        type: 'POST',
        dataType: 'json',
        data: { id: del_parentids, func: 'get_all_branch_ids' },
        success: function(response) {
            const branchIds = response;
            $('.spinner').detach();
            processBranch(branchIds, 0);
        },
        error: function(xhr, status, error) {
            console.error("AJAX Error:", status, error);
        }
    });
}

function processBranch(branchIds, index) {
    if (index >= branchIds.length) {
		total_size =(window.total_size / (1024 * 1024)).toFixed(2) + 'Mb'
		html = $('.message .info').html();
		html+= `Удалено: <b>${total_size}</b> / из ${window.delete_count}x10 файлов<br><p style='color:#ff8800;text-align: center;font-size:20px;'>Удаление завершено!</p>`;
		html = $('.message .info').html(html);
		$('.info').scrollTop($('.info')[0].scrollHeight);
        return; // All branches processed
    }

    const branchId = branchIds[index];

	html = $('.message .info').html();
	html+= `<br> <b>Получаем из ${branchId}</b>  <br>`;
	html = $('.message .info').html(html);
	$('.info').scrollTop($('.info')[0].scrollHeight);

    $.ajax({
        url: '/wp-content/themes/album2/clean_trash.php',
        type: 'POST',
        dataType: 'json',
        data: { id: branchId, func: 'parent_ids' },
        success: function(parentResponse) {
            const parentIdsArray = Object.entries(parentResponse);
            processFilesInBatch(branchId, parentIdsArray, 0, function() {
                processBranch(branchIds, index + 1);
            });
        },
        error: function(xhr, status, error) {
            console.error("AJAX Error:", status, error);
        }
    });
}

function processFilesInBatch(branchId, parentIdsArray, startIndex, callback) {
    const limit = 10; // Set your desired limit for batch size

    if (startIndex >= parentIdsArray.length) {
        callback(); // All batches processed
        return;
    }

    const filesBatch = parentIdsArray.slice(startIndex, startIndex + limit).map(entry => ({
        id: entry[0], // Include the id
        file: entry[1] // Include the file
    }));

    $.ajax({
        url: '/wp-content/themes/album2/clean_trash.php',
        type: 'POST',
        dataType: 'json',
        data: { id: branchId, files: filesBatch, func: 'delete_file' },
        success: function(deleteResponse) {
            console.log("Files deleted successfully:", deleteResponse);
			deleteResponse.guid
			deleteResponse.total_size
			window.total_size+=deleteResponse.total_size;
			window.delete_count++;
			html = $('.message .info').html();
			total_sizes =(window.total_size / (1024 * 1024)).toFixed(2) + 'Mb'
			html+= `<b>${window.delete_count}</b> ${deleteResponse.guid} <b>(${deleteResponse.total_size})</b> Всего: ${total_sizes} <br>`;
			html = $('.message .info').html(html);
			$('.info').scrollTop($('.info')[0].scrollHeight);
            processFilesInBatch(branchId, parentIdsArray, startIndex + limit, callback);
        },
        error: function(xhr, status, error) {
            console.error("AJAX Error:", status, error);
        }
    });
}


// подтвердить удаление элементов
$(document).on( 'click', '.lightbox__button-delete-ok', function()
{
	$.ajax({
		url: '/wp-content/themes/album2/delete_elem.php',
		type: 'POST',
		dataType: 'json',
		data: {id: created_parentid}, 
		success: function(data)
		{
			get_clubs(type_id,level,5);			
		}
	});
	
	$('[data-id="' + created_parentid+'"]').hide('fast', function(){ $('[data-id="' + created_parentid+'"]').remove(); 
		$('.lightbox__button-delete-ok').click(); //костыль
		update_menu_height();
     }); 
	
	
  	$('.lightbox__edit').hide();
  	$('.lightbox').hide();
});


// отменить удаление элементов
$(document).on( 'click', '.lightbox__button-delete-no', function()
{
	$('.lightbox__edit').hide();
	$('.lightbox').hide();
});

  $(document).on('click','.bpress-nav div',function(){
  	   $('.bpress-nav div').removeClass('n-active');
	   $(this).addClass('n-active');
  });

  $(document).on('click','.bpress-nav .n-blog',function(){
 	   $('#item-body').slideDown('fast');
 	   $('.wall').slideUp('fast');  	
  });


  $(document).on('click','.bpress-nav .n-list',function(){
   	 $('#item-body').slideUp('fast');
   	 $('.wall').slideDown('fast');  
	 

  });

  

$(document).on( 'click', '.status', function(e)
{	
	e.preventDefault();
	e.stopPropagation();
	pending = $(this).parent().hasClass('pending');
	processed = false; 
	if((pending && (batch != 'unpublishall')) || (pending && (batch == 'publishall'))){
		
		
		$.ajax({
			url: '/wp-content/themes/album2/published.php',
			type: 'POST',
			dataType: 'json',
			data: {id: $(this).parent().attr('id'), status: 'publish'}, 

		});
		$(this).parent().removeClass('pending');

		return;
	}

	
	if((!pending && (batch != 'publishall'))||((!pending) && (batch == 'unpublishall'))){
		$.ajax({
			url: '/wp-content/themes/album2/published.php',
			type: 'POST',
			dataType: 'json',
			data: {id: $(this).parent().attr('id'), status: 'pending'}, 

		});
		$(this).parent().addClass('pending');
		
		return;
	} 
	
});


$(document).on( 'click', '.publishall', function(e)
{	
	e.preventDefault();
	e.stopPropagation();
	batch = 'publishall';
	$('.status').click();
	setTimeout(function(){batch = '';},4000); 
});


$(document).on( 'click', '.unpublishall', function(e)
{	
	e.preventDefault();
	e.stopPropagation();
	batch = 'unpublishall';
	$('.status').click();
	setTimeout(function(){batch = '';},4000); 
});


 
$(document).on( 'click', '.deleteall', function(e)
{	e.preventDefault();
	if ($('.n-active').hasClass('n-trash')){
		message('Вы действительно удалить хотите ветку?','Подтвердите','que','yes,no',delete_all);
	} else{	
		message('Вы действительно удалить хотите ветку?','Подтвердите','que','yes,no',delete_all2);		
	}
});
function delete_all2(){
	
		batch = 'deleteall';
		$('.clubs .album_img .delete_club').click(); 
		setTimeout(function(){batch = '';},4000); 
		$('.wfade,.message').fadeOut('fast');
}		
 function delete_all(){
        // alert('delete_all');
	   // e.preventDefault();
		//e.stopPropagation();

		 
		let del_parentids = $('.selected').parent().map(function() {
			    $(this).parent().css('opacity','0.1');
				return $(this).parent().attr('id');
		}).get();

		clean_trash(del_parentids) 
}

function delete_all2(){
		var allData = ''; // Initialize a variable to store all data

		$('.selected').each(function() {
		    var id = $(this).data('id'); // Assuming you have an identifier for each item to delete
		    $.ajax({
		        url: 'fdelete_all.php',
		        method: 'POST', // Assuming you want to use POST method
		        data: { id: id }, // Sending the id to the server
		        success: function(data) {
		            // Concatenate the data from each request
		            allData += data;
		        },
		        error: function(xhr, status, error) {
		            // Handling errors, if any
		            console.error(error);
		        },
		        complete: function() {
		            // Check if all AJAX requests are completed
		            if ($('.selected').length === $('.selected').filter('[data-processed]').length) {
		                // Display a message with all data combined
		                message('msg', 'Информация об удалении', allData, 'close');
		            }
		        }
		    }).data('processed', true); // Mark the element as processed to track completion
		});
}

$(document).on('click','.n-stat',function(){
	spn('.stat');
	$('.stat').load( THEME_DIR + 'get_stat.php', {id: type_id, start: level} );	
});
$(document).on('click','.n-import',function(){
	$('.import').show();
});
$(document).on('click','.n-trash', function(){
	spn('.trash');
	setTimeout(function(){spn('.trash');},1000);
	get_trash(type_id, level, 5);
});

$(document).on('click','.n-list', function(){
	spn('.list');
	get_list(type_id, level, 5);
	
	
    tab = 'list';
	freshhistory();
	
});

$(document).on('click','.n-params', function(){

  


	$('.params').load( THEME_DIR + 'get_params.php', {}, function(){  
			//    spn('.params');			      
 						
	});
	/*
	$.ajax({
		type: 'POST',
		url: '/wp-content/themes/album2/set_rels.php',
		dataType: 'json',
		data: {func: 'get_ids'},
		success: function(data){
          branches = data;
          last_id  = branches[0]['last_id'];
          max_id   = branches[0]['max_id'];
          last_id  = branches[0]['last_id'];
          last_ind = branches[0]['last_ind'];        
          total    = branches[0]['total'];
          //$('.params .progress .bar').css('width',0 + 'px'); 
          procent = 100*last_ind/total,3; 
          procent = 0;
          procent =  procent.toFixed(3);
          $('.params svg').parent().detach();
          $('.params .progress .procent').html(procent + '%');  
          $('.last_ind').html(0);
          $('.total_ind').html(total); 
		}
	});		

	*/
});
 
var i = 1;
$(document).on('click','massindex .start_ind', function(){  
   if ($(this).hasClass('stop_i')){

   	   $(this).removeClass('stop_i');
   	   $(this).html('Запустить');
   } else{

	  $(this).addClass('stop_i'); 
	  $(this).html('Остановить');  
   }
   
   length = branches[0]['length'];   

   function send(i,el){
		$.ajax({
			type: 'POST',
			url: '/wp-content/themes/album2/set_rels.php',
			dataType: 'json',
			data: {func: 'set_ids', id: branches[i]['ID'] },
			success: function(data){
	          
	          last_id  = branches[0]['last_id'];
	          max_id   = branches[0]['max_id'];
	          last_id  = branches[0]['last_id'];
	          last_ind = branches[0]['last_ind'];        
	          total    = branches[0]['total'];
			  $('massindex .last_ind').html(i);
			  procent = 100*i/total,3; 
		      procent =  procent.toFixed(3); 
              $('massindex .tsize').html(data[0]+' индексов');
		      $('massindex .params .progress .bar').css('width',10*procent + 'px'); 		       
		      $('massindex .params .progress .procent').html(procent + '%');  

		          
		      $('massindex .total_ind').html(total);
	          i++;
	          
	          if ((i < length)&&(el.hasClass('stop_i'))){
				send(i,el);
		      }	
		      else
		      {
		      	el.removeClass('stop_i');
				el.html('Запустить');
				i = 1;
		      }

	        },
	        error: function(){	        	
	        	setTimeout(send(i,el), 1000);
	        }
		});	  
 }

   send(1,$(this));
 
        
});

$(document).on('click',"checkimg .check_ind",function(){
	start = $('#c_id').val();
    spn('checkimg');
	$.ajax({
	
			type: 'POST',
			url: '/wp-content/themes/album2/clean_full.php',	
			data: {func: 'check_id',offset: start },
			success: function(data){	
    			message(data,'Проверка на диске','inf','close'); 
			}
		  });
  
});

$(document).on('click','deleteorig .start_ind', function(){  
   start = $('deleteorig #s_id').val();
   bytes = 0;
   i = start;
   if ($(this).hasClass('stop_i')){
   	   $(this).removeClass('stop_i');
   	   $(this).html('Запустить');
   	   $('#s_id').val(i)
   } else{
	  $(this).addClass('stop_i'); 
	  $(this).html('Остановить');  
   } 
   $('.mbytes').html('0');
    el = $(this); 
   function send1(i,el){ 

		$.ajax({
			type: 'POST',
			url: '/wp-content/themes/album2/clean_full.php',	
			data: {func: 'clean_id',offset: i },
			success: function(data){	      
			  data = data.split(',');
			  size = data[0];
			  url = data[1];
			  if ($('.dels a').length>20){
			  	  $('.dels').html('');	
			  } 
			  $('deleteorig .origs').append('<a href='+url+' target="_blank">'+url+'</a><br>');
 			  size = parseFloat(size.replace(/\s/g, ''));
			  if (isNaN(size)) size = 0;
        	  bytes = bytes  + size;  

        	  $('deleteorig .mbytes').text((bytes/1024/1024).toFixed(2));

			  $('deleteorig .last_ind').html(i);
			  procent = 100*i/total,3; 
		      procent =  procent.toFixed(3); 
              $('deleteorig .tsize').html(data[0]+'оригиналов');
		      $('deleteorig .params .progress .bar').css('width',10*procent + 'px'); 		       
		      $('deleteorig .params .progress .procent').html(procent + '%');		          
		      $('deleteorig .total_ind').html(total);
	          i++;
	          
	          if ((i < parseInt(total.replace(/\s/g, '')))&&($('deleteorig .start_ind').hasClass('stop_i'))){
			 	send1(i,el);
		      }	
		      else
		      {
		      	el.removeClass('stop_i');
				el.html('Запустить');
				i = start;
		      }

	        },
	        error: function(){	         	
	        	setTimeout(send1(i,el), 1000);
	        }
		});	  
	 }

   	$.ajax({
			type: 'POST',
			url: '/wp-content/themes/album2/clean_full.php',
			dataType: 'json',
			data: {func: 'get_id', offset: 0 },
			success: function(data){	
			total    = data[0]['total'];
  		    send1(i,$(this));
 			} 
    });    
});

$(document).on('click','cleantrash .start_ind', function(){  
   start = $('cleantrash #d_id').val();
   bytes = 0;
   i = start;
   if ($(this).hasClass('stop_i')){
   	   $(this).removeClass('stop_i');
   	   $(this).html('Запустить');
   	   $('#s_id').val(i)
   } else{
	  $(this).addClass('stop_i'); 
	  $(this).html('Остановить');  
   } 
   $('.cleantrash .mbytes').html('0');
    el = $(this); 
   function send1(i,el){ 

		$.ajax({
			type: 'POST',
			url: '/wp-content/themes/album2/clean_trash.php',	
			data: {func: 'clean_id',offset: i },
			success: function(data){	      
			  data = data.split(',');
			  size = data[0];
			  url = data[1];
			  if ($('.cleantrash .origs a').length>20){
			  	  $('.cleantrash .origs').html('');	
			  }
			  $('cleantrash .origs').append('<a href='+url+' target="_blank">'+url+'</a><br>');
 			  
 
			  size = parseFloat(size.replace(/\s/g, ''));
			  if (isNaN(size)) size = 0;
        	  bytes = bytes  + size;  
        	  $('cleantrash .mbytes').text((bytes/1024/1024).toFixed(2));

			  $('cleantrash .last_ind').html(i);
			  procent = 100*i/total,3; 
		      procent =  procent.toFixed(3); 
              $('cleantrash .tsize').html(data[0]+'изображений');
		      $('cleantrash .params .progress .bar').css('width',10*procent + 'px'); 		       
		      $('cleantrash .params .progress .procent').html(procent + '%');		          
		      $('cleantrash .total_ind').html(total);
	          i++;
	          
	          if ((i < parseInt(total.replace(/\s/g, '')))&&($('cleantrash .start_ind').hasClass('stop_i'))){
			 	send1(i,el);
		      }	
		      else
		      {
		      	el.removeClass('stop_i');
				el.html('Запустить');
				i = start;
		      }

	        },
	        error: function(){	         	
	        	setTimeout(send1(i,el), 1000);
	        }
		});	  
	 }

   	$.ajax({
			type: 'POST',
			url: '/wp-content/themes/album2/clean_trash.php',
			dataType: 'json',
			data: {func: 'get_id', offset: 0 },
			success: function(data){	
			total    = data[0]['total'];
  		    send1(i,$(this));
 			} 
    });    
});




		function  statreload(){	
			if ($('.n-stat').hasClass('n-active')){
				//$('.stat').load( THEME_DIR + 'get_stat.php', {id: type_id, start: level} );
				//$('.stat').activity({segments: 12, width: 5.5, space: 6, length: 13, color: '#252525', speed: 1.5});
		    }
		}
var htop = 0;		
var set_top = 0;
var set_left = 0;
function SetCoords(page_el, coord_el){
		 nth = coord_el.attr('eq');

	 	 minheight = coord_el.attr('minheight');
	 	 length = page_el.length;
	 	 if (minheight == undefined) {minheight=0}
	 	 if (nth == undefined) {nth=1;}	 	 
	 	 if (nth > length){length = 0;}
	 	 if (coord_el.hasClass('hint')) {nth = parseInt(nth)-1;}
	 	 else {nth = parseInt(nth);}
	 	// if (page_el.hasClass('hint')) {nth = parseInt(nth)-1; } else {nth = parseInt(nth)-2;}
	 	 if ((length!=0)&&(page_el.eq(nth).height()>minheight)) {   

		 	 el_width = page_el.eq(nth).width();
		 	 el_height = page_el.eq(nth).height();
		 	 oldhtop = htop;
		 	 hleft = page_el.eq(nth).offset().left;
		 	 htop = page_el.eq(nth).offset().top;
		 	 if ((htop>oldhtop-10)&&(htop<oldhtop-10)) {htop = htop + coord_el.height(); }
		 	 coord_el.show('fast');

		 	 ml = 0;
		 	 if (!coord_el.hasClass('hint')){ml=el_width/2;}
		 	 
		 	 set_left = hleft+el_width-ml;
		 	 set_top = htop+(el_height-coord_el.height())/2;
		 	 
		 	 coord_el.css('left', set_left);
		 	 coord_el.css('top', set_top);	 	 
	 	} else {
	 		if (coord_el.hasClass('hint')) {coord_el.hide('fast');  }
	 	}

	 	
};

$(document).on('click','#how_help',function(){
	$('.helper').fadeIn(160,function(){$(this).removeClass('hidden')});
	htop = 0;
	$( ".helper .hint" ).each(function() {
	 	 help_elem = $(this).attr('bind')+':visible';
	 	 help_elem = $(help_elem);
	 	 coord_el = $(this);
	 	 SetCoords(help_elem, coord_el);
	});
	$('.hint[bind="li.select_item"').hide();
});



var commands = [];
commands[0] = ['.club_icon img',5,1200, 'Кликните левой кнопкой мыши по клубу, чтобы увидеть его альбомы'];
commands[1] = ['.album_icon',3,1200, 'Кликните левой кнопкой мыши по альбому, чтобы увидеть фотографии'];
commands[2] = ['.album_img',3,1200, 'Кликните левой кнопкой мыши по фотографии, чтобы увидеть ее на полном экране'];
commands[3] = ['.ligtbox__img_right',1,1200,'Листайте фотографии, кликая левой кнопкой мыши по стрелочке'];
commands[4] = ['.ligtbox__img_right',1,1200,'Листайте фотографии, кликая левой кнопкой мыши по стрелочке'];
commands[5] = ['.ligtbox__img_left',1,1200, 'Листайте фотографии, кликая левой кнопкой мыши по стрелочке'];
commands[6] = ['.lightbox__button-exit',1,1200, 'Чтобы закрыть нажмите левой кнопкой мыши ны крестик'];
commands[7] = ['.select_item .select_item_img',2,1200, 'Кликните левой кнопкой мыщши, чтобы перейти в нижний раздел'];
commands[8] = ['.lmenu_item',2,1200,'Кликните левой кнопкой мыши, чтобы вернуться в верхний раздел'];
commands[9] = ['.lmenu_item',1,1200,'Кликните левой кнопкой мыши по выбранному городу, чтобы увидеть все города'];



var howadd = [];
howadd[-1] = ['.select_item[data-id=4]',0,1200, ''];
howadd[0] = ['.select_item[data-id=23591]',0,1200, 'Выберете город'];
howadd[1] = ['.select_item[data-id=31557094]',0,1200, 'Выберете ветку'];
howadd[2] = ['.select_item[data-id=31818086]',0,1200, 'Выберете ветку'];
//howadd[3] = ['.select_item[data-id=574792]',1,1200,'Листайте фотографии, кликая левой кнопкой мыши по стрелочке'];
howadd[3] = ['.add',1,1200,'Нажмите "+", чтобы добавить альбом'];

var howupload = [];
howadd[-1] = ['.select_item[data-id=4]',0,1200, ''];
howupload[1] = ['.select_item[data-id=23591]',0,1200, 'Выберете город, например Владимир'];
howupload[2] = ['.select_item[data-id=31557094]',0,1200, 'Выберете вид спорта'];
howupload[3] = ['.select_item[data-id=31818086]',0,1200, 'Выберете тип спорта'];
howupload[4] = ['.select_item[data-id=598638]',0,1200, 'Выберете раздел'];
howupload[5] = ['.select_item[data-id=598885]',0,1200, 'Выберете альбом']; 
//howadd[3] = ['.select_item[data-id=574792]',1,1200,'Листайте фотографии, кликая левой кнопкой мыши по стрелочке'];
howupload[6] = ['.nav .upload',1,1200,'Нажмите "загрузить", чтобы закачать фото альбом'];

//commands[1] = ['.n-list',1,2000];  
//commands[0] = ['.lmenu_item',0,3000];
/*commands[3] = ['.album_icon',2,1500];*/

 add_enable = true;    


function domacros(page_el,page_prev, eq, cursor_el,time, text) { 
									cursor_el.attr('eq',eq-1);
	 								if (page_el.length>=eq){
		 									SetCoords(page_prev, cursor_el); 
		 									//SetCoords(page_prev, $('.pulsar')); 
		 									$('.pulsar').css('top',set_top+'px');
		 									$('.pulsar').css('left',set_left+'px');
		 									//cursor_el.html(page_el.attr('class')+';'+cursor_el.css('top')+','+cursor_el.css('left')+';eq:'+eq+';time:'+time);
		 									
		 									

		 									var page_el1=page_el;
		 									function clicker() {
	 										  //page_el1.eq(eq).delay(time+500).trigger('click');
		 										page_el1.delay(time+500).click();
		 									}
		 									function flicker() {
	 											
		 									 		$('.pulsar').fadeIn('slow');
			 									    $('.pulsar').delay(500).fadeOut('fast');	}		 										

		 									setTimeout(clicker,time);
		 									setTimeout(flicker,time-500);
		 								}
	 								} 

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}
var macros_timer;
// RunMacros([1,])
function RunMacros(macros){
	cursor_el = $('.cursor');
	page_prev = $('.empty');
	htop = 0;
	time = 1000;

	
	var index = 0;

	function tick() {
		
		if (index<macros.length){
	 		row = macros[index]
	 		
	 		class_page_el = row[0]; //класс вызываемого элемента
			
	 		page_el = $(class_page_el);

	 		if (page_el.length>0){
	 			hint_text =row[3]; // Пояснялка
	 		} else{
	 			hint_text = '';
	 		}

	 			row = macros[index];
	 			hint_text =row[3]; 
	 			
	 			page_el = row[0]; //класс вызываемого элемента
	 			
	 			class_page_el = row[0];  
	 			page_el = $(class_page_el);
	 		   
	 		//   } 
	 		   

	 		if (hint_text!=''){
				$('.help_text').animate({width:'show'},350);
				$('.help_icon').show();
		 		$('.help_text').text(hint_text);
				//$(".help_text").letterfx({"fx":"fade","backwards":false,"timing":50,"fx_duration":"200ms","letter_end":"restore","element_end":"restore"});
			} else {
				//$('.help_text').hide({width:'hide'},350);
				//$('.help_icon').hide(350);
			}	   
	 		eq = row[1]; //номер вызываемого элемента 
	 		time = row[2]; //интервал через который вызвать событие; 

	 		cursor_el.css('transition: ',row[2]/800+'s'); 
	 		//cursor_el.css('transition: left',row[2]*3/(200+(300*Math.random()))+'s');  

	 		cursor_el.attr('eq',parseInt(eq));  
	 		//alert(index);
	 		if (page_el.length>0){ 			
	 		//	index++;
		 	    domacros(page_el,page_el, eq, cursor_el, time);
		 		//alert(index);
		 	}		
	 		else {  
	 			//alert('нет:'+row[0]);
 		
 			} 
 		} else {
			$('.help_text').hide({width:'hide'},350);
			$('.help_icon').hide(350);
			cursor_el.hide();
			index = 0;
			clearInterval(macros_timer);
		}
 
 		page_prev = page_el;
 		index=index+1;
 		//$('header').html($('header').html()+row[0]);
 	}
 	tick();
	macros_timer = setInterval(tick,5000);

}

$(document).on('click','.cursor',function(){
//	RunMacros(commands);
	
});

function help_text(hint_text, dl){
	$('#deg').change();
	if (hint_text!=''){
			//$('.help_text').animate({width:'show'},350);
			$('.help_text').show();
			$('.help_icon').show();
			if (typeof dl != 'undefined'){
						$('.help_text').delay(dl).animate({width:'hide'},350);
						//$('.help_icon').delay(dl).hide(360);
						$('.help_text').delay(dl).show();
			}

			$('.help_text').text(hint_text);
			//$(".help_text").letterfx({"fx":"fade","backwards":false,"timing":50,"fx_duration":"100ms","letter_end":"restore","element_end":"restore"});
	}

	
}
function help_text_hide(){
			  $('.help_text').animate({width:'hide'},150);
			  $('.help_icon').hide();
	}
function toggle_about(){
 	if ($('header').hasClass('main')){ 
 		$('header').removeClass('main');
		$('.anno').hide('slow'); 		
 		setTimeout(
 			function(){$('.anno').letterfx({"fx":"fade","backwards":false,"timing":50,"fx_duration":"1000ms","letter_end":"restore","element_end":"restore"})},1600);
		$('.tools').show();
 		
 		$('.usr').fadeIn('middle');
 		$('.about').addClass('hidden');
 		$('.about').delay(300).slideUp('slow');
 		$('#gsearch').show('fast');
 		
 	} else{
		$('.tools').hide();
 		$('.anno').show('slow');
 	
	 	$('header').addClass('main');
	 	$('.usr').fadeOut('middle');
	 	$('.about').delay(300).slideDown('slow');
	 	$('#gsearch').hide('fast');
	 	setTimeout(function(){$('.about').removeClass('hidden')},600); 
 	}	
}

$(document).on('click','header',function(){

});
$(document).on('click','.importzip',function(){

	$('#localalbums').show();
})

$(document).on('keypress','body',function(){ 
	$('.help_text').hide({width:'hide'},350);
	$('.help_icon').hide(350);
	cursor_el.hide();
	index = 0;
	clearInterval(macros_timer);
	
});

$(document).on('click','#about', function(){
	toggle_about();

}); 
$(document).on('click','.labout', function(){
	toggle_about();

}); 

$(document).on('click','.gobutton', function(){
	toggle_about();
	get_selected_level(level, type_id); 
});

$(document).on('click','#how_watch',function(){
	$('.cursor').show();
	RunMacros(commands);
});


$(document).on('click','#how_add',function(){
	$('.cursor').show();
	RunMacros(howadd); 
});


$(document).on('click','#how_upload',function(){
	$('.cursor').show();
	RunMacros(howupload); 
});

$(document).on('click','.helper',function(){
	$('.helper').fadeOut(160,function(){$(this).addClass('hidden')});
});
		setInterval(statreload, 2000);
 
batch = '';


  if (window.history && window.history.pushState) {

    $(window).on('popstate', function(e) {      
    	e.preventDefault();
    	$('.select_item[data-pid="'+type_id+'"]').hide();
    	$('.pnums .active').removeClass('active');	
      	$('.l-active').removeClass('l-active');

      if (window.history.state!=null){
    	type_id = window.history.state.type_id;
		level   = window.history.state.level; 
		parid   = window.history.state.parid; 
		page  =  window.history.state.page; 
		sel_top = window.history.state.sel_top; 
		
		//$('.breadcrumbs a[data-id=' + type_id + ']').eq(0).click();
		if (level == 6){level = 5; type_id = parid;}
        main_ind(); 
        if (level<5){ 
		    get_clubs(type_id, level, 5);
		    get_selected_level(level, type_id); 
		}
		else{
			get_child();
			get_selected_level(4, parid); 
		} 
		if (level<6){$('.lightbox__button-exit').click();}
		get_branch(level);
		
		update_menu_height(sel_top); 


	  }
     // if (count==1){$('.next').click(); window.history.pushState('back', null, './#forward');}
    });
 
  } 

  $(document).on('dragstart', 'img', function(event) { 
  	event.preventDefault(); 
  });   

  dragstart = false; 
  dragel = null;
  sX = 0;
  sY = 0;
  $(document).on('dragstart', '.select_item, .album_icon, .club_icon, .album_img ', function(event) {     
    $('.dragger').empty();
    
   // if ((event.offsetX<60)&&(event.offsetY<60)){
    	 
    

    $(this).clone().appendTo(".dragger"); 
    $('.dragger>*').hide();
    $('.dragger>div').css('position','absolute'); 
    dragstart = true;
    sX = event.pageX;
    sY = event.pageY;
    if ($(this).hasClass('select_item')){
    	
          dragid = $(this).attr('id');
    }
    else{
	  	  dragid = $(this).attr('data-id');
    }
    dragel = $(this);
    $('.lmenu_item, .select_item').css('cursor','default');
  //  }
  });   

  $(document).on('mousemove', function(event) {
  	dX = event.pageX;
  	dY = event.pageY;

    if ((dragstart&&admin)&&(((dX-sX)*(dX-sX) + (dY-sY)*(dY-sY))>3300))  { 

	  	 $('.dragger>*').css('top',event.pageY);  
	  	 $('.dragger>*').css('left',event.pageX);  
		 if ($('.dragger>*').css('display')=='none') {$('.dragger>*').show('slow');} 

		// 

	  	  }
	else {
	
	}
  	 
  })
  function DragInObj(obj){
  		if (
  			(event.pageY>obj[0].offsetTop)&&
		    (event.pageY<(obj[0].offsetTop+$('.club-menu')[0].offsetHeight))&&
   		    (event.pageX>obj[0].offsetLeft)&&
		    (event.pageX<(obj[0].offsetLeft+$('.club-menu')[0].offsetWidth))) {
  			return true;
  		}
  }

  $(document).on('mouseup','.dragger', function(event) {
    
	//if (DragInObj($('.club-menu')))	{					
	//		$('.dragger>.select_item').hide('fast'); }

	 //if (DragInObj($('.select_item:visible').eq(0)))	{					
		//	 }

		/*else {
			dragstart = false;
			$('.dragger>.select_item').hide();
		} (*/
	});

	// клики по элементу верхнего меню
	$(document).on( 'mouseup', '.lmenu_item', function(e)
	{	
	if (!dragstart){

		e.preventDefault;
		main_ind(); 
		$('.find').val(''); 
		level = $(this).data('level');
		type_id = $(this).attr('id');
		parid =  $(this).attr('id');
		$('body').scrollTop(0);
		$('.dz-fullprogress,.uploadcount').hide();
		freshhistory();
		$('.l-active').removeClass('l-active');
		page = 0; 
		

	   
	    mi = 0;
	    curr = $(this).index();
	    length = $('.lmenu_item').length;
		for (var mi = 0; mi<=length+1;   mi++)
		{   

			if (mi>curr){

				$('.lmenu_item').eq(curr+1).detach();
			}
			

		}
		
		//$('.lmenu_item').filter(function(){ return $(this).data('level') > level; }).detach();
	 
		get_selected_level(level,type_id);
		get_select(level);
		update_menu_height();

        if (dragstart) {
			if ((dragid!=parid)&&(dragid>0)&&(parid>0)){
			    $.ajax({
			    	type: 'POST',
						url: '/wp-content/themes/album2/change_parent.php',
						data: {id: dragid, parent_id: parid}
					});
	 		}
 	    }  

		if (level < 5){
			if ($('.clubs').css('display')!='none'){
			get_clubs(type_id, level, 5);}
			$('.l-active').removeClass('l-active');
		}
		

		if (level == 5){
			get_child();

		} else { 
			if ($('.list').css('display')!='none'){
				spn('.list');
			    get_list(type_id, level, 5);
			} 
			
			if ($('.trash').css('display')!='none'){
		    	spn('.trash');
		    	tpage = 0;
				get_trash(type_id, level, 5);
			
			}
		} 
	}
	});


   $(document).on('mouseup','.lmenu_item, .select_item, .club_icon, .album_icon', function(event) {     
       dX = event.pageX;
       dY = event.pageY; 
 	   
   	  if ((dragstart&&admin)&&(((dX-sX)*(dX-sX) + (dY-sY)*(dY-sY))>1300)){
	   	    
	   	    dragstart = false; 
	   	    parid = $(this).attr('id');
			datalevel = $(this).attr('data-level'); 
	   	    if ($(this).hasClass('select_item')){ 
	   	    	datalevel = parseInt(datalevel)+1;
				el = $('.select_item[parid='+dragid+']');
	   	    	el.each(function() {
	   	    		$(this).attr('datalevel', datalevel+1);
	   	    		if ((datalevel+1)==4){
	   	    			$(this).removeClass('selectclubs');
	   	    			$(this).addClass('selectalbums');	   	    		
	   	    		}

	   	    	
	   	    	});
	   	    }
	   	    if ((dragid!=parid)&&(dragid!=undefined)&&(dragid!=0)){
	   	    
		   	    //$('.lmenu-sub .select_item[data-id='+dragid+']').slideUp('fast', update_menu_height());
		   	   

		   	    $('.select_item[data-id='+dragid+']').attr('parid', parid);
		   	    $('.select_item[data-id='+dragid+']').attr('data-level', datalevel);
		   	    $('.dragger>.select_item').hide('fast', function(){$('.dragger').empty();});
		 
		   		
				$('.lightbox__content').empty();
				$('.lightbox__content').append("<button class='lightbox__button-exit dashicons dashicons-no-alt'></button>"); 
				
				message('Вы действительно хотите переместить?','Подтвердите','que','yes,no',move_el);
				//showlightbox(true); 

		    }
		   	
   	     }

   });
  

    function move_el(){
		   if  (dragel.hasClass('select_item'))
		   	        {dragel.slideUp('fast'); 
		   	    	 setTimeout(update_menu_height(),700);
		   	        } 
		   	    else
			   	    { dragel.hide('slide', {direction: 'left'}, 150);
			   		  datid = dragel.attr('data-id');
			   		//  $('[data-id="'+datid+'"]').hide('slide', {direction: 'top'}, 150);
  						$('[data-id="'+datid+'"]').hide();
			          } 


		   	setTimeout(update_menu_height(),2500); 

		   		$('.spinner').detach();
		   		$('.message').hide();
		   		$('.wfade').hide();
		   	    if ((dragid!=parid)&&(dragid>0)&&(parid>0)){
		   	    	$('.spinner').detach();
		   	    	//$('.message').detach();
			   	    $.ajax({
						type: 'POST',
						url: '/wp-content/themes/album2/change_parent.php',
						data: {id: dragid, parent_id: parid}
				    });
 				}

 			$('.message').hide();
			$('.wfade').hide();    	
    }

    $(document).on('mouseup',function(){
    	    $('.dragger>*').hide('slow');
      	//  	setTimeout($('.dragger').empty(),1000);
      	    $('.lmenu_item, .select_item').css('cursor','pointer');   
    });

   
   function set_rels(sid){
   				$.ajax({
					type: 'POST',
					url: '/wp-content/themes/album2/set_rels.php',
					dataType: 'json',
					data: {func: 'set_ids', id: sid},
					success: function(data){
						
					}
				});	 
   }

	$(document).on('click','.set_index',function(){

				$.ajax({
					type: 'POST',
					url: '/wp-content/themes/album2/set_rels.php',
					dataType: 'json',
					data: {func: 'set_ids', id: type_id},
					success: function(data){
						//alert('Проиндексировано');
						message('','Проиндексировано','inf','close','yes'); 
					}
				});	 
	});



function imgcentered(container){
	setTimeout(function(){
	el     = $(container);
	el_img = $(container+' img');

	pw = el.width();
	ph = el.height();

	$(el_img).each(function(){
		h = $(this).height();
		w = $(this).width();
		mt = (ph - h)/2;
		if (mt>0){
			mt = 0;
		}
		ml = (pw - w)/2;
		if (ml > 0){
			ml = 0;
		}
		tr = $(this).css('transition');
		$(this).css('margin-top',mt+'px');
		$(this).css('margin-left',ml+'px');
	}); 
},10);



}

$(document).on('click','.study,.ahelp,.dashicons-welcome-learn-more',function(){
	$('.study-list ul').slideToggle('fast');    
	get_selected_level(level, type_id); 
});
$(".tagline").letterfx({"fx":"fall","words":true,"timing":200});
//domacros($('.club_icon img '),$('.club_icon img'), 8, $('.cursor'),2000); 

$(document).on( 'click', '.deleted', function(e){
	e.preventDefault;
	e.stopPropagation(); 
	Y = e.pageY;
	X = e.pageX;
	$('.deletemenu').slideDown('fast');
	$('.deletemenu').css('top',Y);
	$('.deletemenu').css('left',X);
	dataid = $(this).parent().attr('id');
	parid = $(this).parent().attr('parid');
	$('.deletemenu').attr('data-id',dataid);
	$('.deletemenu').attr('parid',parid);
});

$(document).on( 'click', '.deletemenu .fdelete', function(e){
    $('.deletemenu').slideUp('fast');  

     dataid =   $(this).parent().attr('data-id'); 
	 parid =   $(this).parent().attr('parid');   

	    e.preventDefault();
		e.stopPropagation();
		
		created_parentid = $(this).parent().attr('id');
		    
		
	    $.ajax({
			url: '/wp-content/themes/album2/fdelete.php',
			type: 'POST',
		
			data: {id: parid}, 
			success: function(data)
				{   
						  //  $('.list_block[data-id='+parid+']').hide('fast');   	
						$('.album_img[parid='+parid+']').slideUp('fast');
						$('#'+parid).slideUp('fast');
						if ($(this).parent().hasClass('.album_img')){
							$('.list_block[data-id='+parid+']').hide('fast'); 
						}
						//alert(data);
						message(data,'Информация об удаление','inf','close'); 
				}
			});    

});
var call_func;

$(document).on( 'click', '.moreinfo', function(e){
   $('.allinfo').slideDown('fast'); 
});

function message(inner_HTML,caption,type,buttons,call){
	$('.btn').hide();
	$('.spinner').hide();  
	if (buttons == 'nobut'){
		$('.message .close').hide();
	}
	buttons = buttons.split(',');
    $('.icon').removeClass('dashicons-dismiss');
    $('.icon').removeClass('dashicons-warning');
    $('.icon').removeClass('dashicons-editor-help');
    $('.dz-fullprogress').hide();
    //dashicons-warning  dashicons-dismiss dashicons-editor-help
    if (type=='err'){
    $('.icon').addClass('dashicons-dismiss');} 

    if (type=='inf'){ 
    $('.icon').addClass('dashicons-warning');}  
    if (type=='que'){ 
    $('.icon').addClass('dashicons-editor-help');}
	buttons.forEach(function(item, i, arr) {
	  $('.message .'+item).show();
	});
	
	
	if (type=='bar'){
        $('.message .info').html('<div class="dz-fullprogress"></div>');
        $('.dz-fullprogress').width('20');
    }
    else{  
    	$('.message .info').html(inner_HTML);
    }
	$('.message .caption').html(caption);
	$('.message').fadeIn('fast');
	$('.wfade').fadeIn('fast'); 
	hh =  $('.message').height();
	$('.message').css('margin-top', -hh/2+'px');

	call_func = call;
};
$(document).on( 'click', '.message .close, .message .close', function(){ 
	$('.message').fadeOut('fast');
	$('.wfade').fadeOut('fast');
	$('.message').removeClass('deleteinfo');
});

$(document).on( 'click', '.message .close, .message .no', function(){
	$('.message').fadeOut('fast');
	$('.wfade').fadeOut('fast');
	//message(data,'stantart','close');
});

$(document).on( 'click', '.message .yes', function(){	
	spn('.message'); 
	call_func();
});



$(document).on( 'click', '.deletemenu .undelete', function(){
    $('.deletemenu').slideUp('fast'); 
    parid = $(this).parent().attr('parid');
    dataid = $(this).parent().attr('data-id');
    $('.list_block[data-id='+parid+']').append("<div class='undeleted'>Восстановлено</div>").show('fast');  
    $('.del_el[data-id='+dataid+'] .delete').addClass('undeleted');

    $('.select_item[parid = '+parid+']').detach();
		$.ajax({
			url: '/wp-content/themes/album2/published.php',
			type: 'POST',
	
			data: {id: dataid, status: 'publish'}, 
			success: function(data){
				$('.lmenu_item[data-id='+parid+']').click();
				$('a[data-id='+dataid+']').removeClass('delete');
				$('a[data-id='+dataid+']').addClass('publish');
			}
		});
		$(this).parent().removeClass('pending');

});

$(document).on('click', '.clubs .pnums li', function(){
    $('.pnums li').removeClass('active');
    
    $(this).addClass('active');
    page = parseInt($(this).attr('data-num'));
    height = $('.album_img').height();
    hh = $('.clubs').height();
    count  = hh/height/5;
    
    

    $('body').scrollTop(page * limit * height);
    
    freshhistory();    
    get_pagenav(parseInt(count), page);

    // Replace the content of .clubs .pnums with the generated pagination HTML
  
});

// Add the following function to dynamically generate pagination
function get_pagenav(length, page) {
  let i = 0;
  const nums = 10;
  let pliclass = '';
  let phtml = '';
  length = $('.album').length; 
  limit = 15;
  if (length == 0){ length = $('.album_img').length; }
  while (i <= length + 1) {
    const num = i + 1;

    if (i === page) {
      pliclass = 'active';
    } else {
      pliclass = '';
    }

    let start = 0;
    if (page - nums / 2 >= 0) {
      start = page - nums / 2;
    }

    let end = 0;
    if (start + nums <= length) {
      end = start + nums;
    } else {
      end = length;
    }

    if (end > length){
    	end = length;
    }
    if (i >= start && i < end-1) {
      phtml += `<li class='${pliclass}' data-num='${i}'>${num}</li>`;
    }

    i++;
  }

  $('.clubs .pnums').html(`${phtml}`);
  

}


$(document).on('click','.list .pnums li', function(){
	$('.pnums li').removeClass('active');
	$(this).addClass('active');
	//spn('.list');
	lpage = $(this).attr('data-num');
	//get_list(type_id, level, 5, lpage);
	get_slide_arr2()
});




$(document).on('click','.wall .pnums li', function(){
	$('.pnums li').removeClass('active');
	$(this).addClass('active');
	wpage = $(this).attr('data-num');

	
	spn('.wall');
	$('.wall').load( THEME_DIR + 'wall.php', {uid: uid, page: wpage, level: level}, function(){
		//$('.breadcrumbs a[data-id=' + x + ']').addClass('bc-activ');
		get_slide_arr3();
	});
});



$('.unpload.dashicons.dashicons-upload').on('click', function(){

});

$(document).on('click','.upload', function(){
   if (level==5){
   $('.uploader').toggle('fast');}
   else{
   		$( ".helper .hint").hide();
   		$('.helper').fadeIn(160,function(){$(this).removeClass('hidden')});
	    htop = 0;
   		$( ".helper .hint[bind='li.select_item']" ).each(function() {
		 	 help_elem = $(this).attr('bind')+':visible';
		 	 help_elem = $(help_elem);
		 	  $(this).show();
		 	 coord_el = $(this);
		 	 SetCoords(help_elem, coord_el);
		});

   }
});

$(document).on('click','.dashicons-admin-tools,.atools', function(){
   $('.tools').toggle('fast'); 
   get_selected_level(level, type_id); 
});

$(document).on('click','.mtab,.megatab', function(){
   //alert('1');
   $('.nav').toggle('fast'); 
   		if ($(this).hasClass('active')){
			$(this).removeClass('active'); 
		}
		else{
			$(this).addClass('active');
		}
		 
});


$(document).on( 'click', ".lrm-close-form", function(){
    setTimeout(function(){$(`.select_item[parid = ${type_id}]`).show()},1);
   // get_selected_level(level, type_id); 
});

$(document).on( 'click', '.deletemenu .set_par', function(){
    $('.deletemenu').slideUp('fast'); 
    parid = $(this).parent().attr('parid');
    dataid = $(this).parent().attr('data-id');
    $('.list_block[data-id='+parid+']').append("<div class='undeleted'>Назначен родитель</div>").show('fast');  
    $('.del_el[data-id='+dataid+'] .delete').addClass('undeleted');

    $('.select_item[parid = '+parid+']').detach();
		$.ajax({
			url: '/wp-content/themes/album2/change_parent.php',
			type: 'POST',
	
			data: {id: dataid, parent_id: type_id}, 
			success: function(data){
				$('.lmenu_item[data-id='+parid+']').click();
				$('a[data-id='+dataid+']').removeClass('delete');
				$('a[data-id='+dataid+']').addClass('publish');
			}
		});
		$(this).parent().removeClass('pending');

});

$(document).on( 'click', 'body', function(){
   dragstart = false;
   $('.dragger').empty();
});
dsc = 0;
$(document).ready(function()  {
	

	$('.showwall').click(function(){

	});
	$('.showmenu').click(function(){
	   
	   uri =  window.location.href;
	   
	   if ((uri.search('messages')==-1)&&(uri.search('friends')==-1)&&(uri.search('profile')==-1)){
		 
		   $('#item-nav').toggle('fast');
		   $('.prof_action').toggle('fast');
		    $('.wall').toggle('fast');
	   } else {

	   if (uri.search('messages')!=-1){
	   	   $('.prof_action').hide('fast');
	   	   if ($('.messages').css('display')=='block'){
	   	      $('#item-nav').show('fast');
	   	  
	   	      $('.messages').hide('fast');
	   	   }
	   	   else {
	   	   	  $('#item-nav').hide('fast');
	   	   	  $('.messages').show('fast');
	   	   
	   	   }
	   }

	   if (uri.search('profile')!=-1){
	   	   $('.prof_action').hide('fast');
	   	   if ($('.profile').css('display')=='block'){
	   	      $('#item-nav').show('fast');
	   	      $('.profile').hide('fast'); 
	   
	   	   }
	   	   else {
	   	   	  $('#item-nav').hide('fast');
	
	   	   	  $('.profile').show('fast');
	   	   }
	   }

	   if (uri.search('friends')!=-1){
	   	   $('.prof_action').hide('fast');
	   	   if ($('.friends').css('display')=='block'){
	   	      $('#item-nav').show('fast');
	   	      $('.friends').hide('fast'); 
	   
	   	   }
	   	   else {
	   	   	  $('#item-nav').hide('fast');
	
	   	   	  $('.friends').show('fast');
	   	   }
	   }}
	});

	window.leftzone = false;
	$(document).on('mouseenter','.slider',function(){
		window.leftzone = true;	
	});

	$(document).on('mouseleave','.slider',function(){
		window.leftzone = false;	
	});

	$(document).keydown(function(e) {
		if ($('.lightbox__create-elem:visible,.lightbox__change-elemname:visible').length>0){
			return;
		}
    	if (e.keyCode == 37){
    		$('.ligtbox__img_left').click();
    	}
    	if (e.keyCode == 39){
    		$('.ligtbox__img_right').click();
    	}

    	if (window.leftzone){
	    	sh = $('.select_item_img').height();
	    	if (e.keyCode == 38){
	    		e.preventDefault();
	    		slider_move(sh*8);
	    	}
	    	if (e.keyCode == 40){
	    		e.preventDefault();
	    		slider_move(-sh*8);
	    	}
    	} 
	});



    $(document).on( 'click', ".wclose", function(){
		$(this).parent().hide('fast');
	});

	const reader = new FileReader();                
	reader.onload = function(event) {
	  const contents = event.target.result;
	  console.log(contents);
	};
	


	$('body').scrollTop(0);
	$(document).on( 'click', ".switch", function(){
		//alert(1); 
		 if ($('body').hasClass('hidemenu')) {
		 	$('body').removeClass('hidemenu');
		 	$('.switch span').removeClass('dashicons-arrow-left-alt');
		 	$('.switch span').addClass('dashicons-arrow-right-alt');
		    get_selected_level(level,type_id);
		 }
		 else{
		 	$('body').addClass('hidemenu');	
		 	$('.switch span').addClass('dashicons-arrow-left-alt');
		 	$('.switch span').removeClass('dashicons-arrow-right-alt');
		 }
	});
	$(document).on( 'click', ".lightbox__img_photo img", function(e){
	  if (e.offsetX>screen.width/2){
	  	 $('.ligtbox__img_right').click();
	  }
	  if (e.offsetX<screen.width/2){
	  	 $('.ligtbox__img_left').click();
	  }

	});
   
	
});

function lazyLoad() {
	var $lazyImages = $(".album img, .album_img img");
	$lazyImages.each(function() {
		var $img = $(this);
		if ($img.offset().top < $(window).scrollTop() + $(window).height() && $img.offset().top + $img.height() > $(window).scrollTop()) {
			$img.attr("src", $img.data("src"));
			$img.addClass("loaded");
			$lazyImages = $lazyImages.filter(function() {
				return !$(this).hasClass("loaded");
			});
		}
	});

	
}

function autoSlider() {
	function clickImageRight() {
		$('.ligtbox__img_right').click();
	}
	setInterval(clickImageRight, 4000); 
}
 
function autoScroll() {
	$('body,html').animate({ scrollTop: $(document).height() }, 60000);
}



$(document).on("scroll resize", lazyLoad);



$(document).on( 'click', ".fa-palette,.fa-magnifying-glass-plus", function(e){	
	if ($(this).hasClass('pa-active')){
		$(this).removeClass('pa-active');
	}else{
		$(this).addClass('pa-active');
	}
});
$(document).on('change', "#inv", function(e) {
	$('#deg').change();
});

$(document).on('change', "#zoom", function(e) {
    // Получаем новое значение зума из элемента
	e.stopPropagation();
    var zoomLevel = $(this).val();
	localStorage.setItem('zoomLevel', zoomLevel);
    // Применяем новое значение зума к элементу body
    $('body').css('zoom', zoomLevel + '%');
});

zoomLevel = localStorage.getItem('zoomLevel');
//$('#zoom').val(zoomLevel);
//$('#zoom').change();

$(document).on('change', "#deg", function(e) {
	e.stopPropagation();

    let deg = $('#deg').val();
    let iinv = $('#inv').prop('checked') ? 'invert(1)' : '';
	let iiinv = $('#inv').prop('checked') ?  '' : 'invert(1)'; 
	
    $('header, .span.not_found,.lrm-user-modal-container,.help_icon,.albumicon,.ncount,.ligtbox__img_left,.ligtbox__img_right,.fa-comment,.author,.wc-field-submit,.lightbox__edit'+
	 ',.spinner,.lightbox,h3,.lside, div#cash,#parser *,.help_text, #vkablums *,.wclose, .message,.about,.album .fas, .not_found, .album .fa-solid,.author a,.button,.cover_club,.lightbox__button-exit,.delete_club,.edit_club').css(
        'filter', `hue-rotate(${deg}deg) ${iinv}`
    );
	//.album  .cover_club,.album ,.pnums, .edit_club,.album  .delete_club,
    let ddeg = -deg;
    $('.lside img,.usr img').css(
        'filter', `hue-rotate(${deg}deg) ${iiinv}`
    );

	$('.select_item_img img').css(
        'filter', `hue-rotate(${ddeg}deg) ${iinv}`
    );

	$('.spinner').css(
        'filter', `hue-rotate(${deg}deg) ${iinv}`
    );
	$('.uname').css(  'filter', `hue-rotate(${ddeg}deg) ${iiinv}`);
	
	$('.lightbox__content , img.avatar').css( 'filter', `hue-rotate(${ddeg}deg) ${iinv}`);
 
    $('.dz-fullprogress').css( 'filter', `hue-rotate(${deg}deg) ${iiinv}`);
    
	localStorage.setItem('deg', deg);
	localStorage.setItem('inv', iinv);
	
	$('.usr img').css('filter',` ${iinv}`);
    // Apply invert filter to .content background
    if ($('#inv').prop('checked')) {
        $('.content').css('background-color', function(_, bgColor) {
            // Assuming bgColor is in rgb or rgba format
            if (bgColor) {
                let rgb = bgColor.match(/\d+/g);
                if (rgb) {
                    let invertedColor = `rgb(${255 - rgb[0]}, ${255 - rgb[1]}, ${255 - rgb[2]})`;
                    return invertedColor;
                }
            }
            return bgColor;
        });
    } else {
        $('.content').css('background-color', '');
    }

	$('.goback').click(function(){
		window.history.go(-1);
	})
});

