/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	tx_s2pwsproducts_configurator_main.js
	November 2009 / S2 INTERMEDIA GmbH / Alexander Buch
	$Id$
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		Mootools specific
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
(function(){
	if (typeof(MooTools) == 'undefined') return;
	var $ = document.id;
	//dbug.enable();
	window.addEvent('domready', function() {
		/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	       	Declarations
	       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
			var selectorClass	= 'tx-s2pwsproducts-configurator-product-select';
			var rowClass		= 'tx-s2pwsproducts-configurator-product-row';
			var rows			= $$('.'+rowClass);
			var detailLinkClass	= 'tx-s2pwsproducts-configurator-product-details';
			var sumField		= $('tx-s2pwsproducts-configurator-sum');
			var form			= sumField.getParent('form');
	
		window.addEvent('tx::s2pwsproducts::configurator::dataReady', function(data/* Array */){
		/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	       	Declarations :: Products
	       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
			var products = data.products;
			products.each(function(product) {
				product.getGraduatedPrice = function(amount/* Integer */) {
					amount = amount.toInt();
					var graduatedPrice = null, lowestQuantityPrice = null, highestQuantity = 0;
					for (uid in this.prices) {
						var priceObj = this.prices[uid];
						if (lowestQuantityPrice === null
							|| this.prices[uid].quantity.toInt() < lowestQuantityPrice.quantity.toInt()) {
								lowestQuantityPrice = this.prices[uid];
						}
						
						//console.log(priceObj, priceObj.quantity, amount, this.prices[uid].quantity, highestQuantity);
						
						if (this.prices[uid].quantity.toInt() <= amount
							&& this.prices[uid].quantity.toInt() > highestQuantity) {
								highestQuantity = this.prices[uid].quantity;
								graduatedPrice = this.prices[uid];
						}
					}
					// Clone object as we dont want to reference here
					var priceObj = $merge({}, (graduatedPrice === null) ? lowestQuantityPrice : graduatedPrice);
					if (amount == 0) priceObj.price = 0;
					return priceObj;
				}
			});
			
		/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	       	Declarations :: Licences
	       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
			var licences = data.licences;
			
		/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	       	Declarations :: Mode
	       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
			var mode = data.mode;
			
		/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	       	Declarations :: Crossselling
	       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
			var crossselling = data.crossselling;
			
		/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	       	Declarations :: Functions
	       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
		  	
			/**
			 * Formats a number into a string depending on the given price-object.
			 * 
			 * @param {Float} digit
			 * @param {Object} priceObj
			 */
			var formatPrice = function(digit /* Int */, priceObj /* Object */){
				digit = parseFloat(digit);
				return digit.toFixed(2)
							.replace('.00', '.&#8212;')
							.replace('.', priceObj.currency.cu_decimal_point) +
							' ' +
							priceObj.currency.cu_symbol_left;
			}
			
			/**
			 * Calculates every rows subtotal into a sum, adds licence-costs and
			 * writes the result as formatted string into the sum-field.
			 */
			var refreshSum = function() {
				dbug.log('tx_s2pwsproducts_configurator :: refreshing sum');
				var sum = 0, priceObj = null;
				var form = rows[0].getParent('form');
				var priceObj = form.retrieve('common::priceObj');
				var mainProductRow = rows.filter(function(row) { return row.retrieve('productObj').type == 1; })[0];
				
				rows.each(function(row) {
					if (!row.retrieve('enabled') && row.retrieve('productObj').type != 1) return;
					sum += row.retrieve('subtotal');
					if (row.retrieve('graduatedPrice')
						&& !priceObj) {
						priceObj = row.retrieve('graduatedPrice');
					}
				});
				form.store('sum', sum.toInt());
				form.store('common::priceObj', priceObj);			
				
				refreshLicenceCosts();
				sum += parseFloat(form.retrieve('licence::costs'));
				
				try{
					var requestButton = $$('input[name^="tx_s2pwsproducts_configurator[request]"]')[0];
					requestButton.fade(sum > mainProductRow.retrieve('productObj')['min_request_value'] ? 'in' : 'hide');
				}catch(e){}
				
				if (mode == 'elongation') {
					sum = parseFloat(form.retrieve('licence::costs'));
				}
				
				sumField.set('html', formatPrice(sum, priceObj));
			}
			
			/**
			 * Calculates licence-costs depending on the price and amount of the
			 * mainproduct and writes the result as formatted string in the licence-
			 * costs-field.
			 */
			var refreshLicenceCosts = function() {
				dbug.log('tx_s2pwsproducts_configurator :: refreshing licence costs');
				var licence = licences.filter(function(obj) { return obj.uid == form.retrieve('license::uid') })[0],
					licenceCosts = 0,
					minCosts = parseFloat(licence.min_value);
				
				if (mode == 'elongation' || (licence.firstyear_free != 1 && licence.percentage > 0)) {
					rows.each(function(row) {
						if (!row.retrieve('enabled')) return;
						licenceCosts += row.retrieve('graduatedPrice').price * row.retrieve('amount');
					});
					
					licenceCosts = Math.ceil(licenceCosts * licence.percentage) / 100;
					licenceCosts = licenceCosts * (licence.years || 1);
					if (licenceCosts < minCosts) licenceCosts = minCosts;
				}
				
				/*
				var mainProductRow = rows.filter(function(row) { return row.retrieve('productObj').type == 1; })[0];
				
				var licenceCosts = mainProductRow.retrieve('subtotal') * licence.percentage / 100;
				*/
				form.store('licence::costs', licenceCosts);
				
				$$('.tx-s2pwsproducts-configurator-licence-row td.price')[0].set('html', formatPrice(licenceCosts, form.retrieve('common::priceObj')));
			}
			
		/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	       	Iteration :: Licences
	       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
			$$('input[name="tx_s2pwsproducts_configurator[licence]"]').each(function(el) {
				var form = el.getParent('form');
				var licence = licences.filter(function(obj) { return obj.uid == el.get('value'); })[0];
				el.addEvent('change', function(e) {
					form.store('license::uid', this.value);
					form.getElements('.licence-name-item')[0].set('html', licence.name);
					refreshLicenceCosts();
					refreshSum();
				});
				
				el.addEvent('click', function(e) {
					el.fireEvent('change', e);
				});
				
				if (el.get('checked')) el.getParent('form').store('license::uid', el.value);
			});
			
		/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	       	Iteration :: Product-Checkboxes
	       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
			$$('.'+selectorClass).each(function(el) {
				var productId = el.get('id').replace(selectorClass+'-', '');
				var row = $(rowClass+'-'+productId);
				var nameRow = $('tx-s2pwsproducts-configurator-product-name-row-'+productId);
				//var productObj = products.filter(function(obj) { return obj.uid == productId; })[0];
				el.addEvent('change', function(e) {
					nameRow.setStyle('display', (el.checked ? '' : 'none'));
					row.setStyle('display', (el.checked ? '' : 'none'));
					row.store('enabled', el.checked);
					row.retrieve('input').value = (el.checked ? 1 : 0);
					row.retrieve('input').refreshSubTotal();
					refreshSum();
				});
				
				el.addEvent('click', function(e) {
					el.fireEvent('change', e);
				});
				
	//			el.fireEvent('change', {});
				
				row.store('enabled', el.checked);
			});
			
		/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	       	Iteration :: Product-Rows
	       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
			rows.each(function(row) {
				var productId = row.get('id').replace(rowClass+'-', '');
				var productObj = products.filter(function(obj) { return obj.uid == productId })[0];
				row.store('productObj', productObj);
				row.store('productId', productId);
			});
			
			rows.each(function(row) {
				var input = row.getElement('input[name^="tx_s2pwsproducts_configurator[cart][products]"][type=text]');
				var subtotalField = row.getLast('.price');
				var productId = row.retrieve('productId');
				var productObj = row.retrieve('productObj');
				var productNameSpan = row.getElement('.product-name');
				
				var mainProductRow = rows.filter(function(row) { return row.retrieve('productObj').type == 1; })[0];
				var mainProductUid = mainProductRow.retrieve('productObj').uid;
				
				row.store('input', input);
				row.store('subtotalField', subtotalField);
				
				// Main-Products (Type 1 = Program) always enabled
				if (productObj.type == 1) row.store('enabled', true);
				
				input.refreshSubTotal = function() {
					var mainProductAmount = $$('.tx-s2pwsproducts-configurator-mainproduct-row')[0]
											.retrieve('input').value.toInt();
											
					if (productObj.type == 3 /* Plug-In */
						&& this.value.toInt() < mainProductAmount
						&& !this.retrieve('focus')) {
							this.value = mainProductAmount;
					}
					
					var graduatedPrice /* Object */ = productObj.getGraduatedPrice(this.value);
					var subtotal = parseFloat(this.value) * parseFloat(graduatedPrice.price);
					
					var discount = 0;
					//if (productObj.discount) discount = productObj.discount;
					
					row.getElements('.graduated-price')[0].set('html', formatPrice(graduatedPrice.price, graduatedPrice));
					
					var now = new String($time()).substring(0, 10).toInt();
					
					if (Boolean(productObj.discount.toInt())) {
						discount = productObj.discount;
						if ((Boolean(productObj.discount_starttime.toInt()) && productObj.discount_starttime.toInt() > now)
							|| (Boolean(productObj.discount_endtime.toInt()) && productObj.discount_endtime.toInt() < now)) {
								discount = 0;
						}
					}
					
					var crosssellingObj = crossselling.filter(function(obj) { return (obj.product_2 == productObj.uid && obj.product_1 == mainProductUid);})[0];
					
					if (crosssellingObj && Boolean(crosssellingObj.discount.toInt())) {
						if ((Boolean(crosssellingObj.discount_starttime.toInt()) && crosssellingObj.discount_starttime.toInt() > now)
							|| (Boolean(crosssellingObj.discount_endtime.toInt()) && crosssellingObj.discount_endtime.toInt() < now)) {
						} else {
							discount = crosssellingObj.discount;
						}
					}
					
					subtotal -= subtotal*discount/100;
					
					try {
						row.getElements('.reduced-price')[0].set('html', formatPrice(graduatedPrice.price-graduatedPrice.price*discount/100, graduatedPrice));
					} catch (e){}
					
					row.store('subtotal', subtotal);
					row.store('graduatedPrice', graduatedPrice);
					row.store('amount', this.value);
					subtotalField.set('html', formatPrice(subtotal, graduatedPrice));
				};
				
				input.addEvents({
					'keyup': function(e){
						if (isNaN(e.key)) this.value = this.value.replace(/\D/g, '');
						//if (this.value == '') this.value = 1;
						if (this.value == '') return;
						
						if (productObj.type == 1) { // Type: Program
							rows.each(function(tempRow){
								if (!row.retrieve('enabled')) return;
								if (tempRow.retrieve('productObj')['type'] == 3) {
									var tempInput = tempRow.retrieve('input');
									if (tempInput.value.toInt() < input.value.toInt()) {
										tempInput.value = input.value;
										tempInput.fireEvent('keyup', e);
									}
								}
							});
						}
						
						this.refreshSubTotal();
						refreshSum();
					},
					
					'blur': function(e) {
						if (this.value == '' || this.value == 0) {
							switch (mode) {
								case 'signed-customer':
									this.value = 0;
									break;
								default:
									this.value = 1;
									break;
							}
						}
						
						this.store('focus', false);
						this.refreshSubTotal();
						refreshSum();
					},
					
					'focus': function(e) {
						this.store('focus', true);
					}/*,
					'click': function(e) {
						this.select();
					}*/
				});
				
				
				input.refreshSubTotal();
				
				
				
				/*
				var stickyWin = new StickyWin({
					content: StickyWin.ui.pointy('asd', {
						direction: 11
					}),
					position: 'lowerLeft',
					relativeTo: productNameSpan,
					offset: {
						y: 20
					}
				});
				stickyWin.hide();
				
				productNameSpan.addEvents({
					'click': function(e){
						$$('.StickyWinInstance').each(function(win){
							win.retrieve('StickyWin').hide();
						});
						stickyWin.show();
					},
					'mouseenter': function(e) {
						$$('body')[0].setStyle('cursor', 'pointer');
					},
					'mouseleave': function(e) {
						$$('body')[0].setStyle('cursor', '');
					}
				});
				*/
				
				
			});
			
		/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	       	Iteration :: Product-Details
	       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
			$$('.'+detailLinkClass).each(function(el) {
				var product = products.filter(function(obj) { return obj.uid == el.get('rel') })[0];
				var stickyWin = new StickyWin({
					content: StickyWin.ui.pointy(product.shortdescription, {
						direction: 1
					}),
					position: 'lowerLeft',
					relativeTo: el,
					offset: {
						x: -250,
						y: 20
					}
				});
				stickyWin.hide();
				el.addEvent('click', function(e) {
					var e = new Event(e).stop();
					$$('.StickyWinInstance').each(function(win) {
						win.retrieve('StickyWin').hide();
					});
					stickyWin.show();
				});
			});
			
		/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	       	Validation
	       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
		form.addEvent('submit', function(e) {
			var error = false;
			if ($('tx_s2pwsproducts_configurator_licence_id')) {
				var licenceIdField = $('tx_s2pwsproducts_configurator_licence_id');
				var licenceIdFieldValue = licenceIdField.get('value');
				if (!licenceIdFieldValue || /\D/.test(licenceIdFieldValue)) {
					error = true;
					licenceIdField.addClass('tx_s2pwsproducts_configurator_error');
				} else {
					licenceIdField.removeClass('tx_s2pwsproducts_configurator_error');
				}
			}
			
			if (error) {
				var e = new Event(e).stop();
			}
		});
			
			
		/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	       	Initialize
	       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
			refreshSum();
			$$('.'+selectorClass+', input[name="tx_s2pwsproducts_configurator[licence]"]').each(function(el) {
				if (el.checked) el.fireEvent('change', {});
			});
		});
		
	});
	
})();

