if(!jsFrontend) { var jsFrontend = new Object(); }

jsFrontend.shop =
{
	init: function()
	{
		jsFrontend.shop.cart.init();
		jsFrontend.shop.controls.init();
		jsFrontend.shop.checkout.init();
	},

	// end
	eoo: true
}


jsFrontend.shop.cart =
{
	gifts: [],
	numbers: [],
	products: [],
	shipping: [],

	init: function() {
		$('.highlight').effect('highlight', {}, 750);
		jsFrontend.shop.cart.buildWidget();
		jsFrontend.shop.cart.bindClick();

    $('#keepShopping').click(function (e) {
      e.preventDefault();
      $('#shopCartWidget').fadeOut();
    });

    var $pickup = $('.js-shipping-pickup');
    if ($pickup.length > 0) {
      $pickup.live('change', function() {
    		if ($(this).is(':checked')) {
    			$('#shippingDestination').hide();
          $('.js-itemPrice').hide();
          $('.js-itemPricePickUp').show();
          $('#mainContainer .cartTotal').text(
              Number((jsFrontend.shop.cart.numbers.total - jsFrontend.shop.cart.numbers.total_shipping).toFixed(2))
          );

    			return;
				}

        $('#shippingDestination').show();
        $('.js-itemPrice').show();
        $('.js-itemPricePickUp').hide();

        $('#mainContainer .cartTotal').text(
            jsFrontend.shop.cart.numbers.total
        );
      }).trigger('change');
		}
  },


	bindClick: function()
	{
		// when clicking on the cartbutton the item should appear (@remark: custom for the "standard" template)
		$('#cartButton a').live('click', function(evt)
		{
			// prevent default
			evt.preventDefault();

			// hide
			if($('#shopCartWidget').is(':visible')) $('#shopCartWidget').fadeOut();

			// show
			else $('#shopCartWidget').fadeIn();

			$(document).bind('click', function(evt) {
				// check if we clicked inside humanized box
				var outsideHumanized = false;
				$('#shopCartWidget').each(function() {
					if (evt.clientX < $(this).offset().left
						|| evt.clientY < $(this).offset().top
						|| evt.clientX > $(this).offset().left + $(this).width()
						|| evt.clientY > $(this).offset().top + $(this).height()) outsideHumanized = true;
				});
				if (outsideHumanized && $('#shopCartWidget:visible').length > 0)
				{
					$('#shopCartWidget').fadeOut();
					$(document).unbind('click');
					$('#cartButton a').die('click');
					jsFrontend.shop.cart.bindClick();
				}
			});
		});
	},


	buildWidget: function(cart)
	{
		// set cart
		if(typeof cart != 'undefined')
		{
			jsFrontend.shop.cart.gifts = (cart.gifts != null) ? cart.gifts : [];
			jsFrontend.shop.cart.numbers = (cart.numbers != null) ? cart.numbers : [];
			jsFrontend.shop.cart.products = (cart.products != null) ? cart.products : [];
			jsFrontend.shop.cart.shipping = (cart.shipping != null) ? cart.shipping : [];
		}
		else
		{
			jsFrontend.shop.cart.getCart();
		}

		// no products
		if((jsFrontend.shop.cart.products == null || jsFrontend.shop.cart.products.length == 0) && (jsFrontend.shop.cart.gifts == null || jsFrontend.shop.cart.gifts.length == 0))
		{
			$('.cartNoItems').show();
			$('.cartItems').hide();
			$('.cartNumItems').hide();
		}
		else
		{
			// apperently we should show the full cart (@remark: as usual there are custom thing for the "standard" template)
			// clear
			$('.cartProductsHolder, .cartProductsHolder').html('');

			// product row template available?
			if($('#cartProductRowTemplate').length > 0)
			{
				// get html
				var template = $('<div />').html($('#cartProductRowTemplate').clone(false).removeAttr('id').show());

				// loop products
				for(var i in jsFrontend.shop.cart.products)
				{
					// get html
					var html = $(template);

					$(html.find('.cartProductRowAmount')[0]).html(jsFrontend.shop.cart.products[i].amount);
					$(html.find('.cartProductRowUrl')[0]).attr('href', jsFrontend.shop.cart.products[i].full_url);
					$(html.find('.cartProductRowTitle')[0]).html(jsFrontend.shop.cart.products[i].title);
					$(html.find('.cartProductRowItemPrice')[0]).html((jsFrontend.shop.cart.products[i].is_promo) ? jsFrontend.shop.cart.products[i].promo_price : jsFrontend.shop.cart.products[i].price);

					// append
					$('.cartProductsHolder').append(html.html());
				}
			}

			// gifts row template available
			if($('#cartGiftRowTemplate').length > 0)
			{
				// get html
				var template = $('<div />').html($('#cartGiftRowTemplate').clone(false).removeAttr('id').show());

				// loop products
				for(var i in jsFrontend.shop.cart.gifts)
				{
					// get html
					var html = $(template);

					$(html.find('.cartGiftRowAmount')[0]).html(jsFrontend.shop.cart.gifts[i].amount);
					$(html.find('.cartGiftRowUrl')[0]).attr('href', jsFrontend.shop.cart.gifts[i].full_url);
					$(html.find('.cartGiftRowTitle')[0]).html(jsFrontend.shop.cart.gifts[i].title);
					$(html.find('.cartGiftRowItemPrice')[0]).html((jsFrontend.shop.cart.gifts[i].is_promo) ? jsFrontend.shop.cart.gifts[i].promo_price : jsFrontend.shop.cart.gifts[i].price);

					// append
					$('.cartGiftsHolder').append(html.html());
				}
			}

			// show hide
			$('.cartNoItems').hide();
			$('.cartItems').show();

			// multiple products
			if(jsFrontend.shop.cart.numbers.num_products > 1)
			{
				$('.cartProductsSingle').hide();
				$('.cartProductsMultiple').show();
			}

			// one product
			else if(jsFrontend.shop.cart.numbers.num_products == 1)
			{
				$('.cartProductsSingle').show();
				$('.cartProductsMultiple').hide();
			}

			// no products
			else $('.cartProductsRow').hide();

			// loop products
			for(var i in jsFrontend.shop.cart.products)
			{
				$('.cartProductSubTotal_'+ jsFrontend.shop.cart.products[i].id +'_'+ jsFrontend.shop.cart.products[i].variant_id).html(jsFrontend.shop.cart.products[i].sub_total);
			}

			// multiple gifts
			if(jsFrontend.shop.cart.numbers.num_gifts > 1)
			{
				$('.cartGiftsSingle').hide();
				$('.cartGiftsMultiple').show();
			}

			// one gift
			else if(jsFrontend.shop.cart.numbers.num_gifts == 1)
			{
				$('.cartGiftsSingle').show();
				$('.cartGiftsMultiple').hide();
			}

			// no gifts
			else $('.cartGiftsRow').hide();

			// set values
			$('.cartProductsNumItems').html(parseInt(jsFrontend.shop.cart.numbers.num_products));
			$('.cartGiftsNumItems').html(parseInt(jsFrontend.shop.cart.numbers.num_gifts));
			$('.cartNumItems').html('('+ (parseInt(jsFrontend.shop.cart.numbers.num_products) + parseInt(jsFrontend.shop.cart.numbers.num_gifts)) +')');

			$('.cartTotalGifts').html(jsFrontend.shop.cart.numbers.total_gifts);
			$('.cartTotalProducts').html(jsFrontend.shop.cart.numbers.total_products);
			$('.cartTotalShippingCosts').html(jsFrontend.shop.cart.numbers.total_shipping);
			$('.cartTotalDiscount').html(jsFrontend.shop.cart.numbers.total_discount);
			$('.cartTotalCustomerDiscount').html(jsFrontend.shop.cart.numbers.total_customer_discount);

			$('.cartTotal').html(jsFrontend.shop.cart.numbers.total);

			$('.cartShippingRowLabel').html(jsFrontend.shop.cart.shipping.label);
			$('.cartShippingRowFreeMessage').html(jsFrontend.shop.cart.shipping.free_message);

			if (jsFrontend.shop.cart.shipping.destination === 'pickup') {
				$('.cartShippingRowLabelRow').addClass('hidden');
				$('.cartShippingRowFreeMessage').removeClass('hidden');
			} else {
				$('.cartShippingRowLabelRow').removeClass('hidden');
				$('.cartShippingRowFreeMessage').addClass('hidden');
			}
			// when there are no items the number of items should be hidden (@remark: as usual there are custom thing for the "standard" template)
			if((parseInt(jsFrontend.shop.cart.numbers.num_products) + parseInt(jsFrontend.shop.cart.numbers.num_gifts)) > 0) $('.cartNumItems').show();
			else $('.cartNumItems').hide();

			// toggle
			if(jsFrontend.shop.cart.numbers.total_discount > 0) $('.toggleTotalDiscount').show();
			else $('.toggleTotalDiscount').hide();
			if(jsFrontend.shop.cart.numbers.total_customer_discount > 0) $('.toggleTotalCustomerDiscount').show();
			else $('.toggleTotalCustomerDiscount').hide();
		}
	},


	getCart: function()
	{
		$.ajax({
			url: '/frontend/ajax.php?module=shop&action=get_cart&language=nl&resetShipping=' + (document.resetShipping ? 'Y' : 'N'),
			async: false,
			success: function(json, textStatus)
			{
				if(json.code == 200 && json.data !== null)
				{
					jsFrontend.shop.cart.gifts = (typeof json.data.gifts != 'undefined' && json.data.gifts != null) ? json.data.gifts : [];
					jsFrontend.shop.cart.numbers = (typeof json.data.numbers != 'undefined' && json.data.numbers != null) ? json.data.numbers : [];
					jsFrontend.shop.cart.products = (typeof json.data.products != 'undefined' && json.data.products != null) ? json.data.products : [];
					jsFrontend.shop.cart.shipping = (typeof json.data.shipping != 'undefined' && json.data.shipping != null) ? json.data.shipping : [];

					return json.data;
				}
			}
		});
	},


	// end
	eoo: true
}


jsFrontend.shop.checkout =
{
	init: function()
	{
		$('#otherCountry').bind('change', function(e) {
			if($(this).is(':checked')) $('#billingCountry').addClass('disabled').attr('disabled', 'disabled');
			else $('#billingCountry').removeClass('disabled').attr('disabled', '');
		}).change();

		// change checkbox for billing address
		$('#billingSameAsShipping').bind('change', function()
		{
			if($(this).is(':checked'))
			{
				// disable
				$('#enableWithSameInvoice').hide();
				$('#enableWithSameInvoice input').attr('disabled', 'disabled').addClass('inputDisabled');
			}
			else
			{
				// enable
				$('#enableWithSameInvoice').show();
				$('#enableWithSameInvoice input').attr('disabled', '').removeClass('inputDisabled');
			}
		});

		// check checkbox for billing address
		if($('#billingSameAsShipping').is(':checked'))
		{
			// disable
			$('#enableWithSameInvoice').hide();
			$('#enableWithSameInvoice input').attr('disabled', 'disabled').addClass('inputDisabled');
		}
		else
		{
			// enable
			$('#enableWithSameInvoice').show();
			$('#enableWithSameInvoice input').attr('disabled', '').removeClass('inputDisabled');
		}

		// change checkbox for invoice
		$('#billingInvoice').bind('change', function()
		{
			if($(this).is(':checked'))
			{
				// enable
				$('#enableWithInvoice').show();
				$('#enableWithInvoice input').attr('disabled', '').removeClass('inputDisabled');
			}
			else
			{
				// disable
				$('#enableWithInvoice').hide();
				$('#enableWithInvoice input').attr('disabled', 'disabled').addClass('inputDisabled');
			}
		});

		// change checkbox for invoice
		if($('#billingInvoice').is(':checked'))
		{
			// enable
			$('#enableWithInvoice').show();
			$('#enableWithInvoice input').attr('disabled', '').removeClass('inputDisabled');
		}
		else
		{
			// disable
			$('#enableWithInvoice').hide();
			$('#enableWithInvoice input').attr('disabled', 'disabled').addClass('inputDisabled');
		}
	},


	// end
	eoo: true
}


jsFrontend.shop.controls =
{
	init: function()
	{
		$('.productDetail .productAmount').live('blur', jsFrontend.shop.controls.checkStock);
		$('.productAdd').live('click', jsFrontend.shop.controls.updateProduct);
		$('.productRemove').live('click', jsFrontend.shop.controls.removeProduct);

		$('.giftAdd').live('click', jsFrontend.shop.controls.updateGift);
		$('.giftRemove').live('click', jsFrontend.shop.controls.removeGift);

		$('#cartOverview .productAmount').live('blur', jsFrontend.shop.controls.updateProduct);
		$('#cartOverview .giftAmount').live('blur', jsFrontend.shop.controls.updateGift);
		$('.cartShippingDestination').bind('change', jsFrontend.shop.controls.updateShipping);
		$('.cartDiscountCode').live('blur', jsFrontend.shop.controls.updateDiscount);
		$('.cartCustomerCode').live('blur', jsFrontend.shop.controls.updateCustomerDiscount);
	},


	checkStock: function(evt)
	{
		// grab data
		var input = $(this);
		var variantId = parseInt(input.data('variant-id'));
		var productId = parseInt(input.data('product-id'));
		var val = parseInt(input.val());

		// make the call
		$.ajax({
			url: '/frontend/ajax.php?module=products&action=check_stock&language=nl',
			data: 'product_id='+ productId +'&variant_id=' + variantId +'&requested='+ val,
			success: function(json, textStatus)
			{
				// reset if needed
				if(!json.data.is_ok)
				{
					// reset to available stock
					input.val(json.data.available);

					// hilight
					input.effect('highlight', {}, 1200);

					// show message
					jsFrontend.messages.add('notice', json.message);
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				// reset
				input.val(1);
			}
		});
	},


	updateCustomerDiscount: function(evt)
	{
		// grab data
		var input = $(this);
		var val = input.val();

		// hide previous error
		$('#customerDiscountError').hide();

		// make the call
		$.ajax({
			url: '/frontend/ajax.php?module=shop&action=update_customer_code&language=nl',
			data: 'code='+ val,
			success: function(json, textStatus)
			{
				// visual feedback
				if(val == 0) {}
				else jsFrontend.messages.add('success', json.message);

				// build the cart
				jsFrontend.shop.cart.buildWidget(json.data);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				$('#customerDiscountError').html($.parseJSON(XMLHttpRequest.responseText).data).show();

				// reset
				input.val('');
			}
		});
	},


	updateDiscount: function(evt)
	{
		// grab data
		var input = $(this);
		var val = input.val();

		// hide previous error
		$('#discountError').hide();

		// make the call
		$.ajax({
			url: '/frontend/ajax.php?module=shop&action=update_discount_code&language=nl',
			data: 'code='+ val,
			success: function(json, textStatus)
			{
				// visual feedback
				if(val == 0) {}
				else jsFrontend.messages.add('success', json.message);

				// build the cart
				jsFrontend.shop.cart.buildWidget(json.data);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				$('#discountError').html($.parseJSON(XMLHttpRequest.responseText).data).show();

				// reset
				input.val('');
			}
		});
	},


	updateGift: function(evt)
	{
		// prevent
		evt.preventDefault();

		// grab data
		var reset = 'false';
		var input = $(this);

		var giftId = parseInt(input.data('gift-id'));
		var val = parseInt($('input[data-gift-id='+ giftId + '].giftAmount').val());
		var name = $('input[data-gift-id='+ giftId + '].giftName').val();
		var email = $('input[data-gift-id='+ giftId + '].giftEmail').val();
		var text = $('textarea[data-gift-id='+ giftId + '].giftText').val();

		// remove previous errors
		$('span[data-gift-id].formError').remove();
		$('p.errorArea').removeClass('errorArea');

		// validate
		var hasError = false;
		if(!utils.form.isFilled($('input[data-gift-id='+ giftId + '].giftName')))
		{
			$('#giftNameArea span.inlineError').remove();
			$('input[data-gift-id='+ giftId + '].giftName').after('<span class="inlineError"><span data-gift-id="'+ giftId +'" class="formError">' + "Gelieve een naam in te geven." + '</span></span>');
			$('input[data-gift-id='+ giftId + '].giftName').parents('p#giftNameArea').addClass('errorArea');
			hasError = true;
		}
		if(!utils.form.isEmail($('input[data-gift-id='+ giftId + '].giftEmail')))
		{
			$('#giftEmailArea span.inlineError').remove();
			$('input[data-gift-id='+ giftId + '].giftEmail').after('<span class="inlineError"><span data-gift-id="'+ giftId +'" class="formError">' + "E-mail is een verplicht veld." + '</span></span>');
			$('input[data-gift-id='+ giftId + '].giftEmail').parents('p#giftEmailArea').addClass('errorArea');
			hasError = true;
		}

		// invalid value!
		if(val == 0 || hasError) return false;

		// if we are on the cart overview we should reset instead of add
		if($('#cartOverview').length > 0) reset = 'true';

		// make the call
		$.ajax({
			url: '/frontend/ajax.php?module=shop&action=update_gift&language=nl',
			data: 'gift_id=' + giftId +'&amount='+ val + '&reset='+ reset + '&remove=false&name='+ name +'&email='+ email + '&text='+ text,
			success: function(json, textStatus)
			{
				// visual feedback
				if(val == 0) {}
				else jsFrontend.messages.add('success', json.message);

				// build the cart
				jsFrontend.shop.cart.buildWidget(json.data.cart);

				// clear
				$('input[data-gift-id='+ giftId + '].giftName').val('');
				$('input[data-gift-id='+ giftId + '].giftEmail').val('');
				$('textarea[data-gift-id='+ giftId + '].giftText').val('');
			},
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				// init var
				textStatus = "Er ging iets mis.";

				// get real message
				if(typeof XMLHttpRequest.responseText != 'undefined') textStatus = $.parseJSON(XMLHttpRequest.responseText).message;

				// add message
				jsFrontend.messages.add('error', textStatus);
			}
		});
	},


	updateProduct: function(evt)
	{
		// prevent
		evt.preventDefault();

		// grab data
		var reset = 'false';
		var input = $(this);

		var variantId = parseInt(input.data('variant-id'));
		var productId = parseInt(input.data('product-id'));
		var val = 0; // parseInt($('input[data-variant-id='+ variantId + ']').val()); // this _should_ work fine, but it does not...
		$('input[data-variant-id]').each(function() { if($(this).data('variant-id') == variantId) val = $(this).val(); }); // this is the ugly fix for above anomaly

		if(val == 0 && $('.collection').length > 0) val = 1;

		// if we are on the cart overview we should reset instead of add
		if($('#cartOverview').length > 0) reset = 'true';

		// make the call
		$.ajax({
			url: '/frontend/ajax.php?module=shop&action=update_product&language=nl',
			data: 'product_id=' + productId +'&variant_id='+ variantId +'&amount='+ val + '&reset='+ reset + '&remove=false',
			success: function(json, textStatus)
			{
				// visual feedback
				jsFrontend.messages.add(json.data.message_type, json.message);

				// this is a notice so something has to change
				if(json.data.message_type == 'notice' && input.hasClass('inputText'))
				{
					// reset to available stock
					input.val(json.data.available);

					// hilight
					input.effect('highlight', {}, 1200);
				}

				// build the cart
				jsFrontend.shop.cart.buildWidget(json.data.cart);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				// init var
				textStatus = "Er ging iets mis.";

				// get real message
				if(typeof XMLHttpRequest.responseText != 'undefined') textStatus = $.parseJSON(XMLHttpRequest.responseText).message;

				// add message
				jsFrontend.messages.add('error', textStatus);
			}
		});
	},


	updateShipping: function(evt)
	{
		// prevent
		evt.preventDefault();

		// grab data
		var input = $(this);
		var val = input.val();

		// make the call
		$.ajax({
			url: '/frontend/ajax.php?module=shop&action=update_shipping&language=nl',
			data: 'id=' + val,
			success: function(json, textStatus)
			{
				// show message
				jsFrontend.messages.add('success', json.message);

				// build the cart
				jsFrontend.shop.cart.buildWidget(json.data);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				// init var
				textStatus = "Er ging iets mis.";

				// get real message
				if(typeof XMLHttpRequest.responseText != 'undefined') textStatus = $.parseJSON(XMLHttpRequest.responseText).message;

				// add message
				jsFrontend.messages.add('error', textStatus);
			}
		});
	},


	removeGift: function(evt)
	{
		// prevent
		evt.preventDefault();

		// grab data
		var input = $(this);
		var giftId = parseInt(input.data('gift-id'));
		var email = input.data('email');
		var val = 0;

		// make the call
		$.ajax({
			url: '/frontend/ajax.php?module=shop&action=update_gift&language=nl',
			data: 'gift_id=' + giftId +'&name=foo&email='+ email +'&amount='+ val + '&reset=true&remove=true',
			success: function(json, textStatus)
			{
				// show message
				jsFrontend.messages.add('success', json.message);

				// visual feedback
				$('#cartGiftRow_'+ giftId + '[data-email='+ email+ ']').fadeOut(1200, function() {
					// remove the HTML
					$(this).remove();

					// are we on the cart?
					if($('#cartOverview').length > 0)
					{
						// no products or gifts? Just reload the page
						if($('.cartProductRow:visible').length == 0 && $('.cartGiftRow:visible').length == 0) window.location.reload();
					}
				});

				// build the cart
				jsFrontend.shop.cart.buildWidget(json.data.cart);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				// init var
				textStatus = "Er ging iets mis.";

				// get real message
				if(typeof XMLHttpRequest.responseText != 'undefined') textStatus = $.parseJSON(XMLHttpRequest.responseText).message;

				// add message
				jsFrontend.messages.add('error', textStatus);
			}
		});
	},


	removeProduct: function(evt) {
		// prevent
		evt.preventDefault();

		// grab data
		var input = $(this);
		var variantId = parseInt(input.data('variant-id'));
		var productId = parseInt(input.data('product-id'));
		var val = 0;

		// make the call
		$.ajax({
			url: '/frontend/ajax.php?module=shop&action=update_product&language=nl',
			data: 'product_id=' + productId + '&variant_id=' + variantId +'&amount=' + val + '&reset=true&remove=true',
			success: function(json, textStatus)
			{
				// show message
				jsFrontend.messages.add('success', json.message);

				// visual feedback
				$('#cartProductRow_' + productId + '_' + variantId).fadeOut(1200, function() {
					// remove the HTML
					$(this).remove();

					// are we on the cart?
					if($('#cartOverview').length > 0)
					{
						// no products or gifts? Just reload the page
						if($('.cartProductRow:visible').length == 0 && $('.cartGiftRow:visible').length == 0) window.location.reload();
					}

				});

				if (json.data.cart.shipping.pickup_only) {
					$('.js-shipping-no-pick-up').addClass('hidden');
					$('.js-shipping-pick-up').removeClass('hidden');
				} else {
					$('.js-shipping-no-pick-up').removeClass('hidden');
					$('.js-shipping-pick-up').addClass('hidden');
				}
				// build the cart
				jsFrontend.shop.cart.buildWidget(json.data.cart);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				// init var
				textStatus = "Er ging iets mis.";

				// get real message
				if(typeof XMLHttpRequest.responseText != 'undefined') textStatus = $.parseJSON(XMLHttpRequest.responseText).message;

				// add message
				jsFrontend.messages.add('error', textStatus);
			}
		});
	},

	// end
	eoo: true
}

$(document).ready(function() { jsFrontend.shop.init(); });
