(function ($) {
	$(function () {
		Pod.require(['xmasTreeVars'], function (xmasTreeVars) {
			var canPickUpGift = xmasTreeVars.canPickUpGift;
			var minDeposit = xmasTreeVars.minDeposit;
			var instantGifts = xmasTreeVars.instantGifts;
			var collectibleGifts = xmasTreeVars.collectibleGifts;

			function countPickedUpGiftsAmount(gifts) {
				var count = 0;
				$.each(gifts, function (key, g) {
					count += g.pickedUpAmount ? 1 : 0;
				});
				return count;
			}

			function updateInstantGiftsView() {
				var listTag = $('#js_instant_gifts_slider');

				$.each(instantGifts, function (key, g) {
					var tag = listTag.find('#instant_gift_' + g.id);
					if (g.pickedUpAmount == 0) {
						tag.children('.newyear_prize_tip').remove();
						tag.append(
								$('<div>').addClass('newyear_prize_tip')
										.append($('<p>').addClass('newyear_instant_tip_title').text(g.name))
										.append($('<p>').addClass('newyear_instant_tip_text').html('<a href="/cashier">Пополните счёт</a>, чтобы получить этот подарок!'))
						);
						tag.addClass('unavailable');
					} else {
						tag.removeClass('unavailable');
						tag.children('.newyear_prize_tip').remove();
						tag.append(
								$('<div>').addClass('newyear_prize_tip')
										.append($('<p>').addClass('newyear_instant_tip_title').text(g.name))
										.append($('<p>').addClass('newyear_instant_tip_text').html(g.tipText || ''))
						);
					}
				});
				$('#js_instant_picked_up_gifts_amount').text(
					countPickedUpGiftsAmount(instantGifts).toString() + '/' + Object.keys(instantGifts).length
				);
			}

			function updateCollectibleGiftsView() {
				var listTag = $('#js_collectible_gifts_list');
				$.each(collectibleGifts, function (key, g) {
					var tag = listTag.find('#collectible_gift_' + g.collectible);
					if (g.pickedUpAmount == 0) {
						tag.find('img').attr('src', g.imgLocked);
						if (!tag.children('.newyear_prize_tip').length) {
							tag.append(
								$('<div>').addClass('newyear_prize_tip').addClass('down')
									.append($('<p>')
											.addClass('newyear_instant_tip_text')
											.html(g.tipText || '<a href="/cashier">Пополните счёт</a>, чтобы получить этот элемент коллекции!'))
							);
						}
					} else {
						tag.find('img').attr('src', g.imgUnlocked);
						tag.children('.newyear_prize_tip').remove();
					}
				});
				var collectedAmount = countPickedUpGiftsAmount(collectibleGifts).toString();
				var totalAmount = Object.keys(collectibleGifts).length;
				$('#js_collectible_picked_up_gifts_amount').text(collectedAmount + '/' + totalAmount);

				var collectionDone = collectedAmount == totalAmount;
				if (collectionDone) {
					$('#js_get_a_collectible_prize').hide();
					$('#js_collection_done_img').show();
				} else {
					$('#js_get_a_collectible_prize').show();
					$('#js_collection_done_img').hide();
				}
			}

			function scrollToXmasTree() {
				var offsetTop = $('.xmas_tree').offset().top;
				$('html, body').animate({
					scrollTop: offsetTop -= 74
				}, 1000);
			}

			$('#js_get_an_instant_prize').on('click', function (e) {
				if (canPickUpGift) {
					scrollToXmasTree();
				} else {
					location.href = '/cashier';
				}
				return false;
			});
			$('#js_get_a_collectible_prize').on('click', function (e) {
				if (canPickUpGift) {
					scrollToXmasTree();
				} else {
					location.href = '/cashier';
				}
				return false;
			});

			updateInstantGiftsView();
			updateCollectibleGiftsView();

			$('#xmas_page_events')
				.on('giftUpdated', function (e, gift) {
					console.log('onGiftUpdated', gift);
					if (!gift) {
						return;
					}
					updateInstantGiftsView();
					updateCollectibleGiftsView();
				})
				.on('giftPickedUpAmountChanged', function (e, data) {
					var giftId = data.giftId,
						collectible = data.collectible,
						deltaAmount = data.deltaAmount,
						popupParams = data.popupParams;
					console.log('giftPickedUpAmountChanged', data);
					if (!collectible) { // update instant gift
						var gift = instantGifts[giftId];
						if (gift) {
							gift.pickedUpAmount += deltaAmount;
							updateInstantGiftsView();
						} else {
							console.log('error: unable find gift with id ' + giftId);
						}
					} else { // update collectible gift
						$.each(collectibleGifts, function (key, g) {
							if (g.id == giftId && g.collectible == collectible) {
								g.pickedUpAmount += deltaAmount;
								updateCollectibleGiftsView();
								return false;
							}
						});
					}
					if (deltaAmount == 1 && popupParams) {
						if (collectible && countPickedUpGiftsAmount(collectibleGifts) == Object.keys(collectibleGifts).length) {
							popup_show('newyear_collection', null, 'popupLayoutNewyear');
						} else {
							popup_show('newyear_prize', popupParams, 'popupLayoutNewyear');
						}
					}
					$liveReload.reload(['account']); // обновить отображение кассы
				})
				.on('pickUp', function (e, data) {
					var callback = (data ? data.onFinish : null) || new Function();
					$.ajax(
						'actions/ajax/pobeda/ny2016/gift/pickup',
						{
							type: 'POST',
							dataType: 'json',
							context: this,
							success: function (response) {
								if (!response) {
									console.log('some error ocurred - response is empty');
								} else if (response.error) {
									if(response.canPickUpGift.length != 0) {
										window.open("/cashier", '_blank');
									}
									console.log('failed: ' + response.error);
								} else {
									console.log('gift granted', response.gift);
									canPickUpGift = response.canPickUpGift;
									$(this).trigger('giftPickedUpAmountChanged', {
										giftId: response.gift.id,
										collectible: response.gift.collectible,
										deltaAmount: 1,
										popupParams: response.gift.popupParams
									});
								}
								callback(canPickUpGift);
							},
							error: function (e) {
								console.log('generic error ' + e);
								callback(canPickUpGift);
							}
						}
					);
				})
				.attr('data-xmas-state', 'ready')
				.trigger('xmasReady', {canPickUpGift: canPickUpGift});
		});
	});
})($);