var showProductPopup = null;
var reloadMiniBasket = null;
(function($){
	/* start filter for product/variations */
	var loc = window.location;
	var ajaxUrl = loc.protocol+'//'+loc.host+'/index.php?type=6667';
	var productHandlerUrl = loc.protocol+'//'+loc.host+'/index.php?type=6668';
	var prices = null;
	
	var checkAllFilterSelected = function(filter){
		var allSelected = true;
		var selects = $(filter).find('select');
		if(selects.size() > 0){
			$(selects).find('option:selected').each(function(index,el){
				if($(el).val() == "")
				{
					allSelected = false;
				}
			});
		}
	return allSelected;
	}

	var getFilterData = function(filter)
	{		
		var data = {}
		var productField = $(filter).find('input[name*=product_id]');
		data[$(productField).attr('name')] = $(productField).val();
		var filterSelects = $(filter).find('select');
		if(filterSelects.size() >0){
			$.each(filterSelects,function(index,el){
				data[$(el).attr('name')] = $(el).find('option:selected').val();
			});
		}
	return data;
	}

	var initFilter = function(filter){
		var wrapper = $(filter).parents('.variation-filter-wrapper:first');
		var filterSelects = $(filter).find('select');		
		filterSelects.bind('change',function(){
			var allSelected = checkAllFilterSelected(filter);
			var filterData = getFilterData(filter);
			filterData['tx_nfcshop_pi1[a]']='fpv';			
			if(allSelected){
				$.ajax({
					url:ajaxUrl,
					type: 'POST',
					dataType: 'json',
					data: filterData,
					success: function(data) {
						if(data && data.state == 1)
						{
							if(data.payload)
							{
								if(data.payload.variationUid && data.payload.variationUid > 0)
								{
									$(filter).find('input[name*=variation_id]').val(data.payload.variationUid);
									if(data.payload.prices)
									{
										prices = data.payload.prices;
									}
								}								
							}
							checkDependencies(wrapper);
						}
						else
						{
							$(filter).find('input[name*=variation_id]').val('');
							checkDependencies(wrapper);
							alert('Die gewählte Variante ist im Moment nicht verfügbar');
						}						
					}
				});
			}
			else
			{
				$(filter).find('input[name*=variation_id]').val('');
				checkDependencies(wrapper);
			}
		});
	}

	var checkDependencies = function(wrapper)
	{
		var success = false;
		var filters = $(wrapper).find('.variation-filter').each(function(index,el){
			var variationSelected = $(el).find('input[name*=variation_id]').val();
			var quantity = $(el).find('select[name*=quantity]').val();
			var productId =$(el).find('input[name*=product_id]').val();
			variationSelected = variationSelected == "" ? 0 : parseInt(variationSelected);
			quantity = quantity == "" ? 0 : parseInt(quantity);
			productId = productId == "" ? 0 : parseInt(productId);
			if(quantity > 0)
			{
				success = variationSelected > 0 ? true :false;
			}
		});

		$(wrapper).find('.addToShoppingCartButton').unbind('click');
		//everything ok
		if(success)
		{
			$(wrapper).find('.addToShoppingCartButton').bind('click', addPreparedProductsToCart);
			$(wrapper).find('.addToShoppingCartButton').css('display', 'block');
			$(wrapper).find('.addToShoppingCartButtonInaktiv').css('display', 'none');
		}
		else
		{
			$(wrapper).find('.addToShoppingCartButton').css('display', 'none');
			$(wrapper).find('.addToShoppingCartButtonInaktiv').css('display', 'block');
		}
		recalculate(wrapper);
	return success;
	}
	
	var addPreparedProductsToCart = function()
	{
		var wrapper = $(this).parents('.variation-filter-wrapper:first');
		var filter = $(wrapper).find('.variation-filter');
		var filterSize = $(filter).size();
		if(filterSize > 0)
		{
			var requestData = {
				'tx_nfcshop_pi1[items]':[],
				'tx_nfcshop_pi1[noredirect]': 1,
				'tx_nfcshop_pi1[action]':'add',
				'tx_nfcshop_pi1[ajaxcall]':1
			};
			$.each(filter,function(index,el){
					var itemData = getCredentialsFromFilterForOrdering(el);
					if(itemData){						
						requestData['tx_nfcshop_pi1[items]'].push(itemData);											 
					}					
			});
			if(requestData['tx_nfcshop_pi1[items]'].length > 0)
			{
				$.ajax({
					url:productHandlerUrl,
					type: 'POST',
					dataType: 'json',
					data: requestData,
					success: function(data) {						
						if(data.state == 1 && data.shoppingcarturl)
						{
							closePopUp();
							reloadMiniBasket();
							if(data.payload.content)
							{								
								openPopUp(data.payload.content);
							}
							else
							{
							 window.location=data.shoppingcarturl;
							}
						}
					}
				});
			}
		}
	}

	var getCredentialsFromFilterForOrdering=function(filter)
	{
		filter = $(filter);
		if(filter){
			var result = {};
			var productId = $(filter).find('input[name*=product_id]').val();
			var variationId = $(filter).find('input[name*=variation_id]').val();
			var quantity = $(filter).find('select[name*=quantity]').val();
			productId == "" ? 0 : parseInt(productId);
			variationId == "" ? 0 : parseInt(variationId);
			quantity == "" ? 0 : parseInt(quantity);
			if(productId == 0 || variationId == 0 || quantity == 0 ) return false;
			result['product_id'] = productId;
			result['variation_id'] = variationId;
			result['quantity'] = quantity;
		return result;
		}
	return false;
	}

	var recalculate = function(wrapper)
	{
		//prices will only be set if ajax call was successfully
		if(prices){
			var priceField = $(wrapper).find('.variation-price-single:first');
			var priceFieldTotal = $(wrapper).find('.variation-price-total:first');
			var quantity = 0;
			$(wrapper).find('select[name*=quantity]').each(function(index,el){
				var selectQuantity = $(el).val() == "" ? 0 : parseInt($(el).val());
				quantity += selectQuantity;
			});
			var price = prices[1];
			$.each(prices,function(index,el){
				if(quantity>=index){
					price = prices[index];
				}
			});
			price = new Number(price).toFixed(2);
			$(priceField).text(price);
			var priceTotal = price * quantity;
			priceTotal = new Number(priceTotal).toFixed(2);
			$(priceFieldTotal).text(priceTotal);
		}
	}
	/* function needed to init after ajax etc... */
	var initFilterByWrapper = function(filterWrapper)
	{
		filterWrapper = $(filterWrapper);
		if(filterWrapper){
				var filter = filterWrapper.find('.variation-filter');
				var filterCount = filter.size();
				if(filterCount > 0)
				{
					$.each(filter,function(index,el){
						initFilter(el);
					});
				}
				checkDependencies(filterWrapper);
		}
	}
	/* end filter for product/variations */

	/* start popup */
	showProductPopup = function(productId)
	{
		productId = parseInt(productId);
		if(productId > 0)
		{
				var requestData = {
					'tx_nfcshop_pi1[a]':'gpop',
					'tx_nfcshop_pi1[product_id]':productId
				};
				$.ajax({
					url:ajaxUrl,
					type: 'POST',
					dataType: 'json',
					data: requestData,
					success: function(data) {						
						if(data.state == 1 && data.payload)
						{
							openPopUp(data.payload)
							var filterWrapper = $('#'+popupid).find('.variation-filter-wrapper:first');
							initFilterByWrapper(filterWrapper);
						}
					}
				});
		}		
	}
	/* end popup */

	/* start reload cart*/
	reloadMiniBasket = function()
	{
			var requestData = {
					'tx_nfcshop_pi1[a]':'rmb'					
			};
			$.ajax({
				url:ajaxUrl,
				type: 'POST',
				dataType: 'json',
				data: requestData,
				success: function(data) {
					if(data.state == 1 && data.payload)
					{
							$('#shopping-cart').empty().append(data.payload);
					}
				}
			});
	}
	/* end reload cart*/

	/* handle document ready */
	$(document).ready(function(){
		/* filter */
		var filterWrapper = $('.variation-filter-wrapper:first')
		initFilterByWrapper(filterWrapper);	
		/* end filter */
		/* popup */
		$('.product-box.openpopup a').bind('click',function(ev){
			ev.preventDefault();
		});
		$('.product-box.openpopup').bind('click',function(){		
				var link = $(this).find('a:first').attr('href');
				var productId = link.match(/\d+\.html/g);
				if(productId.length > 0)
				{
					productId = parseInt(productId[0].slice(0,-5));
					if(productId > 0)
					{
						showProductPopup(productId);
					}
				}			
		});
		/* end popup */
	});
})(jQuery);


