/*
* @Copyright (c) 2010 Ricardo Andrietta Mendes - eng.rmendes@gmail.com
* 
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
* 
* How to use it:
* var formated_value = $().number_format(final_value);
* 
* Advanced:
* var formated_value = $().number_format(final_value, 
* 													{
* 													numberOfDecimals:3,
* 													decimalSeparator: '.',
* 													thousandSeparator: ',',
* 													symbol: 'R$'
* 													});
*/
jQuery.fn.extend({ 
	number_format: function(numero, params)
		{ 
		var sDefaults = 
			{			
			numberOfDecimals: 2,
			decimalSeparator: ',',
			thousandSeparator: '.',
			symbol: ''
			}
 
		var options = jQuery.extend(sDefaults, params);
		var number = numero; 
		var decimals = options.numberOfDecimals;
		var dec_point = options.decimalSeparator;
		var thousands_sep = options.thousandSeparator;
		var currencySymbol = options.symbol;
		
		var exponent = "";
		var numberstr = number.toString ();
		var eindex = numberstr.indexOf ("e");
		if (eindex > -1)
		{
		exponent = numberstr.substring (eindex);
		number = parseFloat (numberstr.substring (0, eindex));
		}
		
		if (decimals != null)
		{
		var temp = Math.pow (10, decimals);
		number = Math.round (number * temp) / temp;
		}
		var sign = number < 0 ? "-" : "";
		var integer = (number > 0 ? 
		  Math.floor (number) : Math.abs (Math.ceil (number))).toString ();
		
		var fractional = number.toString ().substring (integer.length + sign.length);
		dec_point = dec_point != null ? dec_point : ".";
		fractional = decimals != null && decimals > 0 || fractional.length > 1 ? 
				   (dec_point + fractional.substring (1)) : "";
		if (decimals != null && decimals > 0)
		{
		for (i = fractional.length - 1, z = decimals; i < z; ++i)
		  fractional += "0";
		}
		
		thousands_sep = (thousands_sep != dec_point || fractional.length == 0) ? 
					  thousands_sep : null;
		if (thousands_sep != null && thousands_sep != "")
		{
		for (i = integer.length - 3; i > 0; i -= 3)
		  integer = integer.substring (0 , i) + thousands_sep + integer.substring (i);
		}
		
		if (options.symbol == '')
		{
		return sign + integer + fractional + exponent;
		}
		else
		{
		return currencySymbol + ' ' + sign + integer + fractional + exponent;
		}
	}
});

var showProductPopup = null;
var reloadMiniBasket = null;
var recalculateProductView = null;
(function($){
	/* start filter for product/variations */
	var config = {
		'autosetAvailableStock':1
	};
	if(typeof(nfcShopConfig) == 'object')
	{
		config = $.extend(config,nfcShopConfig);
	}
	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 getAjaxUrl = function()
	{				
		return ajaxUrl+getLanguageAndPageQuery();
	}
	
	var getProductHandlerUrl = function()
	{
		return productHandlerUrl+getLanguageAndPageQuery();
	}
	
	var getLanguageAndPageQuery = function()
	{
		var query = '';
		var langParam = parseInt($('#cds-lang').text());
		var pageParam = parseInt($('#cds-id').text());
		if(langParam > 0)
		{
			query+='&L='+langParam;
		}
		if(pageParam > 0)
		{
			query+='&id='+pageParam;
		}
	return query;
	}
	
	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 productWrapper = $(wrapper).parents('.product-data-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:getAjaxUrl(),
					type: 'POST',
					dataType: 'json',
					data: filterData,
					success: function(data) {
						if(config.handleFPVResult && typeof(config.handleFPVResult) =='function')
						{
							config.handleFPVResult(data,filter);
						}
						else
						{
							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);
										$(productWrapper).trigger('variationSelected',{'payload':data.payload});
										$(filter).find('input[name*=variation_id]').trigger('change');
										if(data.payload.prices)
										{
											prices = data.payload.prices;
										}
									}																
									if(data.payload.availableStock && data.payload.stockLowerThanQuantity && config.autosetAvailableStock)
									{
										var availableStockCount = parseInt(data.payload.availableStock);
										$(filter).find('select[name*=quantity]').val(availableStockCount);
										$(filter).find('select[name*=quantity]').trigger('change');
									}							
									if(data.payload.content)
									{
										openPopUp(data.payload.content);
									}								
								}
								checkDependencies(wrapper);
							}
							else
							{
								$(filter).find('input[name*=variation_id]').val('');
								$(filter).find('input[name*=variation_id]').trigger('change');
								if(data.payload && data.payload.content)
								{								
										openPopUp(data.payload.content);
								}
								checkDependencies(wrapper);
							}	
						}
					}
				});
			}
			else
			{
				$(filter).find('input[name*=variation_id]').val('');
				$(filter).find('input[name*=variation_id]').trigger('change');
				checkDependencies(wrapper);
			}
		});		
		$(filter).find('select[name*=quantity]').trigger('change');
	}

	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){	
						$(wrapper).trigger('itemDataBeforeSend',itemData);
						requestData['tx_nfcshop_pi1[items]'].push(itemData);											 
					}					
			});
			if(requestData['tx_nfcshop_pi1[items]'].length > 0)
			{
				$.ajax({
					url:getProductHandlerUrl(),
					type: 'POST',
					dataType: 'json',
					data: requestData,
					success: function(data) {	
						if(config.handleAddProductResult && typeof(config.handleAddProductResult) =='function')
						{
							config.handleAddProductResult(data);
						}
						else
						{
							if(data.state == 1 && data.shoppingcarturl)
							{
								//closePopUp();
								reloadMiniBasket();
								if(data.payload.content)
								{								
									openPopUp(data.payload.content);
								}
								else
								{
								 window.location=data.shoppingcarturl;
								}
							}
							//error popup
							if(data.state == 0 && data.payload.content)
							{
								//closePopUp();
								reloadMiniBasket();
								if(data.payload.content)
								{								
									openPopUp(data.payload.content);
								}
							}	
						}						
					}
				});
			}
		}
	}

	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;
	}
	
	recalculateProductView = function(){
		$('.variation-filter-wrapper').each(function(index,el){
			var wrapper = $(el);
			recalculate(wrapper);
		});		
	};
	
	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);
			$(wrapper).trigger('afterCalculated',
				{
					'wrapper':wrapper,
					'totalPriceField':priceFieldTotal,
					'totalPrice':priceTotal,
					'singlePriceField':priceField,
					'singlePrice':price,
					'quantity':quantity
				});
		}
	}
	/* function needed to init after ajax etc... */
	var initFilterByWrapper = function(filterWrapper)
	{
		filterWrapper = $(filterWrapper);
		if(filterWrapper){				
				$(filterWrapper).bind('afterCalculated',handleOptionAddPrice);
				$(filterWrapper).bind('itemDataBeforeSend',addOptionsToRequest);
				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:getAjaxUrl(),
					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:getAjaxUrl(),
				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 options */
	var handleOptionAddPrice = function()
	{		
		var data = arguments[1];
		var addition = new Number(0.00);
		var wrapper = $(this).parents('.product-data-wrapper:first');
		if(wrapper.size() >0)
		{
			$(wrapper).find('.product-option-wrapper select').each(function(index,el){
				var selectedOption = $(el).find('option:selected');	
				if(selectedOption)
				{
					var addPrice = new Number($(selectedOption).attr('data-addprice'));					
					if(addPrice.toString() != 'NaN')
					{
						addition += addPrice;						
					}
				}		
			});
		}		
		var singlePrice = new Number(data.singlePrice)+addition;						
		var total = singlePrice * data.quantity;		
		//output
		singlePrice = $().number_format(singlePrice);
		$(data.singlePriceField).text(singlePrice);
		total = $().number_format(total);				
		$(data.totalPriceField).text(total);
	}
	
	var addOptionsToRequest = function()
	{
		var data = arguments[1];
		data.options = [];
		var wrapper = $(this).parents('.product-data-wrapper:first');
		if(wrapper.size() >0)
		{
			$(wrapper).find('.product-option-wrapper select').each(function(index,el){
				var selectedOption = $(el).find('option:selected').val();	
				data.options.push(selectedOption);
			});				
		}
	}	

	/* handle document ready */
	$(document).ready(function(){
		/* filter */
		var filterWrapper = $('.variation-filter-wrapper');
		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+\./g);	
		if(productId.length > 0)
		{
			productId = parseInt(productId[0].slice(0,-1));
			if(productId > 0)
			{
				showProductPopup(productId);
			}
		}			
	});
	/* end popup */
	
	$('.product-option-wrapper select').live('change',function(){
				recalculateProductView();		 
	});
			
	/* template tags */
	if($('.reloadminibasket').size() > 0)
	{
		reloadMiniBasket();
	}
	});
})(jQuery);


