//8-929-677-46-01
var M = {};
var fS = [];					//false-select
M.mobileMenu = false;
M.mobileLK = false;
M.menu = 0;						//номер меню	
M.punkt = 0;					//номер пункта меню
//M.left = [0,290, 580];		//смещение влево
M.left = [0, 0, 290, 580];		//смещение влево
M.heightCatalog;				//высота корневого каталога
M.heightParameters;
M.shiftRight = false;
M.scroll = 0;
M.limitWidht = 992;				//нет сдвига, если меньше и не показывать 
M.color = '#202020';


window.onresize = function(){
	if( $('.my-container').width() > 640) 
		$('.header__menu').css('display', 'block');
	else{
		$('.header__menu').css('display', 'none');
	}
	
	if( $('.my-container').width() > 420) 
		$('#logoPic img').attr('src', '/images/logo_v11.png');
	else{
		$('#logoPic img').attr('src', '/images/logo_globus.png');
	}

	//размер модального окна
	M.widthModal = $('.win-hidden').outerWidth();
	M.leftModal = document.body.clientWidth/2 - M.widthModal/2;
	$('.win-hidden').css( { 'left': M.leftModal});
	
	if(M.shiftRight){
		var widthCont = $('.my-container').width(); 
		var widthPlash = $('.find__plash').width();
		$('.my-content').css('width', (widthCont-widthPlash -20) + 'px');
	}
	if(window.innerWidth <= 992){
		$('.my-content').css('width', '100%');
	}	
}

function setHeightFooter(heightPlash){
	var heightContent = $('.my-content').height();
	
	if( heightContent < heightPlash ){
		var delta = heightPlash - heightContent; 
		$('.false-footer').height(M.falseFooterHeight + delta);
	}
}

$(document).ready(function(){
	 jQuery.fn.center = function(id){
    if($(this).attr('id') == 'inlineChar') {
      $(this).css("top", "1px");
      $(this).css("right","1px");
    } else {
		  $(this).css("top", document.body.clientHeight/2-$(this).outerHeight()/2);
		  $(this).css("left",document.body.clientWidth/2-$(this).outerWidth()/2);
    }
	};
	
	M.falseFooterHeight = $('.false-footer').height();
	//$('#search_name').val(screen.width +'x'+screen.height);
	
	//Плашки
	$('.plash').on( 'click', function(){
    var id = $(this).attr('id');
		//alert (id);
		if( $(this).attr( 'data-view') == 0 ){
			$('.child').slideUp(0);
			$('.plash').attr( 'data-view', 0);

			//$(this).next().slideDown(0);	//css('display', 'block');
      if( id == 'parameters' ){
			  $('#all-fucking-search').slideDown(0);	//css('display', 'block');
			} else {
			  $('#all-fucking-catalog').slideDown(0);	//css('display', 'block');
      }

			$(this).attr( 'data-view', 1);
			
			if( id == 'parameters' ){
				M.heightParameters = $('.search-parameters').outerHeight();
				shiftRight(M.heightParameters);
				clearMenu();
			}	else{
				//M.heightCatalog = $('.find-catalog').outerHeight();
				// alert(screen.width +'x'+screen.height +'\n'+
				 // $(window).height() +'\n'+
				 // M.heightCatalog);
				M.heightCatalog = $(window).height() - 220; 
				$('.find-catalog, .drop').css( 'height', M.heightCatalog + 'px'); 
				shiftRight(M.heightCatalog);
			}
			if( $(document).width() >= M.limitWidht) {
			  $('.search-banner').show();
		    }
		}	else {
			clearMenu();
			//$(this).next().slideUp(400, shiftBack );	//вернуть  блок
      if( id == 'parameters' ){
			  $('#all-fucking-search').slideUp(400, shiftBack );	//вернуть  блок
			} else {
			  $('#all-fucking-catalog').slideUp(400, shiftBack );	//вернуть  блок
      }
			$(this).attr( 'data-view', 0);		
			$('.search-banner').hide();
		}
	});
	
	
	$('.level-menu .menu').on('mouseenter', function(e){
		
		//не показывать 2 и 3 уровни
		if( $(document).width() <= M.limitWidht) return;
		
		var level = $(this).parent().attr('data-level');
		$('div[data-level='+level+'] .drop').removeClass('visible'); 
		$(this).next('.drop').addClass('visible');
		
		$('div[data-level='+level+'] .menu').css('color', M.color);
		$(this).css('color', '#4b6ecd');
	});	
	
	$('.drop').on('mouseleave',function(e){
		$('.menu').css('color', M.color);
		$(this).removeClass('visible');
		
	});	
	
	$('.find-catalog').on('mouseleave',function(e){
		$('.menu').css('color', M.color);
		$('.drop').removeClass('visible');
		
	});	
	
	//сдвинуть блок content вправо
	function shiftRight(heightPlash){
		//alert($('.my-container').width()+' - '+$(document).width()+' - '+M.limitWidht);
		if( $(document).width() > M.limitWidht){
			M.shiftRight = true;
			var widthCont = $('.my-container').width(); 
			var widthPlash = $('.find__plash').width();
			$('.catalog__block').css('width','33.3%'); 
			$('.my-content').css('width', (widthCont-widthPlash -20) + 'px');
			setHeightFooter(heightPlash);
			$('#index-banner-block').css('display','inline-block'); 
		}
	}	
	
	//вернуть блок content назад
	function shiftBack(){
		if( $(document).width() > M.limitWidht){
			M.shiftRight = false;
			$('.catalog__block').css('width','25%');
			$('.my-content').css('width', '100%');
			$('.false-footer').css('height', '315px');
			$('#index-banner-block').css('display','none'); 
		}
	}
	
	//убрать меню каталога
	function clearMenu(){
		$('.find-catalog').animate({scrollTop: 0}, 300);
		$('.drop').removeClass('visible');
		$('.level-menu .menu').css('color', M.color);
		M.punkt = 0;
		M.menu = 0;
	}
			
	//показать/скрыть кнопку Вверх
	$(window).scroll(function (e) {
		M.scroll = $(this).scrollTop();

		if(document.body.clientWidth > 768)  
			M.offsetTop = 30
		 else 
		 	M.offsetTop = 30+M.scroll;
	 
		if (M.scroll > 200) {
			$(".up-btn").show();
		}else{
			$(".up-btn").hide();
		}
	});
	
	//прокрутка в начало
	$(".up-btn").on( 'click', function(){
		$('html, body').
				animate({scrollTop: 150},0).
				animate({scrollTop: 0}, 600);
		return false;
	});
	
	
	// (избранное)
	M.listFavorites = "<a href='/account/favorites'><img src='/images/favorits.png' width='48px' title='Смотреть список избранного'></a>"
	var isFavorite = $('.is-favorite').text();
	if( isFavorite == 1){
		$('.remove-favorite').removeClass('d-none');
		$('.info-favorite').html(M.listFavorites);
	}
	else{
		$('.add-favorite').removeClass('d-none');
	}
	
	//js-ссылки
	$('.js-link').on( 'click', function(e){
		var id = $(this).attr('data-link');
		var item = $(this).attr('data-item');
		var user = $(this).attr('data-user');
				
		switch(id){
			case "add-favorite":
				$.ajax({
					type: 'POST',
					url: '/js/ajax_favorite.php',
					data: 'action=add&user='+user+'&item='+item,
					success: function(text){
						$('.add-favorite').addClass('d-none');
						$('.remove-favorite').removeClass('d-none');
						$('.info-favorite').html(M.listFavorites);
					}
				});
			break;
			case "remove-favorite":
				$.ajax({
					type: 'POST',
					url: '/js/ajax_favorite.php',
					data: 'action=remove&user='+user+'&item='+item,
					success: function(text){
						$('.remove-favorite').addClass('d-none');
						$('.add-favorite').removeClass('d-none');
						$('.info-favorite').html("");
					}
				});
			break;
			case "remove-favorite-from-list":
				var goodsBlock = $(this).parent().parent();
				$(this).parent().next('a').children('.good-card').addClass('noactive');	//<div class='good-card noactive'> 
				var html = $(this).parent().next('a').html(); 							//<div class='good-card noactive'> ... </div>
				var iconWb = "<div class='hit'><img src='/images/remove-favorite-wb.png'></div>";
				$(goodsBlock).html( iconWb + html);
				
 				$.ajax({
					type: 'POST',
					url: '/js/ajax_favorite.php',
					data: 'action=remove-favorite-from-list&user='+user+'&item='+item,
					success: function(text){
						if( text == 0)	location.href = "/account.php";
					}
				});
 			break;
		}	
		
	});
	
	//*modal window 
	// show
	$('.my-modal').on( 'click', function(){
		var id = $(this).attr('data-id');
		$('#'+id).fadeIn(700).center();
		$('#my-modal-over').fadeIn(300);
	});

	// close
	$('.win-close').on( 'click', function(){
		$('.win-hidden').fadeOut(300);
		$('#my-modal-over').fadeOut(600);
		resetInputError('full');
	});

	$('#my-modal-over').on( 'click', function(){
		$('.win-hidden').fadeOut(300);
		$('#my-modal-over').fadeOut(600);
	});
	
	$("form input.agree").on('click', function(){
	if ($(this).is(':checked')){
			$("form button")
				.removeAttr("disabled")
				.removeClass('stop');
		} else {
			$("form button")
				.attr("disabled",true)
				.addClass('stop');
		}
	});		
	
	function resetInputError(mode){
		$("form.win-form input:not([type=hidden]), form.win-form textarea")
			.attr('placeholder', '')
			.css( 'borderColor', "#ccc");
			
		if( mode == 'full'){
			$("form.win-form input:not([type=hidden]), form.win-form textarea").val('');
			$("form.win-form button").removeAttr("disabled").removeClass('stop');
			$("#request1click").css('display', 'block');
			$(".win-form").css('display', 'block');
			$(".form-response").text('');
		}	
			
	}
	
	//slider на первой странице
	var step = 170 * 3 - 50;
	var countImg = $('#count-img').text();
	$(".img-container").css( 'width', (countImg * 170 + 100 ) + 'px');
	
	function moveSlider(number){
		X = -step*number;
		$(".img-container").css( {'transform': 'translateX('+X+'px)'});
	}
	
	$('.navi-clients__button i').on( 'click', function(){
		$('.navi-clients__button i').removeClass('fa-circle');	
		$(this).addClass('fa-circle');
		var number = $(this). attr('data-number'); 	
		moveSlider(number); 
	});
	
	//mobile menu
	$('.gambu').on( 'click', function(){
		if( !M.mobileMenu ){
			$('.mobile-navbar').css(	{ 'transform': 'translateX(288px)' });
			M.mobileMenu = true;
			$(this).addClass('gambu-open');
			$('#mobile-menu-over').css( 'display', 'block');
			$('body').addClass( 'fixed' );
		}
		else {
			$('.mobile-navbar').css( { 'transform': 'translateX(-288px)' });
			M.mobileMenu = false;
			$(this).removeClass('gambu-open');
			$('#mobile-menu-over').css( 'display', 'none');
			$('body').removeClass( 'fixed' );
		}
	});
	
	//lk__mobile
	$( ".lk__mobile" ).on('click', function(){ 
		if( !M.mobileLK ){
			$('.lk__mobile__list').css(	{ 'transform': 'translateX(288px)' });
			//$('#mobile-menu-over').css( 'display', 'block');
			$('body').addClass( 'fixed' );
			M.mobileLK = true;
			
		}
		else {
			$('.lk__mobile__list').css( { 'transform': 'translateX(-288px)' });
			//$('#mobile-menu-over').css( 'display', 'none');
			$('body').removeClass( 'fixed' );
			M.mobileLK = false;
		}
	});
	
	//загрузить параметры выбора
	// alert(typeof pageID);
	//if (typeof pageID === "undefined") { pageID = 'not'; }
	//if (pageID != 'catalog') {
		make_search_v2_v2();
	//}
	
	
	//убрать Подбор по параметрам для раздела каталога
	var sp = $('#noShowParameters').text();
	if(sp){
		$('#parameters').addClass('hd');	
	}
	
	//new falseSelect('find');
	
	try{
		// для ЛК
		fS[0] = new falseSelect('day');
		fS[1] = new falseSelect('month');
		fS[2] = new falseSelect('year');
		
		new togglePassword('old-password');
		new togglePassword('new-password');
		new togglePassword('new1-password');
	}
	catch(e){
	}
	checkField();
	
    // (function(){
		
	// })();
	
	
});

// false select
function falseSelect(id){
	this.open = false;
	this.selectDropdownSpan = document.querySelector('#span-select-'+id);
	this.selectDropdown = document.querySelector('.select-dropdown-'+id);
	this.selectDropdownContainer = document.querySelector('.dropdown-container-'+id);
	
	this.selectListSpan = document.querySelectorAll('.select-list-'+id+' span');
	this.inputSelect = document.querySelector('#input-select-'+id);
	this.spanSelect = document.querySelector('#span-select-'+id);
	var o = this;
	
	this.selectDropdownSpan.onclick = function(e){
		if(!o.open){
			for( var f = 0; f < fS.length; f++){
				fS[f].open = false;
				fS[f].selectDropdown.classList.remove('cd-active');
				fS[f].selectDropdownContainer.classList.remove('dropdown-container-show');
			}
			o.open = true;
			o.selectDropdown.classList.add('cd-active');
			o.selectDropdownContainer.classList.add('dropdown-container-show');
		}	
		else{
			o.open = false;
			o.selectDropdown.classList.remove('cd-active');
			o.selectDropdownContainer.classList.remove('dropdown-container-show');
		}	
	}
	
	for( var s = 0; s < this.selectListSpan.length; s++){
		this.selectListSpan[s].onclick = function(e){
			var text = this.textContent;
			var value = this.getAttribute('data-value');
			
			//частный случай c поиском (каталог/архив). Для автозаполнения
			if( o.inputSelect.id == 'input-select-find'){
				M.arch = value;	
			}	
			o.inputSelect.value = value;
			o.spanSelect.textContent = text;
			o.open = false;
			o.selectDropdown.classList.remove('cd-active');
			o.selectDropdownContainer.classList.remove('dropdown-container-show');
		}	
	}	
}

/* проверка  полей формы*/
function checkField(){	
	var forms = document.querySelectorAll('form');
	//var reg = new RegExp( '^\\s{1,1111}$');
	
	for( var f = 0; f < forms.length; f++){
		forms[f].onsubmit = function(e){
			var check = false;
			//this - текущая форма
			var nodes = this.querySelectorAll('.required');
			for( var n = 0; n < nodes.length; n++){
				switch( nodes[n].tagName.toLowerCase() ){
					//просто input
					case "input":
						if( nodes[n].value.length > 0 && !nodes[n].value.match(/^\s{1,111}$/) ){
							nodes[n].style.borderColor = "#ccc";
							
							//проверить телефон
 							if( nodes[n].getAttribute('name').match(/.*phone.*/)){
								var phone = nodes[n].value;
								var reg = phone.match(/\+7\s\(\d{3}\)\s\d{3}\-\d{2}\-\d{2}/);
								var res;
								if( !reg ){
									nodes[n].style.borderColor = "#f00";
									check = true;
								}
								else{
									nodes[n].style.borderColor = "#ccc";
								}	
							}
							
 							continue;
						}	
						else{
							nodes[n].value = '';
							nodes[n].setAttribute( 'placeholder', 'поле не заполнено');
							nodes[n].style.borderColor = "#f00";
							check = true;
						}
					break;
					//false-select
					case "span":
						if( nodes[n].textContent.length > 1 && !nodes[n].value.match(/^\s{1,111}$/)){
							nodes[n].parentNode.style.borderColor = "#ccc";
							continue;
						}	
						else{
							nodes[n].parentNode.style.borderColor = "#f00";
							check = true;
						}
					break;
					//password
					case "div":
						if( nodes[n].childNodes[1].value.length > 0 && !nodes[n].value.match(/^\s{1,111}$/)){ //[1] - указатель на input в наборе
							nodes[n].style.borderColor = "#ccc";
							continue;
						}	
						else{
							nodes[n].style.borderColor = "#f00";
							nodes[n].childNodes[1].setAttribute( 'placeholder', 'поле не заполнено');
							check = true;
						}
					break;
					//textarea
					case "textarea":
						if(  nodes[n].value.length > 1 && !nodes[n].value.match(/^\s{1,111}$/)){
							nodes[n].style.borderColor = "#ccc";
							continue;
						}
						else{
							nodes[n].style.borderColor = "#f00";
							nodes[n].setAttribute( 'placeholder', 'поле не заполнено');
							check = true;
						}
				
				break;
				}
			}		
			if( check) return false;
		}	
	}	
}

function update(){
	var ca = document.getElementById("captcha");
	ca.setAttribute("src","/captcha/secpic.php?rnd="+Math.round(Math.random(0)*1000));
}	

//показать/скрыть пароль
function togglePassword(id){
	this.show = false;
	this.togglePassword = document.querySelector('#'+id);
	this.nodes = this.togglePassword.childNodes;
	for( var n = 0; n < this.nodes.length; n++){
		if(this.nodes[n].nodeType == 1){
			if( this.nodes[n].tagName.toLowerCase() == "input"){
				this.input = this.nodes[n];
			}
			if( this.nodes[n].tagName.toLowerCase() == "img"){
				this.img = this.nodes[n];
			}
		}
		else{
			continue;
		}	
	}	
	
	this.eye = 0;
	var o = this;
	
	this.img.onclick = function(e){
		if( o.eye == 0 ){
			o.eye = 1;
			o.img.setAttribute( 'src', '/images/eye-open.png');
			o.input.setAttribute( 'type', 'text');
		}
		else{
			o.eye = 0;
			o.img.setAttribute( 'src', '/images/eye-close.png');
			o.input.setAttribute( 'type', 'password');
		}	
	}
}


function toggleShowHide(block, butt1, butt2){
	this.block = document.querySelector('#'+block);
	this.butt1 = document.querySelector('#'+butt1);	//кнопка показать
	this.butt2 = document.querySelector('#'+butt2); //кнопка скрыть
	
	var click1 = function(e){
		this.block.style.display = "block";
		this.butt2.style.display = "block";
		e.currentTarget.style.display = "none";
		
		M.heightParameters = $('.search-parameters').outerHeight();
		setHeightFooter(M.heightParameters);
		return false;
	};
	var click2 = function(e){
		this.block.style.display = "none";
		this.butt1.style.display = "block";
		e.currentTarget.style.display = "none";
		
		M.heightParameters = $('.search-parameters').outerHeight();
		setHeightFooter(M.heightParameters);
		return false;
	};
	try{
		this.butt1.onclick = click1.bind(this);
		this.butt2.onclick = click2.bind(this);
	}
	catch(error){}
}


	

	

	