var isMakeOrder = false;
var slideMobileModule = new SlideModule();
var slideDesktopModule = new SlideModule();

$(window).ready(function() {
	$('.chosenselect').chosen({
		width: "108px",
		disable_search: true
	});
	$('.other .prd-small-carousel').prdCarousel({
		staticFirst: true,
		margin: 0,
		items: 9999999,
		responsive: {
			768: {
				items: 5
			}
		}
	});
	$('.recommend .prd-small-carousel').prdCarousel({
		staticFirst: true,
		margin: 0,
		items: 10,
		responsive: {
			768: {
				items: 3
			}
		}
	});
	//Сворачивание, разворачивание блока инструкций покупателю
	$(".requiredInfo-instruction-link-show").on("click", function() {
		$(this).find('img').toggleClass('rotate180');
		$(".requiredInfo-instruction-text-block").toggleClass("hidden");
	});
	$(".requiredInfo-instruction-link-hide").on("click", function() {
		$(".requiredInfo-instruction-link-show").find('img').removeClass("rotate180");
		$(".requiredInfo-instruction-text-block").addClass("hidden");
	});
	//Сворачивание, разворачивание блока Предупреждение
	$(".requiredInfo-risks-link-show").on("click", function() {
		$(this).find('img').toggleClass('rotate180');
		$(".requiredInfo-risks-block-text").toggleClass("hidden");
	});
	$(".requiredInfo-risks-link-hide").on("click", function() {
		$(".requiredInfo-risks-link-show").find('img').removeClass("rotate180");
		$(".requiredInfo-risks-block-text").addClass("hidden");
	});
	$(document).on('click', '.order-extras__select-block', function() {
		$('#order-extras_' + $(this).data('id') + ', #order-extras_' + $(this).data('id') + '_right').prop('checked', true);
		recalculatePrice('side');
	});
	$(".order-extra-item").on("click", function(e) {
		var checkbox = $(this).find("input[type='checkbox']");
		if (checkbox.prop("checked")) {
			if (!$(e.target).is('.chosen-container') && $(e.target).closest('.chosen-container').length === 0) {
				checkbox.prop("checked", false);
			}
		} else {
			checkbox.prop("checked", true);
		}
		recalculatePrice();
	});
	$(".order-extra-item-right").on("click", function(e) {
		var checkbox = $(this).find("input[type='checkbox']");
		if (checkbox.prop("checked")) {
			if (!$(e.target).is('.chosen-container') && $(e.target).closest('.chosen-container').length === 0) {
				checkbox.prop("checked", false);
			}
		} else {
			checkbox.prop("checked", true);
		}
		recalculatePrice('side');
	});
	$('.js-cannotorder').on('click', function() {
		can_not_order_popup(jsCategoryName, jsCategorySeo);
	});
	$('.js_package_card_vert__toggleInfo').on('click', function() {
		if ($(this).parent().find('.package_card_vert_info').css('display') == 'block') {
			return;
		}
		$(this).parent().parent().find('.package_card_vert_info').slideUp('fast');
		$(this).parent().parent().find('.package_card_vert__arrow').show();
		$(this).parent().find('.package_card_vert_info').slideDown('fast');
		$(this).parent().find('.package_card_vert__arrow').hide();
	});
	$('#button-contact-with-me').on('click', function() {
		//var workername = $('#button-contact-with-me').data('workername');
		//location.href = "/conversations/" + workername + "?prdId=" + post_id + "&goToLastUnread=1";
	});

	setTimeout(function() {
		slideMobileModule.init({
			sliderName: '.prd_slider_mobile #slider_mobile',
			settings: {
				lazyLoad: 'ondemand',
				slidesToShow: 1,
				slidesToScroll: 1,
				dots: false,
				arrows: false,
				infinite: true,
				sliderCount: true,
				adaptiveHeight: true,
				mode: 'mobile'
			}
    });
 	}, 200);

	slideDesktopModule.init({
		sliderName: '.prd_slider_desktop #slider_desktop',
		settings: {
			lazyLoad: 'ondemand',
			slidesToShow: 1,
			slidesToScroll: 1,
			dots: false,
			arrows: true,
			infinite: true,
			speed: 100,
			fade: true,
			cssEase: 'linear',
			mode: 'desktop'
		}
	});
	$('.prd_slider_desktop #slider_desktop').on('beforeChange', function(event, slick, currentSlide, nextSlide) {
		$('.prd_slider_desktop #slider_desktop').addClass('prd-slider_preload')
		$('.prd_slider_desktop .sliderItem').css({
			visibility: "hidden"
		})
		$('.prd_slider_desktop .sliderItem[data-index="' + currentSlide + '"]').css({
			visibility: "visible"
		})
		$('.prd_slider_desktop .sliderItem[data-index="' + nextSlide + '"]').css({
			visibility: "visible"
		})
	});

	$('.prd_slider_desktop #slider_desktop .slick-slide img').on('load', function() {
		$('.prd_slider_desktop #slider_desktop').removeClass('prd-slider_preload');
	});

	$(document).on('click', '.prd-count>div', function() {
		if ($(this).hasClass('prd-count_minus')) {
			if (parseInt($(this).siblings('input').val()) == 1) {
				return false;
			}
			$(this).siblings('input').val(parseInt($(this).siblings('input').val()) - 1);
		} else {
			if (parseInt($(this).siblings('input').val()) >= parseInt($(this).siblings('input').attr('data-max'))) {
				return false;
			}
			$(this).siblings('input').val(parseInt($(this).siblings('input').val()) + 1)
		}
		recalculatePrice();
	});
	init_package_tabs();
	$(document).on('click', '.package_tabs>*', function() {
		$('.package_tabs .active').removeClass('active');
		$(this).addClass('active');
		$(this).parents('.b-package').removeClass('show-standard').removeClass('show-medium').removeClass('show-premium');
		$(this).parents('.b-package').addClass('show-' + $(this).attr('data-type'))
	});

});

window.ad_product = {
	"id": post_id,
	"price": price,
  "price_dodji": price_dodji,
	"url": productUrl,
	"picture": pictureUrl,
	"name": productName,
	"category": productCategory
};

$(window).load(function() {
	ReviewsModule.init({
		id: post_id,
		onPage: 10,
		onPageStart: 5,
		entity: 'prd',
		baseUrl: baseUrl
	});
	if (isRecalculatePrice) {
		recalculatePrice('side');
	}
	if (showBalancePopup) {
		show_balance_popup(balanceRefillAmount, 'prd');
	}
	if (isUserDodjiAndOnPause) {
		show_message('notice', noticeMessage);
	}
	recalculatePrice('', true);
	recalculatePrice();
	$('a.edit-prd-button.has-offers').click(function() {
		change_prd_offer_confirm($(this).attr('href'));
		return false;
	});
	$('.package_cards_row .package_cards_block:not(:first-child)').hover(function() {
			$('.package_cards_block').removeClass('package_card_selected');
			var $packageCardsElement = $('.package_cards_');
			$packageCardsElement.css('padding-bottom', 3);
			var t = parseInt($(this).index()) + 1;
			$('.package_cards_row .package_cards_block:nth-child(' + t + ')').addClass('package_card_selected');
			$packageCardsElement.css('padding-bottom', 0);
		},
		function() {
			var t = parseInt($(this).index()) + 1;
			$('.package_cards_row .package_cards_block:nth-child(' + t + ')').removeClass('package_card_selected');
			$('.package_cards_').css('padding-bottom', 3);
		});
});

var bookmark_login_redirect = function() {
	$('.login-js:first').trigger('click');
};

function recalculatePrice(place, preCalc) {
	if (isPackage) {
		return;
	}

	if (place !== 'side') {
		place = '';
	}
	var $prdCountElement = $("#prdcnt" + place);
	var $prdCountMobileElement = $('.prdcnt_mobile');
	var count = $prdCountElement.val() ? $prdCountElement.val() : 1;
	if ($prdCountMobileElement.is(":visible")) {
		count = parseInt($prdCountMobileElement.val()) ? parseInt($prdCountMobileElement.val()) : 1;
	}

	var totalPrice = price * count;
  var totalPriceDodji = price_dodji * count;
	if (actor_lang == 'ru' && prdLang == 'en') {
		totalPrice = totalPrice * CURRENCY_RATE * 100;
		totalPrice = Math.round(totalPrice) / 100.0;
	}
	var totalTime = Number(getDuration(prdDays, count, rate));
	$prdCountElement.val(count);
	$prdCountElement.trigger("chosen:updated");
	$("#newextform" + place + " input[type='checkbox']:not(.js-order-quick)").each(function() {
		var EID = $(this).val();
		var $extraCountElement = $("#extra_count" + place + EID);
		var $orderExtrasElement = $("#order-extras_" + EID + (place == "side" ? "" : "_right"));
		var $orderExtraBlock = $("#order-extra-block-" + EID);
		var $orderExtraBlockRight = $("#order-extra-block-" + EID + "-right");

		var count = $extraCountElement.val();
		if ($prdCountMobileElement.is(":visible")) {
			count = parseInt($("#mobile_extra_count" + EID).val())
		}

		if ($(this).is(':checked')) {
			var priceStr = $(this).attr('data-price');
      var priceDodjiStr = $(this).attr('data-pricedodji');
			totalPrice += parseFloat(clearPriceStr(priceStr)) * count;
      totalPriceDodji += parseFloat(clearPriceStr(priceDodjiStr)) * count;

			totalTime += getDuration(Number($(this).attr('data-time')), count, rate);
		}
		$orderExtraBlockRight.toggleClass("bgBeige", $(this).is(':checked'));
		$orderExtraBlock.toggleClass("bgBeige", $(this).is(':checked'));
		$orderExtrasElement.prop('checked', $(this).is(':checked'));
		$extraCountElement.val(count);
		$extraCountElement.trigger("chosen:updated");
	});

	if (!preCalc) {
		var totalPriceString = "",
        totalPriceDodjiString = "";
    totalPriceString = Utils.numberFormat(totalPrice, 2, ".", " ");
    totalPriceDodjiString = Utils.numberFormat(totalPriceDodji, 2, ".", " ");

		$('.newordext:not(.newordext-dodji)').html(totalPriceString);
    $('.newordext.newordext-dodji').html(totalPriceDodjiString);
    if(totalPriceDodji > 0) {
      $('.newordext.newordext-dodji').parent().show();
    } else {
      $('.newordext.newordext-dodji').parent().hide();
    }
		$('#time').html(totalTime + ' ' + declension(totalTime, 'день', 'дня', 'дней'));
	}
}

function recalculateQuick(totalPrice, totalTime) {}

function PopUpShow() {
	$("#popup1").show();
}

function PopUpHide() {
	$("#popup1").hide();
}

function checkQuickPackage(packageType, check, quickPrice, price) {}

function make_order(indodji) {
	if (isMakeOrder) {
		return false;
	}
	isMakeOrder = true;

	var data = $('#newextformside').serialize();
	if (CartModule !== undefined) {
		CartModule.preventNextShow();
	}
	$.ajax({
		type: "POST",
		url: '/api?method=cart_order&indodji=' + indodji,
		data: data,
		dataType: 'json',
		success: function(result) {
			if (result.success === true) {
				$('.js-make-order').attr('disabled', 'disabled').addClass('make-order-disable');
				$('.js-make-order').removeAttr('href');
				location.href = result.redirect;
			} else {
        $('#header_cart_morder_ispay').hide(); $('#header_cart_morder').show();
				if (result.error == 'purse') {
					location.replace(result.redirect);
					return true;
				} else if (result.error == 'paused_prd') {
					show_message('notice', t(cot_sitename['phrases']['paused_fcharup'] + ', поскольку очередь к нему достигла {{0}} заказов. ' + cot_sitename['phrases']['hasbeenunpaused_fcharup'] + ', когда очередь снизится до {{1}} заказов.', [$("#newextformside").attr('data-pause-on'), $("#newextformside").attr('data-pause-off')]));
				} else {
          if(result.purse_amount > 0) {
            if(indodji) {
              show_balance_dodji_popup(result.purse_amount, 'prd', result.id);
            } else {
              show_balance_popup(result.purse_amount, 'prd', result.id);
            }
          } else {
					  show_message('error', 'Произошла ошибка. Пожалуйста, попробуйте еще раз.');
          }
        }
				isMakeOrder = false;
			}
		},
		error: function() {
			isMakeOrder = false;
		}
	});
  return false;
}

function make_package_order(prdId, type, isCart, obj, indodji) {
  if(typeof indodji != 'undefined' && indodji == 1) {
    if(isCart) return false;
  } else {
    indodji = 0;
  }

	if (isMakeOrder) {
		return false;
	}
	isMakeOrder = true;
	if (typeof obj === 'undefined') {
		var isQuick = $(".package_card_quick-option__value").find("input[name='" + type + "_duration']:checked").val();
	} else {
		var isQuick = $("#package_" + type + "_quick").is(':checked');
	}
	var data = {
		prdId: prdId,
		packageType: type,
		isCart: isCart,
		isQuick: isQuick
	};
	if (!isCart && CartModule !== undefined) {
		CartModule.preventNextShow();
	}
	$.ajax({
		type: "POST",
		url: '/api?method=cart_order&indodji=' + indodji,
		data: data,
		success: function(data) {
      $('#header_cart_morder_ispay').hide(); $('#header_cart_morder').show();
			var result = JSON.parse(data);
			if (result.success) {
				if (isCart) {
					isMakeOrder = false;

          if(result.item.ciexists == 1) {
            $('.cart-popup .block-popup .block-popup_body_conteiner .cart-popup_row[data-id="' + result.id + '"]').remove();
          }
          var newitem = '<div class="cart-popup_row" data-id="' + result.id + '">' +
                          '<div class="cart-popup__col cart-popup__image"><a role="button"><img src="' + result.item.photo_first + '" width="90" height="60" alt=""></a></div>' +
                          '<div class="cart-popup__col cart-popup__name"><a role="button" class="cart-popup_text">' + result.item.title + '</a></div>' +
                          '<div class="cart-popup__col cart-popup__count">' + result.item.cnt_item + '</div><div class="cart-popup__col cart-popup__extras">' + result.item.cnt_extras + '</div>' +
                          '<div class="cart-popup__col cart-popup__sum"><span class="cart-popup_price_prd-js" data-price="' + result.item.cost + '">' + result.item.cost_format + '</span>&nbsp;<span class="rouble">Р</span></div>' +
                          '<div class="cart-popup__col cart-popup__delete-block">' +
                            '<div class="cart-popup_delete" onclick="CartModule.deleteItem(this, ' + result.id + ');"></div>' +
                          '</div>' +
                        '</div>';

          $('.cart-popup').addClass('active').find('.block-popup .cart-popup_empty_block').hide();
          $('.cart-popup .block-popup .block-popup_body_conteiner').prepend(newitem);
      		$('.dropdownbox').hide();
      		$('.cart-popup').find('.block-popup').fadeIn(200, 'swing');
      		$('.cart-popup .block-popup_body').jScrollPane();
      		update_cart();
      		refreshCartScroll();
      		$('.cart-popup .cart-popup_icon').addClass('active');
      		$('.massage .block-popup').hide();

					return true;
				} else {
				  window.location.replace(result.redirect);
        }
			} else {
				if (result.error == 'purse') {
					location.replace(result.redirect);
					return true;
				} else if (result.error == 'paused_prd') {
					show_message('notice', t(cot_sitename['phrases']['paused_fcharup'] + ', поскольку очередь к нему достигла {{0}} заказов. ' + cot_sitename['phrases']['hasbeenunpaused_fcharup'] + ', когда очередь снизится до {{1}} заказов.', [$("#newextformside").attr('data-pause-on'), $("#newextformside").attr('data-pause-off')]));
				} else {
          if(result.purse_amount > 0) {
            if(indodji) {
              show_balance_dodji_popup(result.purse_amount, 'prd', result.id);
            } else {
              show_balance_popup(result.purse_amount, 'prd', result.id);
            }
          } else {
					  show_message('error', 'Произошла ошибка. Пожалуйста, попробуйте еще раз.');
          }
        }
				isMakeOrder = false;
			}
		},
		error: function() {
			isMakeOrder = false;
		}
	});
}

function init_package_tabs() {
	if ($('.package_tabs>*') && $('.package_tabs>*').length && $('.package_tabs>*').is(':visible')) {
		$('.package_tabs>*:nth-child(2)').trigger('click');
	}
}

$(document).ready(function() {
  $('select[name^="extra_count"], select[name="prdcnt"]').change(function() {
  	var tval = $(this).val();
  	var other = $('select[name="' + $(this).attr('name') + '"]').not($(this));
    if(other.val() != tval) {
      other.find('option').prop('selected', false).filter('[value="' + tval +'"]').prop('selected', true);
      other.change();
    }
  });
});