
function owlWrapperWidth( selector ) {
	$(selector).each(function(){
    	$(this).find('.owl-carousel').outerWidth( $(this).closest( selector ).innerWidth() );
  	});
}

function calcCart() {
	var itog = 0;
	var itog2 = 0;
	var dost_price = 0;
	if ($('#radio-1-2').is(':checked') || $('#radio-1-3').is(':checked') || $('#radio-1-4').is(':checked')) {
		if ($('#radio-1-2').is(':checked')) dost_price = parseInt($('#radio-1-2').attr('dost-price'));
		else if ($('#radio-1-3').is(':checked')) dost_price = parseInt($('#radio-1-3').attr('dost-price'));
		else dost_price = parseInt($('#radio-1-4').attr('dost-price'));
		$('.itogo1').slideDown('fast');
	} else {
		
		$('.itogo1').slideUp('fast');
	}
	$('.cart-row').each(function(index, el) {
		var iter = $(el).find('.cart-price').attr('iter');
		var prc = $(el).find('.cart-price span').html();
		var price = parseInt(prc.replace(/\s/g, ""));
		var kol = parseInt($(el).find('.inp-kol[iter="'+iter+'"]').val());
		var price1 = price*kol;
		itog = itog + price1;
	});
	console.log(dost_price);
	/*if (dost_price > 0) {
		$('.itogo1').slideDown('fast');
		itog2 = itog + dost_price;
		$('.itogo1 span').html(dost_price);
		$('.dost_cena').val(dost_price);
	} else {
		$('.itogo1').slideUp('fast');
		$('.dost_cena').val(0);
		itog2 = itog;
	}*/

	itog2 = itog;
	$('.itog_cena').val(itog);
	$('.itogo span').html(itog);
	$('.itogo2 span').html(itog2);
}

function add2fav(id) {
	 $.ajax({
      type: "POST",
      url: '/inc/async.php',
      data: {id: id, func: 'add2fav'},
      success: function(jqXHR ){
        console.log(jqXHR );
        if (jqXHR.res == true) {
            $('.icon_fav .kol').html(jqXHR.cnt1);
            $('.ProductCardWishlistButton__icon[iter="'+id+'"]').addClass('active');
            $('.ProductCardWishlistButton__icon[iter="'+id+'"]').find('a').attr('onclick', ' delfav('+id+');');
        }
      },
      dataType: 'json'
    });
}

function delfav(id) {
	 $.ajax({
      type: "POST",
      url: '/inc/async.php',
      data: {id: id, func: 'delfav'},
      success: function(jqXHR ){
        console.log(jqXHR );
        if (jqXHR.res == true) {
            $('.icon_fav .kol').html(jqXHR.cnt1);
            $('.ProductCardWishlistButton__icon[iter="'+id+'"]').removeClass('active');
            $('.ProductCardWishlistButton__icon[iter="'+id+'"]').find('a').attr('onclick', ' add2fav('+id+');');
        }
      },
      dataType: 'json'
    });
}

function fmContSend() {
	$('.bCont').prop('disabled', true);
	$.ajax({
      type: "POST",
      url: '/inc/async.php?func=fmContSend'+'&title='+$(document).prop('title'),
      data: $('#fmCont').serialize(),
      success: function(jqXHR ){
        console.log(jqXHR );
        if (jqXHR.res == true) {
        		Fancybox.close(true); 
        		Fancybox.show([{ src: "#dialog-msg-ok", type: "inline", infinite: false }]);
        }
        $('.bCont').prop('disabled', false);
      },
      done: function() {
  			$('.bCont').prop('disabled', false);
		},
      dataType: 'json'
    });
}

window.addEventListener("DOMContentLoaded", function() {
    [].forEach.call(document.querySelectorAll('.tel'), function(input) {
        var keyCode;

        function mask(event) {
            event.keyCode && (keyCode = event.keyCode);
            var pos = this.selectionStart;
            if (pos < 3) event.preventDefault();
            var matrix = "+7 (___) ___-__-__",
                i = 0,
                def = matrix.replace(/\D/g, ""),
                val = this.value.replace(/\D/g, ""),
                new_value = matrix.replace(/[_\d]/g, function(a) {
                    return i < val.length ? val.charAt(i++) || def.charAt(i) : a
                });
            i = new_value.indexOf("_");
            if (i != -1) {
                i < 5 && (i = 3);
                new_value = new_value.slice(0, i)
            }
            var reg = matrix.substr(0, this.value.length).replace(/_+/g,
                function(a) {
                    return "\\d{1," + a.length + "}"
                }).replace(/[+()]/g, "\\$&");
            reg = new RegExp("^" + reg + "$");
            if (!reg.test(this.value) || this.value.length < 5 || keyCode > 47 && keyCode < 58) this.value = new_value;
            if (event.type == "blur" && this.value.length < 15) this.value = ""
        }

        input.addEventListener("input", mask, false);
        input.addEventListener("focus", mask, false);
        input.addEventListener("blur", mask, false);
        input.addEventListener("keydown", mask, false)

    });

});

function resize() {
	 $.post('/inc/async.php?func=resize', { width: screen.width, height:screen.height }, function(json) {
	 	
	 	console.log(json);

        if(json.res == 'success') {
            if (json.device == 'tablet' && parseInt(json.width) > parseInt(json.height))   {
            	$('.cat-mob').find('.cat-col-5').show();
            	$('.cat-mob').find('.cat-col').removeClass('col-6').addClass('col-4');
            } else {
            	$('.cat-mob').find('.cat-col-5').hide();
            	$('.cat-mob').find('.cat-col').removeClass('col-4').addClass('col-6');
            }
        } else {
            alert('Unable to let PHP know what the screen resolution is!');
        }
    },'json');
}


function resetFilter() {
	$('.cat-item-wrap').show();
	$('.color-check').prop('checked', false);
}

function setFilter() {
	var colorIdArray = [];
	var i = 0;
	$('.color-check').each(function(index, el) {
		if ($(el).is(':checked')) {
			colorIdArray[i] = $(el).attr('data-colorid');
			i++;
		}
	});
	$('.cat-item-wrap').hide();
	$('.cat-item-wrap').each(function(index, el) {
		if (jQuery.inArray($(el).attr('data-colorid'), colorIdArray) !== -1 ) {
			$(el).show();
		}
	});
	if (colorIdArray.length == 0) {
		resetFilter();
	}
}

function sortByFav() {
	var YuttiSortFavDirection = 'asc';
	if (typeof(localStorage.YuttiSortFavDirection) != 'undefined') {
		YuttiSortFavDirection = localStorage.YuttiSortFavDirection;
	}
	if (YuttiSortFavDirection == 'desc') {
		$('.cat-row > div').sort(function (a, b) {
		    var contentA =parseInt( $(a).data('fav'));
		      var contentB =parseInt( $(b).data('fav'));
		      return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
		}).appendTo('.cat-row');
		$('.sort-fav-desc').hide();
		$('.sort-fav-asc').show();
		localStorage.YuttiSortFavDirection = 'asc';
	} else {
		$('.cat-row > div').sort(function (a, b) {
		    var contentA =parseInt( $(a).data('fav'));
		      var contentB =parseInt( $(b).data('fav'));
		      return (contentA > contentB) ? -1 : (contentA < contentB) ? 1 : 0;
		}).appendTo('.cat-row');
		$('.sort-fav-asc').hide();
		$('.sort-fav-desc').show();
		localStorage.YuttiSortFavDirection = 'desc';
	}
	localStorage.YuttiSortFavOn = 1;
	localStorage.YuttiSortPriceOn = 0;
}

function sortByPrice() {
	var YuttiSortPriceDirection = 'asc';
	if (typeof(localStorage.YuttiSortPriceDirection) != 'undefined') {
		YuttiSortPriceDirection = localStorage.YuttiSortPriceDirection;
	}
	if (YuttiSortPriceDirection == 'desc') {
		$('.cat-row > div').sort(function (a, b) {
		    var contentA =parseInt( $(a).data('price'));
		      var contentB =parseInt( $(b).data('price'));
		      return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
		}).appendTo('.cat-row');
		$('.sort-price-desc').hide();
		$('.sort-price-asc').show();
		localStorage.YuttiSortPriceDirection = 'asc';
	} else {
		$('.cat-row > div').sort(function (a, b) {
		    var contentA =parseInt( $(a).data('price'));
		      var contentB =parseInt( $(b).data('price'));
		      return (contentA > contentB) ? -1 : (contentA < contentB) ? 1 : 0;
		}).appendTo('.cat-row');
		$('.sort-price-desc').show();
		$('.sort-price-asc').hide();
		localStorage.YuttiSortPriceDirection = 'desc';
	}
	localStorage.YuttiSortFavOn = 0;
	localStorage.YuttiSortPriceOn = 1;
}


function search() {
	 $.ajax({
      type: "POST",
      url: '/inc/async.php',
      data: {q: $('.inp_search').val(), func: 'search'},
      success: function(jqXHR ){
        console.log(jqXHR );
        if (jqXHR.res == true && jqXHR.result.length > 0 ) {
            $('.search_results').html('');
            for (a in jqXHR.result) {
            	var b = '<a href="'+jqXHR.result[a].url+'">'+jqXHR.result[a].name+'</a>';
            	$('.search_results').append(b);
            }
        }
      },
      dataType: 'json'
    });
}

function add2cart(id, size) {
	 $.ajax({
      type: "POST",
      url: '/inc/async.php',
      data: {id: id, size: size, func: 'add2cart'},
      success: function(jqXHR ){
        console.log(jqXHR );
        if (jqXHR.res == true ) {
            $('.icon_cart .kol').html(jqXHR.cnt);
            $('.nocart[iter="'+id+'"]').addClass('nodis').removeClass('dis');
            $('.incart[iter="'+id+'"]').addClass('dis').removeClass('nodis');
        }	
      },
      dataType: 'json'
    });
}

function setcartcnt(id, cnt) {
	 $.ajax({
      type: "POST",
      url: '/inc/async.php',
      data: {id: id, cnt: cnt, func: 'setcartcnt'},
      success: function(jqXHR ){
        console.log(jqXHR );
        if (jqXHR.res == true ) {
            $('.icon_cart .kol').html(jqXHR.cnt);
        }	
      },
      dataType: 'json'
    });
}


function delcart(id, size) {
	 $.ajax({
      type: "POST",
      url: '/inc/async.php',
      data: {id: id, size: size, func: 'delcart'},
      success: function(jqXHR ){
        console.log(jqXHR );
        if (jqXHR.res == true ) {
            $('.icon_cart .kol').html(jqXHR.cnt);
            $('.cart-row[iter="'+id+'~'+size+'"]').remove();
            calcCart();
            if ($('.cart-row').length<1) {
            	$('#fmCart').hide();
            	$('.emptyCart').show();
            }
        }	
      },
      dataType: 'json'
    });
}

$(function() { // ready
	$('.icon_search').click(function() {
  		$('.head_search').slideToggle();
	});

	$('.search_close').click(function() {
  		$('.head_search').slideToggle();
	});
	$('.inp_search').focusin(function() {
	 	if ($( this ).val()=='Что ищем?') {
	 		$( this ).val('');
	 	}
	});
	$('.inp_search').focusout(function() {
	 	if ($( this ).val()=='') {
	 		$( this ).val('Что ищем?');
	 	}
	});
	$('.menuitem.has-sub').hover(
	  function() {
	    $( this ).removeClass('has-sub');
	    $( this ).addClass('has-sub1');
	    $( this ).find('.submenu').show();
	  }, function() {
	    $( this ).removeClass('has-sub1');
	    $( this ).addClass('has-sub');
	    $( this ).find('.submenu').hide();
	  }
	);

	$('.menu-subitem.has-ssub').hover(
	  function() {
	    $( this ).removeClass('has-ssub');
	    $( this ).addClass('has-ssub1');
	    $( this ).find('.subsubmenu').show();
	  }, function() {
	    $( this ).removeClass('has-ssub1');
	    $( this ).addClass('has-ssub');
	    $( this ).find('.subsubmenu').hide();
	  }
	);
	$('.mob,.mob1').click(function() {
  		$('.mobmenu').slideToggle();
		$('.mob').toggle();
		$('.mob1').toggle();
	});
	$('.mobmenuitem.has-sub > a,.mobmenuitem.has-sub1 > a').click(function() {
		$(this).parent().find('.mobsubmenu').slideToggle();
		$(this).parent().toggleClass('has-sub1');
		$(this).parent().toggleClass('has-sub');
		return false;
	});	
	$('.mobsubmenuitem.has-ssub > a,.mobsubmenuitem.has-ssub1 > a').click(function() {
		$(this).parent().find('.mobsubsubmenu').slideToggle();
		$(this).parent().toggleClass('has-ssub1');
		$(this).parent().toggleClass('has-ssub');
		return false;
	});	

	owlWrapperWidth( '.owl-wrapper' );
	
	$(window).bind('resize',  function(event) {
       owlWrapperWidth( $('.owl-wrapper') );
       resize();
   	});
    
    $(window).bind('scroll',  function(event) {
       owlWrapperWidth( $('.owl-wrapper') );
	});	

	$('.main-slider').owlCarousel({
        rtl: false,
        center: true,
        loop: true,
        items : 1,
        lazyLoad:true,
        nav : true,
        dots: true,
        navText:['',''],
        
    });

	$('.cat-owl').owlCarousel({
        rtl: false,
        center: false,
        loop: false,
        // items : 4,
        lazyLoad:true,
        nav : true,
        dots: false,
        navText:['',''],
        margin:15,
        stagePadding: 15,
        responsive : {
        	0 : {
		        items : 2,
		        slideBy: 2,
		    },
		    990 : {
		        items : 6,
		        slideBy: 6,
		    },
        }
    });

	$('.open,.close').click(function(event) {
		$(this).parent().toggleClass('act');
		$(this).parent().find('.open').toggle();
		$(this).parent().find('.close').toggle();
		$(this).parent().find('.left-submenu').slideToggle();
	});
	
	if ($('.zoom > img').length>0) {		
		$('.zoom > img').blowup({
			scale:2,
		});
	}

	$('.mini').click(function(event) {
		var itr = $(this).attr('itr');
		var iter = $(this).attr('iter');
		var big = $(this).attr('big');

		$('.mini').removeClass('act');
		$(this).addClass('act');

		$('.zoom > img').attr('src', big);

		$('.zoom > img').blowup({
			scale:2,
		});

	});
 
	// $(document).click(function(event) { 
	//   	var $target = $(event.target);
	//   	if(!$target.closest('.select-option-main').length && $('.select-option-wrap').is(":visible")) {
	//     	$('.select-up,.select-option-wrap').hide();
	//     	$('.select-down').show();
	//   	}        
	// });

	$('.select-main').click(function(event) {
		$(this).find('.select-down').toggle();
		$(this).find('.select-up').toggle();
		$(this).next('.select-option-wrap').slideToggle('fast');
	});

	// $('.select-option-main').click(function(event) {
	// 	$(this).closest('.select-main').find('.select-down').toggle();
	// 	$(this).closest('.select-main').find('.select-up').toggle();
	// 	$(this).closest('.select-wrap').find('.select-option-wrap').slideToggle('fast');
	// });

	$('.select-option-wrap a').click(function(event) {
		var a_html = $(this).parent('.select-option').clone();
		$(this).closest('.size-box').find('.select-option-main').html(a_html);
		$(this).closest('.size-box').find('.select-option').removeClass('act');
		$(this).parent('.select-option').addClass('act');
		$(this).closest('.select-option-wrap').slideToggle('fast');
		
	});

	$('.label-radio, input[type="radio"]').click(function(event) {
		var iter = $(this).attr('iter');
		$('input#'+iter).click();

		if ($('#radio-1-2').is(':checked') || $('#radio-1-4').is(':checked')) {
			$('.cart-dost-addr').slideDown('fast');
			$('.cart-dost-addr-punkt').slideUp('fast');
			$('.tr-sbp').slideUp('fast');
		} else {
			if ($('#radio-1-3').is(':checked')) {
				$('.cart-dost-addr').slideUp('fast');
				$('.cart-dost-addr-punkt').slideDown('fast');
			} else {

				$('.cart-dost-addr').slideUp('fast');
				$('.cart-dost-addr-punkt').slideUp('fast');

				$('.tr-sbp').slideDown('fast');
			}
		}

		if (!$('#radio-1-1').is(':checked')) {
			$('#radio-2-2').prop('checked', false);
			$('#radio-2-1').prop('checked', true);
		}
		calcCart();
	});

	$('.minus').click(function(event) {
		var iter = $(this).attr('iter');
		var inp = $('.inp-kol[iter="'+iter+'"]');
		var val = parseInt(inp.val());
		val = val - 1;
		if (val<1) val = 1;
		inp.val(val);
		setcartcnt(iter, val);
		calcCart();
	});
	$('.plus').click(function(event) {
		var iter = $(this).attr('iter');
		var inp = $('.inp-kol[iter="'+iter+'"]');
		var val = parseInt(inp.val());
		val = val + 1;
		inp.val(val);
		setcartcnt(iter, val);
		calcCart();
	});
	$(document).on('keyup', '.inp-kol', function(event) {
		calcCart();
		
	});

	resize();
/*
	if ( typeof(localStorage.YuttiSortFavOn) !=='undefined' && localStorage.YuttiSortFavOn == 1) {
		sortByFav();
		sortByFav();
	}
	if ( typeof(localStorage.YuttiSortPriceOn) !=='undefined' && localStorage.YuttiSortPriceOn == 1) {
		sortByPrice();
		sortByPrice();
	}*/

	$('.color-check').click(function(event) {
		setFilter();
	});

	
	$('.inp_search').keyup(function(event) {
		if ($('.inp_search').val().length >= 3) {
			search();
		}
	});

	$('.tov-uhod-head').click(function(event) {
		if ($('.tov-uhod-desc').is(':visible')) {
			$('.tov-uhod-close').hide();
			$('.tov-uhod-open').show();
			$('.tov-uhod-desc').slideUp();
		} else {
			$('.tov-uhod-close').show();
			$('.tov-uhod-open').hide();
			$('.tov-uhod-desc').slideDown();
		}
	});

	$('#fInpZakPhone').mask('+7 (999) 999-99-99');

	// console.log(localStorage.YuttiSortFavDirection + localStorage.YuttiSortFavOn + ' ' + localStorage.YuttiSortPriceDirection + localStorage.YuttiSortPriceOn);

});	