jQuery(function ($) {

	Handlebars.registerPartial('miniCartItem', $("#MiniCart-ItemDetail").html());

	CCRZ.models.miniCartModel = CCRZ.CloudCrazeModel.extend({
		className: 'B2C_HeaderPageController',
		fetch: function () {
			var m = this;
			m.set('loaded',false);
			m.set('cartId', CCRZ.pagevars.currentCartID);
				this.invokeCtx('getMiniCartData', m.get('cartId'), function (response, event) {
					if (response && response.success && response.data) {
						m.set(m.parse(response.data));
						m.processData();
						m.set('loaded', true);
					} else {
						m.set('loaded', true);
						m.set('cartEmpty', true);
					}
					CCRZ.pubSub.trigger('miniCartLoaded');
				}, { buffer: true, nmsp: false });
				m.set('cartEmpty', true);
				
		},
		processData : function() {
			let m = this;
			let items = m.attributes.ccrz__E_CartItems__r;
			if(items && items.length > 0){
				m.set('cartEmpty', false);
			}
			_.forEach(items, function (item) {
					item.STEXCartClassification__c = m.attributes.STEXCartClassification__c;
					item.SKU = item.ccrz__Product__r.ccrz__SKU__c;
			});
		}
	});

	CCRZ.miniCartView = CCRZ.util.createView({
				desktop: { target: 'miniCart-RenderTarget', template: 'MiniCart-Template' },
				containers: { desktop:'#miniCart:visible', mobile:'#miniCart-Mobile' },
				model: new CCRZ.models.miniCartModel(),
				init: miniCartInit,
				render: miniCartRender,
				setupListeners: setupListeners,
				updateContainer: updateContainer,
				goToCart: goToCart,
				goToCheckout: goToCheckout,
				showMiniCart: showMiniCart,
				hideMiniCart: hideMiniCart,
				toggleMiniCart: toggleMiniCart,
				setupTimer: setupTimer,
				startTimer: startTimer,
				stopTimer: stopTimer,
				setupOutsideClick: setupOutsideClick,
				removeAllListeners: removeAllListeners,
				shown: false,
				hideTime: 4000,
				hoverHideTime: 2000,
				mobileBreak: 480,
				events: {
					'click .miniCart-cartBtn' : 'goToCart',
					'click .miniCart-checkoutBtn' : 'goToCheckout'
				}
			});

	function goToCart() {
		CCRZ.headerView.goToCart();
	}

	function goToCheckout() {
		document.location = "/Store/ccrz__CheckoutNew?cartID=" + CCRZ.pagevars.currentCartID + getCSRQueryString();
	}

	function setupTimer() {
		this.$el.off('mouseenter mouseleave');
		this.startTimer(this.hideTime);
		this.$el.mouseenter( () => this.stopTimer() );
		this.$el.mouseleave( () => this.startTimer(this.hoverHideTime) );
	}

	function startTimer(time) {
		this.timerId = setTimeout(this.hideMiniCart.bind(this), time);
	}

	function stopTimer() {
		clearTimeout(this.timerId);
	}

	function setupOutsideClick() {
		$('body').mousedown( (e) => {
			let clickedCartButton = $.contains($('.chead:visible')[0], e.target);
			let clickedMiniCart = $.contains(this.$el[0], e.target);
				if ( !(clickedCartButton || clickedMiniCart) ) {
					this.hideMiniCart();
				} 
			} 
		);
	}

	function removeAllListeners() {
		CCRZ.pubSub.off('miniCartLoaded');
		$('body').off('mousedown');
		this.$el.off('mouseenter mouseleave');
	}

	function miniCartInit() {
		this.model.fetch();
		this.setupListeners();
	}

	function setupListeners() {
		this.listenTo(CCRZ.pubSub, 'cartChange', function (cartId) {
			this.model.set({ cartId: cartId });
			this.model.fetch();
			
		});
		this.listenTo(CCRZ.pubSub, 'showMiniCart', function (isAddToCart) {
			this.showMiniCart(isAddToCart);
		});
		this.listenTo(CCRZ.pubSub, 'hideMiniCart', function () {
			this.hideMiniCart();
		});
		this.listenTo(CCRZ.pubSub, 'toggleMiniCart', function () {
			this.toggleMiniCart();
		});
		this.listenTo(CCRZ.pubSub, 'view:headerView:refresh', function () {
			this.$el = $('#miniCart-RenderTarget');
			this.delegateEvents();
			this.updateContainer();
		});

		//change btwn mobile/desktop containers when crossing breakpoint
		let prevSize = $(window).width();
		let v = this;
		$(window).resize(function(){
			if( $(window).width() <= v.mobileBreak && prevSize > v.mobileBreak ){
				v.updateContainer();
			} else if ( $(window).width() > v.mobileBreak && prevSize <= v.mobileBreak ){
				v.updateContainer();
			}
			prevSize = $(window).width();
		});
	}

	function showMiniCart(isAddToCart) {
		CCRZ.pubSub.off('miniCartLoaded');
		CCRZ.pubSub.on('miniCartLoaded', () => {this.render()});
		this.shown = true;
		this.setupOutsideClick();
		if(isAddToCart) {
			this.model.set('title', CCRZ.pageLabelMultiString('MiniCartAddedTitle',0).string);
			$('html').animate({
				scrollTop: (this.$el.offset().top)
			},0);
			this.setupTimer();
		} else {
			this.model.set('title', CCRZ.pageLabelMultiString('MiniCartTitle',0).string);
		}

		this.render();
	}

	function hideMiniCart() {
		this.$el.fadeOut('slow');
		this.removeAllListeners();
		this.shown = false;
	}

	function toggleMiniCart() {
		this.shown ? this.hideMiniCart() : this.showMiniCart();
	}

	function miniCartRender() {
		this.$el.fadeIn('slow');
		this.$el.html(this.desktop.template(this.model.attributes));
	}

	function updateContainer() {
		if( $(window).width() <= this.mobileBreak){
			$(this.containers.mobile).append(this.$el.detach());
		} else {
			$(this.containers.desktop).append(this.$el.detach());
		}
		
	}
});