/*
	Class: Product
		Performs different action to the product.
		
	Usage:
		For instant, use to manage product variation
		
	Parameters:
		targetProduct - Product target (the product container)
		targetPrice - Product price target 
		targetVariation - Product variations target (all)
		separator - The char who separe thousand 
		formatPrice - Choose if the price must be formated // 0 : no format price (ex:1200) / 1 : format (ex:1'200.00)
		
	Exemple:
	
	About:
		product.js v.1.0 for mootools v1.1 05 / 2007
		
		by Floor SA (http://www.floor.ch) MIT-style license
		
		last modified by Denis Schneiter 18.09.2007
*/
var Product = new Class({
	Implements: [Events, Options],		
	
	options : {
		targetProduct : '.product',		// Product target (the product container)
		targetPrice : '.price',			// Product price target 
		targetVariation : '.prdvars',		// Product variations target (all)
		separator : "'",					// The char who separe thousand 
		formatPrice : '1'					// 0 : no format price (ex:1200) / 1 : format (ex:1'200.00)
	},

    /*
	Constructor: initialize
		Constructor
	
		Get the product price and add Event into some product variations (whit the variation price)
	*/
	
	initialize : function(options) {
		this.setOptions(options)
		
		this.initVarBox();
		
		this.plusminus();
		
		$(document.body).getElements(this.options.targetProduct).each(function(el){
			this._getPrdInfos(el);
			this._getVariation(el);
			//this._getBasket(el);
		}, this);
		
		this._calculatePrice(this.options.targetProduct);

	},
	
	initVarBox : function(){
		$(document.body).getElements('.modify').each(function(btn) {
			btn.addEvent('click', function() {
				if (btn.hasClass('opened')) {
					btn.getParent().getNext().show();
					btn.removeClass('opened').addClass('closed');
				} else {
					btn.getParent().getNext().hide();
					btn.removeClass('closed').addClass('opened');
				}						  
			})	
		});
	},
	
	/*
	Function: _getPrdInfos
		Internal method
		
		get the product ID and the product categoryID
		get the product price.
		the product price must be found into a title (ex: <span title="1200">
		
		Parameters:
			prd - html element
	*/
	_getPrdInfos : function(prd) {
		// Get product ID
		this.prdID = prd.id.replace(/^item/, '');
		// Get the product price 
		this.els = prd.getElements(this.options.targetPrice );
		this.els.each(function(el){				
			this.price = el.title;
			this.newprice = this.price;
			this.elprice = el;
		}, this);	
	},
	/*
	Function: _getVariation
		Internal method
		
		get all variations and his price supplement for the product.
		add Event to change variations
		
		Parameters:
			prd - html element
	*/
	_getVariation : function(prd) {
		var that = this;
		that.els = $(document.body).getElements(that.options.targetVariation, prd);
		that.els.each(function(el){
			if ($(el).type == 'text') {
				$(el).addEvents({
					'keyup': function(){
						that._calculatePrice(prd);
					}
				});
			}
			else {
				$(el).addEvents({
					'click': function(){
						that._calculatePrice(prd);
					}
				});
			}
		});
	},
	/*
	Function: _getBasket
		Internal method
		
		get all variations and his price supplement for the product.
		add Event to change variations
		
		Parameters:
			prd - html element
	*/
	_getBasket : function(prd) {;
		this.els = prd.getElements('.add');
		this.els.each(function(el){
			$(el).addEvent('click', function(e){
				this.basket.add(this.prdID,this.newprice);
			}.bind(this));
							
		}, this);
	},
	/*
	Function: _calculatePrice
		Internal method
		
		Change the product price according to the variation price
		
		Parameters:
			variationPrice - supplement price 
	*/
	_calculatePrice : function(prd){
		var variationPrice = 0;
		
		var removeSeparator = new RegExp(this.options.separator);
		
		if (this.price) {
			this.newprice = this.price.replace(removeSeparator, '').toFloat(); // clear thousand separator and change string to int 
	
			this.els = $(document.body).getElements(this.options.targetVariation, prd);
			this.els.each(function(el){
				if (el.type == 'text') {
					var parentfaktor = 0;
					if (el.id.match(/\d+\-\d+/))	{
						var parentid = /\d+\-(\d+)/.exec(el.id)[1];
						if ($('input'+parentid) && $('input'+parentid).name.match(/^qty/) && $('input'+parentid).value.toFloat() >= 0){
							parentfaktor = $('input'+parentid).value.toFloat();
						}
					}
					var difprice = el.alt;
					
					if (difprice.match(/\d+\-\d+\.\d{2}/))	{
						difprice = difprice.replace(/::$/,'');
						var difprices = difprice.split('::');
						for (var i=0; i<difprices.length; i++)	{
							var pricedef = difprices[i].split('-');
							if (el.value.toInt() >= pricedef[0].toInt())	{
								difprice = pricedef[1];
							}
							else	{
								break;
							}
						}
					}
					if ($('price' + el.id.replace(/input/, ''))) {
						if (!difprice.match(/\d+\-\d+\.\d{2}/))
							$('price' + el.id.replace(/input/, '')).set('html', difprice.toFloat().toFixed(2) + (($('priceqty' + el.id.replace(/input/, '')).get('alt')) ? '/' + $('priceqty' + el.id.replace(/input/, '')).get('alt') : ''));
					}
					if ($('priceqty' + el.id.replace(/input/, ''))) {
						$('priceqty' + el.id.replace(/input/, ''))
							.set('html', ((parentfaktor > 0) ? parentfaktor + 'x' : '') + el.value + (($('priceqty' + el.id.replace(/input/, '')).get('alt')) ? $('priceqty' + el.id.replace(/input/, '')).get('alt')+' &agrave;' : 'x'));
					}
					if (parentfaktor == 0)
						parentfaktor = 1;
					if ($('pricetotal'+el.id.replace(/input/,'')))
						$('pricetotal'+el.id.replace(/input/,'')).set('html',(((el.value) ? el.value.toInt() : 0) * ((difprice) ? difprice.toFloat() : 0) * parentfaktor).toFixed(2));
					variationPrice = variationPrice + ((el.value) ? el.value.toInt() : 0) * ((difprice) ? difprice.toFloat() : 0) * parentfaktor;
				}
				else {
					if (el.checked == true && el.alt) {
						variationPrice = variationPrice + el.alt.toInt();
					}
				}
			}, this);
			
			this.newprice = this.newprice + variationPrice;
	
			this.elprice.innerHTML = this._formatPrice(this.newprice);  //inject new price
	
			this.tva = this.newprice * 7.6 / 100;
			
			this.tva = (this.tva*20).round()/20;
			
			$(document.body).getElement('.total .tva').innerHTML = this._formatPrice(this.tva);
			this.pricetva = this.newprice + this.tva;
			$(document.body).getElement('.total .pricetva').innerHTML = this._formatPrice(this.pricetva);
		}
	},
	
	/*
	Function: _formatPrice
		Internal method
		
		Add thousand separator and cent
		
	*/
	_formatPrice : function(price) {
		price = (price).round(2)  
		
		var newformat = "" + price;	
		var newprice = price;
		
		// manage thousand separator
		
		var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})');
		while(sRegExp.test(newformat)) {
			newformat = newformat.replace(sRegExp, "$1"+this.options.separator+"$2");
		}
		
		// manage decimal 
		
		if (price.toFloat() == price.toInt()) {		
			return newformat + ".00";
		} else if ((price*10).toFloat() == (price*10).toInt()) {	
			return newformat + "0";
		} else {
			return newformat;
		}
	},
	
	/*
	Function: _plusminus
		public method
		
		manage plus-minus box
		
	*/
	plusminus : function() {
		var plus = $$('.plus');
		plus.forEach(function(el){
			el.addEvent('click', function() {
				var el_ID = el.id.replace(/^p_/, '');
				$('input'+el_ID).value = $('input'+el_ID).value.toInt() + 1;
				$('input'+el_ID).fireEvent('keyup');
			});
		});
		
		var minus = $$('.minus');
		minus.forEach(function(el){
			el.addEvent('click', function(){
				var el_ID = el.id.replace(/^m_/, '');						  
				if ($('input'+el_ID).value > 0){
					$('input'+el_ID).value = $('input'+el_ID).value.toInt() - 1;
					$('input'+el_ID).fireEvent('keyup');
				}
			});
		});	
	},
});


window.addEvent('domready',function() {
	var product = new Product();
	
	/* scrollspy instance */
	var ss = new ScrollSpy({
		min: 330,
		onEnter: function(position,enters) {
			//if(console) { console.log('Entered [' + enters + '] at: ' + position.x + ' / ' + position.y); }
			$('order').setStyles({
				position: 'fixed',
				top: '30px'
				
			});
		},
		onLeave: function(position,leaves) {
			//if(console) { console.log('Left [' + leaves + '] at: ' + position.x + ' / ' + position.y); }
			$('order').setStyle('position', '');
		},
		onTick: function(position,state,enters,leaves) {
			//if(console) { console.log('Tick  [' + enters + ', ' + leaves + '] at: ' + position.x + ' / ' + position.y); }
		},
		container: window
	});

	
});


/* scroll spy plugin / class */
		var ScrollSpy = new Class({
			
			/* implements */
			Implements: [Options,Events],
		
			/* options */
			options: {
				min: 0,
				mode: 'vertical',
				max: 0,
				container: window,
				onEnter: $empty,
				onLeave: $empty,
				onTick: $empty
			},
			
			/* initialization */
			initialize: function(options) {
				/* set options */
				this.setOptions(options);
				this.container = $(this.options.container);
				this.enters = this.leaves = 0;
				this.max = this.options.max;
				
				/* fix max */
				if(this.max == 0) 
				{ 
					var ss = this.container.getScrollSize();
					this.max = this.options.mode == 'vertical' ? ss.y : ss.x;
				}
				/* make it happen */
				this.addListener();
			},
			
			/* a method that does whatever you want */
			addListener: function() {
				/* state trackers */
				this.inside = false;
				this.container.addEvent('scroll',function() {
					/* if it has reached the level */
					var position = this.container.getScroll();
					var xy = this.options.mode == 'vertical' ? position.y : position.x;
					/* if we reach the minimum and are still below the max... */
					if(xy >= this.options.min && xy <= this.max) {
							/* trigger Enter event if necessary */
							if(!this.inside) {
								/* record as inside */
								this.inside = true;
								this.enters++;
								/* fire enter event */
								this.fireEvent('enter',[position,this.enters]);
							}
							/* trigger the "tick", always */
							this.fireEvent('tick',[position,this.inside,this.enters,this.leaves]);
					}
					else {
						/* trigger leave */
						if(this.inside) 
						{
							this.inside = false;
							this.leaves++;
							this.fireEvent('leave',[position,this.leaves]);
						}
					}
				}.bind(this));
			}
		});

