function setCookie(name, value, options) {
    options = options || {};
    var expires = options.expires;
    if (typeof expires == "number" && expires) {
        var d = new Date();
        d.setTime(d.getTime() + expires * 1000);
        expires = options.expires = d;
    }
    if (expires && expires.toUTCString) {
        options.expires = expires.toUTCString();
    }
    value = encodeURIComponent(value);
    var updatedCookie = name + "=" + value;
    for (var propName in options) {
        updatedCookie += "; " + propName;
        var propValue = options[propName];
        if (propValue !== true) {
            updatedCookie += "=" + propValue;
        }
    }
    document.cookie = updatedCookie;
}

function opencookie(par) {
    var allcookies = document.cookie;
    var pos = allcookies.indexOf(par);
    var dlina = par.length;
    if (pos !== -1) {
        var start = pos + dlina + 1;
        var end = allcookies.indexOf(';', start);
        if (end == -1) end = allcookies.length;
        var znachenie = allcookies.substring(start, end);
        znachenie = decodeURIComponent(znachenie);
        this.cooka = znachenie;
    }
}

function readcooka(name) {
    // if(document.cookie!==''){
    // 		var namecomcooka = new opencookie(name);
    // }
    // 	return namecomcooka.cooka;
    var matches = document.cookie.match(new RegExp("(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"));
    return matches ? decodeURIComponent(matches[1]) : undefined;
}

function  delete_product_in_cart(product_id) {
    $.ajax({
        data: {product_id: product_id, 'action' : 'remove_product_pp'},
        url: myajax.url,
        type: 'POST',
        dataType: "json",
        beforeSend: function(){
            $("#product-" + product_id).css("opacity", '0.5');
        },
        success: function(res){
            // console.log(res);
            if(!res) alert('Ошибка!');
            // console.log(res["html"]);
            $("#top-cart-link").html(res['fragments']['top_cart']);

            if(res['flag'] == 0){
                $("#popup-content").html(res['fragments']['cart_modal']);
                // $('a#checkout-link').css("display", "inline-block");
                // $('#title-cart').css("display", "inline-block");
                // $('#title-empty-cart').css("display", "none");
            }else{
                // $("#cart-modal").html(res['fragments']['cart_modal']);
                $("#popup-content").html("");
                $('a#checkout-link').css("display", "none");
                // $('#title-cart').css("display", "none");
                // $('#title-empty-cart').css("display", "inline-block");
                $("#link-empty-cart").trigger('click');
            }



        },
        error: function(){
            alert('Error!');
        }
    });
}

function getRandomArbitrary(min, max) {
    return Math.round(Math.random() * (max - min) + min);
}

function isset_product(hash) {
    var flag_a = 0;
    if (flag_a != 1) {
    	$('a.see-more').each(function(index) {

        var link = $(this);
        var id = link.data('id');
        var term = link.data('term');
        var limit = link.data('limit');
        var page = link.data('page');
        var offset = link.data('offset');
        var count = link.data('count');
        //console.log(term );
			console.log(count+' > '+offset);
        if(count > offset || $('#'+hash).length==0){
            $.ajax({
                type: "POST",
                url: myajax.url,
                data: {
                    'action': 'product_more',
                    id: id,
                    term: term,
                    limit: limit,
                    page: page,
                    offset: offset,
                    count: count,
                },
                beforeSend: function (msg) {
                    $(link).closest('div').find(".loader").html('<img src="/wp-content/themes/parfum/img/loading-slider.gif" alt="loader">');
                },
                success: function (msg) {
                    var next = parseInt(offset)+16;
                    // console.log(msg);
                    // var link_more = link;
                    // console.log(link_more);
                    // jQuery.data(link_more, 'offset', next);

                    link.data('offset',next);
                    //console.log(link.data('offset')+'offset');
                    //
                    var dataid = $(link).closest('section').attr('id');
                    // $('#more_block').find('#link_more').data('offset', next);
                    //
                    var length = document.getElementById(dataid).getElementsByClassName("tovar").length;


                    console.log(dataid+length+'-count-'+count);
                    if(count == length){
                        $(link).fadeOut();
                    }
                    $(link).closest('div').find(".loader").html("");
                    // $('.popup-overlay-white').fadeIn(500);
                    // window.location.href = "thanks.html";
                    // form[0].reset();
                    if ($('[data=' + hash + ']').length > 0) {
                            flag_a = 1;
                            //console.log(" //+ существует" + flag_a);
                            $("[data=" + hash + "] .product").css("box-shadow", "2px 2px 6px #FF4770, -2px -2px 6px #FF4770, -2px 2px 6px #FF4770, 2px -2px 6px #FF4770");
                            $("[data=" + hash + "]").attr('id', hash);
                              console.log(hash +"isset_product");
                            $.scrollTo('#' + hash, 800, {
                                offset: -80
                            });
							// СКРЫВАЕМ КНОПКУ
						    var length = document.getElementById(dataid).getElementsByClassName("tovar").length;
							//console.log(dataid+length);
							if(count == length){
								$(link).fadeOut();
							}
                            // return false;
                        } else {
                            var count_p = "1";
                            if (flag_a == 0) {
                               // console.log(" //не существует");
                                // $("section[data-term=" + cat + "]").append(html.data);
 
                                  $(link).closest('.category-content').find('.products').append(msg);
                                if (index == 1) {
                                     isset_product(hash);
                                }
                            }
                            count_p = count_p + 1;
                            // console.log(count_p);
                            // if(count_p == 8) return false;
                        }
                }
            })
        }else{
            link.fadeOut();
        }





    		console.log(offset);
    		// if(flag == true) return false;
    	});
    } else {
    	console.log('flag_a=1');
    }
}

function isset_product_OLD(hash) {
    var flag_a = 0;
    if (flag_a != 1) {
    	$('a.see-more').each(function(index) {
    		var cur = $(this);
    		console.log(index + 'index');
    		var cat = cur.attr("data-id");
    		var limit = cur.attr("data-limit");
            var term = cur.attr("data-term");
    		var page = cur.attr("data-page");
            var offset = cur.attr("data-offset");
    		console.log('cat-' + cat + 'page-' + page);
    		console.log('ajax' + flag_a);
    		$.ajax({
    			async: false,
               url: myajax.url,
    			type: "POST",

    			data: {
    				"category": cat,
    				"limit": limit,
    				"page": page,
    				"action" : 'product_more'
    			},
    			success: function(html) {
    				// if (html.status == "ok") {
    					var next;
    					page = parseInt(page);
    					next = page + 1;
    					offset = Number(offset) + 16;
    					console.log('page-' + next);
                    console.log('offset-' + offset);
    					cur.attr("data-offset", offset);
    					if ($('[data=' + hash + ']').length > 0) {
    						flag_a = 1;
    						console.log(" //+ существует" + flag_a);
    						// return false;
    					} else {
    						var count_p = "1";
    						if (flag_a == 0) {
    							console.log(" //не существует");
    							$("section[data-term=" + cat + "]").append(html.data);
    							if (index == 1) {
    								// isset_product(hash);
    							}
    						}
    						count_p = count_p + 1;
    						// console.log(count_p);
    						if(count_p == 5) return false;
    					}
    				// }
    			},
    			// dataType: 'json'
    		});
    		console.log(offset);
    		// if(flag == true) return false;
    	});
    } else {
    	console.log('flag_a=1');
    }
}




jQuery(document).ready(function($) {
   $('.popup-modal').magnificPopup({
            type: 'inline',
            preloader: false,
            closeOnBgClick: false,
            focus: '#username',
            // modal: true
        });
        $(document).on('click', '.popup-modal-dismiss', function (e) {
            e.preventDefault();
            $.magnificPopup.close();
        });
      // $("input[name=phone]").mask("8 (999) 999-99-99? x99");
    $('input[name="phone"]').mask("8 (999) 999-99-99");
    jcf.replaceAll();
    $('.timer').downCount({
        date: '09/09/2017 00:00:00',
        offset: +3
    });

	if (!readcooka('orders')) {
		$("#orders").text("267");
	} else {
		$("#orders").text(readcooka('orders'));
	}
	setCookie('orders', $("#orders").text(), {
		path: '/'
	});
	setInterval(function() {
		var text_orders = "";
		var text = $("#orders").text();
		if (text >= 0) {
			text_orders = Number(text) + 1;
			setCookie('orders', text_orders, {
				path: '/'
			});
			$("#orders").text(text_orders);
		} else {
			$("#orders").text("0");
			var date = new Date(0);
			document.cookie = "orders=; path=/; expires=" + date.toUTCString();
			setCookie('orders', $("#orders").text("267"), {
				path: '/'
			});
		}
	}, 15000);

	$("a.scrollToId").mPageScroll2id();
	$('input,textarea').focus(function() {
		$(this).data('placeholder', $(this).attr('placeholder'))
		$(this).attr('placeholder', '');
	});
	$('input,textarea').blur(function() {
		$(this).attr('placeholder', $(this).data('placeholder'));
	});
    $('.popup-with-form').magnificPopup({
        type: 'inline',
        preloader: false,
        focus: '#name',
  		closeOnBgClick: false,
        // When elemened is focused, some mobile browsers in some cases zoom in
        // It looks not nice, so we disable it:
        callbacks: {
            beforeOpen: function() {
                if($(window).width() < 700) {
                    this.st.focus = false;
                } else {
                    this.st.focus = '#name';
                }
            }
        }
    });


	// $("#cart .ajax-popup.woman-button").click(function() {
	// 	$.scrollTo('#order', 800, {
	// 		offset: -80
	// 	});
	// });
	// alert("dd");
	// убираем placeholder при нажатии
	$('input,textarea').focus(function() {
		$(this).data('placeholder', $(this).attr('placeholder'))
		$(this).attr('placeholder', '');
	});
	$('input,textarea').blur(function() {
		$(this).attr('placeholder', $(this).data('placeholder'));
	});


	if (document.location.hash != "") {
		var hash = document.location.hash;
		hash = hash.replace(/\s/g, "_");
		hash = hash.replace(/&/g, "");
		hash = hash.replace(/%20/g, "_");
		hash = hash.replace("#", "");
		if ($('[data=' + hash + ']').length > 0) {
			// return false;
			//console.log(" существует");
		} else {
			//console.log(" не существует");
			isset_product(hash);
		}
		$("div[data=" + hash + "] .product").css("box-shadow", "2px 2px 6px #FF4770, -2px -2px 6px #FF4770, -2px 2px 6px #FF4770, 2px -2px 6px #FF4770");
		$("div[data=" + hash + "]").attr('id', hash);
		$.scrollTo('#' + hash, 800, {
			offset: -80
		});
		// $('body').animate({scrollTop: $("div[data="+hash+"]").offset().top-100}, 800);
		// return false;
	}

	//$('.bs-component [data-toggle="popover"]').popover();


	var popOverSettings = {
		selector: '.bs-component [data-toggle="popover"]'
	}

	$('body').popover(popOverSettings);


	$(".view-descr").click(function() {
		var ariaid = $(this).attr("aria-describedby");
		if ($(this).attr("aria-describedby")) {
			$(this).text("Посмотреть описание");
		}
		if (!$("div#" + ariaid + "").is(".popover.fade.bottom.in")) {
			$(this).text("Скрыть описание");
		}
	});

    $('.see-more').click(function (e) {
        e.preventDefault();
        var link = $(this);
        var id = link.data('id');
        var term = link.data('term');
        var limit = link.data('limit');
        var page = link.data('page');
        var offset = link.data('offset');
		var count = link.data('count');

		//console.log(term );
        if(count > offset){
            $.ajax({
                type: "POST",
                url: myajax.url,
                data: {
                    'action': 'product_more',
                    id: id,
                    term: term,
					limit: limit,
					page: page,
                    offset: offset,
                    count: count,
                },
                beforeSend: function (msg) {
					$(link).closest('div').find(".loader").html('<img src="/wp-content/themes/parfum/img/loading-slider.gif" alt="loader">');
                },
                success: function (msg) {
                    //console.log(offset+'offset');
                    var next = parseInt(offset)+16;
                    // console.log(msg);
                    // var link_more = link;
                    // console.log(link_more);
                    // jQuery.data(link_more, 'offset', next);

                    link.data('offset',next);
                   
                    $(link).closest('.category-content').find('.products').append(msg);
                    var dataid = $(link).closest('section').attr('id');
                    // $('#more_block').find('#link_more').data('offset', ne xt);
                    //
                    var length = document.getElementById(dataid).getElementsByClassName("tovar").length;


                    console.log(dataid+length+'count'+count);
                    if(count == length){
                        $(link).fadeOut();
                    }
                    $(link).closest('div').find(".loader").html("");
                    // $('.popup-overlay-white').fadeIn(500);
                    // window.location.href = "thanks.html";
                    // form[0].reset();
                }
            })
        }else{
            link.fadeOut();
        }

    });
  
  

    $('#cart-modal ').on('click', '.btn-del', function(e){
        e.preventDefault();
        var product_id = $(this).data('product_id');
        delete_product_in_cart(product_id);
        return false;
    });
    $(".backing").click(function(e) {
        e.preventDefault();
        console.log("backing");
        var magnificPopup = $.magnificPopup.instance;
        magnificPopup.close();
        return false;
    });



    $('#cart-modal').on('click', '.jcf-number > span', function(e){
        var current_qty = $(this).parent().find('input[type=number]').val();
        var act = '';
        var qty = 1;

        if($(this).hasClass('jcf-btn-inc')) act = 'plus';
        if($(this).hasClass('jcf-btn-dec')) act = 'minus';
        // var product_sum = $(this).closest('tr').find('.wid-9 strong span').text();
        // console.log(product_sum);
        var product_id = $(this).closest('tr').data('id');
        // alert(current_qty);

        if(current_qty !== 0 && current_qty < 999) {
            change_ajax_qty(product_id, current_qty, qty, act);
        }else if(current_qty > 999){
            $(this).parent().find('input[type=number]').val('999');
            alert("Вы превысили максимальное колличество товаров в заказе");
        }
        if(current_qty == '1'){
            // $(this).parent().find('input[type=number]').val('1');
            // alert("Такой товар только один в корзине. Удалите его");
        }
    });

    function sendemail(name, phone){
        $.ajax({
            type: "POST",
            url: myajax.url,
            data: {
                'action': 'sendform',
                'name' : name,
                'phone'  : phone
            },
            beforeSend: function (msg) {

                // var magnificPopup = $.magnificPopup.instance;
                // magnificPopup.content[0].innerHTML = '<div style="width:300px; height:200px; text-align: center; vertical-align: middle; display: table-cell;"><img src="/wp-content/themes/parfum/img/loading2.gif" width="20"></div>';
            },
            success: function (res) {
                // console.log(msg);
                // if(msg == "success"){
                $("#popup-content").html(res['fragments']['cart_modal']);
                $("#top-cart-link").html(res['fragments']['top_cart']);
                console.log("success");
                $("#checkout-link").css("display", "none");
                $("#phone").removeClass("error");
                $("#success-link").trigger('click');
                var magnificPopup = $.magnificPopup.instance;
                // magnificPopup.content[0].innerHTML = '<div id="success" class="window" style="text-align: center;">	<p style="font-size: 22px; color: green; text-align:center;">Спасибо!</p><p style="font-size: 18px; text-align: center;">Ваша заявка принята.</p></div>';
                setTimeout(function(){
                    magnificPopup.close(); // Close popup that is currently opened
                }, 3500);

                // }
            }
        })
    }




    $('#cart-modal').on('keyup', 'input[type=number]', function(e){
        var qty = $(this).val();
        var product_id = $(this).closest('tr').data('id');
        var act = 'qty';
        if(qty !== ''){
            console.log(qty);
            change_ajax_qty(product_id, qty, act);
        }



    });





    function showCart(cart){
        // $('#cart ').html(cart);

    }


    function change_ajax_qty(product_id, current_qty, qty, act){

        $.ajax({
            data: {'product_id': product_id, 'action' : 'change_qty', 'act': act, 'qty': qty, 'current_qty' : current_qty },
            url: myajax.url,
            type: 'POST',
            // dataType: "json",
            beforeSend: function(){
                $("#product-" + product_id).css("opacity", '0.5');
            },
            success: function(res){
                console.log(res);
                if(!res) alert('Ошибка!');
                $('a#checkout-link').css("display", "inline-block");
                // $('#title-cart').fadeIn();
                // $('#title-empty-cart').fadeOut();
                $("#popup-content").html(res['fragments']['cart_modal']);
                $("#top-cart-link").html(res['fragments']['top_cart']);

                $("#top-cart-link").trigger('click');
                // if(res['json']['cart']['qty'] !== null){
                    // $("#top-cart").find(".fa-shopping-cart > span").html(res['json']['cart']['qty']);
                    // $("#top-cart").find("a > span").html(res['json']['cart']['sum']);
                    // $("#product-" + product_id).find('.wid-9 strong span').text(res['json']['product']['sum']);
                    // $('#cart').find('.total-price .price span').text(res['json']['cart']['sum']);
                    // $("#product-" + product_id).css("opacity", '1');
                // }
                // else {
                    // $("#top-cart").find(".fa-shopping-cart > span").fadeOut();
                    // $("#top-cart").find("a ").html("Корзина пуста");
                    // showCart(res["html"]);
                    // $(".client-info").remove();
                    // $(".btns").remove();

                // }


            },
            error: function(){
                alert('Error!');
            }
        });



    }



});

// Ajax add to cart (on list page)

// overlay + form

$( ".pop3477" ).click(function() {
        $( ".forma .form-wrap,.overlay_form" ).fadeIn( "slow")
    });

$( ".overlay_form,.close_btn" ).click(function() {
        $( ".forma .form-wrap,.overlay_form" ).hide("slow")
    });

$( ".close_btn2" ).click(function() {
        $( ".forma .form-wrap,.overlay_form" ).hide("slow")
    });
