if(!Coursorama) { var Coursorama = {}; }

/************************************
 *          MessageBox             *
 ************************************/
Coursorama.MessageBox = Class.create({
    
    initialize: function(element, options) {
		this.target = element;
		$(this.target).hide();
		if (!$("notification_box").empty()) { this.blindDown(element).bind(this);}
    },
    
    blindDown : function(e) {
    	 new Effect.BlindDown(this.target, { duration: 0.5  });
    	 new PeriodicalExecuter(this.blingUp.bind(this), 4);
    },
    
    blingUp : function(e) {
   	 	new Effect.BlindUp(this.target, { duration: 0.5 , afterFinish: this.blingUp.bind(this) });
   }
});

Coursorama.Slideshow = Class.create({
	
	selectors: {
    	'selected' : 'selected',
    	'points' : 'slidePoint',
    	'pointsSelected' : 'currentSelected'
	},
	
    initialize: function(element, options) {
		this.slideshowWrapper = $(element);
		$(element).select('li').each(function(item) {
			item.hide();
		});
		this.initSlider();
		this.initController();
		this.runAnimation();
		this.observeInterrupt();
    },
    
    initSlider : function(e) {
    	//Show the first slide on init
    	this.slideshowWrapper.down('li').show();
    	this.slideshowWrapper.down('li').addClassName(this.selectors.selected);
		this.currentSlide = this.slideshowWrapper.down('li');
		this.nextSlide = this.slideshowWrapper.down('li').next();
		this.previousSlide = this.slideshowWrapper.down('.slide3').next();
		this.firstSlide = this.slideshowWrapper.down('li');
		this.lastSlide = this.slideshowWrapper.down('.slide3').next();
    },
    
    initController : function(e) {
    	this.controlerWrapper = this.slideshowWrapper.down('.control');
    	this.controlerWrapper.down('.'+ this.selectors.points).addClassName(this.selectors.pointsSelected);
    	this.currentPoint = this.controlerWrapper.down('.'+ this.selectors.points);
    	this.nextPoint = this.controlerWrapper.down('.'+ this.selectors.points).next();
    	this.previousPoint = this.controlerWrapper.down('.point4');
    	this.firstPoint = this.slideshowWrapper.down('.point1');
    	this.lastPoint = this.slideshowWrapper.down('.point4');
    },
    
    nextController : function(e) {
    	if (!this.currentPoint.next('.slidePoint')) {
			this.nextPoint = this.firstPoint;
		} else {
	    	this.nextPoint = this.currentPoint.next('.slidePoint');
		}
    	this.previousPoint = this.currentPoint;
    	this.currentPoint.removeClassName(this.selectors.pointsSelected);
    	this.nextPoint.addClassName(this.selectors.pointsSelected);
    	this.currentPoint = this.nextPoint; 
    },
    
    previousController : function(e) {
    	if (!this.currentPoint.previous('.slidePoint')) {
			this.nextPoint = this.lastPoint;
		} else {
	    	this.nextPoint = this.currentPoint.previous('.slidePoint');
		}
    	this.previousPoint = this.currentPoint;
    	this.currentPoint.removeClassName(this.selectors.pointsSelected);
    	this.nextPoint.addClassName(this.selectors.pointsSelected);
    	this.currentPoint = this.nextPoint; 
    },
    
    runAnimation : function(e) {
    	this.periodicalUpdater = new PeriodicalExecuter(function(pe) {
    		this.goNextSlide(); 
    	}.bind(this), 10);
    },
    
    observeInterrupt : function(e) {
    	this.slideshowWrapper.down('.control').down('.left').observe('click', function(e) {
    		this.goBackSlide();
			this.periodicalUpdater.stop();
			this.periodicalUpdater = new PeriodicalExecuter(function(pe) {
	    		this.goNextSlide(); 
	    	}.bind(this), 10);
    	}.bind(this));
		this.slideshowWrapper.down('.control').down('.right').observe('click', function(e) {
			this.goNextSlide();
			this.periodicalUpdater.stop();
			this.periodicalUpdater = new PeriodicalExecuter(function(pe) {
	    		this.goNextSlide(); 
	    	}.bind(this), 10);
		}.bind(this));
     },
    
    goNextSlide : function(e) {
    	this.slideshowWrapper.select('.' + this.selectors.selected).each(function(item) {
    		if (!item.next()) {
    			this.previousSlide = item;
    			this.nextSlide = this.firstSlide;
    		} else {
    			this.previousSlide = item;
    			this.nextSlide = item.next();
    		}	
    		this.previousSlide.hide();
    		this.nextSlide.show();
    		/*new Effect.Parallel([
    		  new Effect.Fade(this.previousSlide), 
    		  new Effect.Appear(this.nextSlide) 
    		], { 
    		  duration: 0.2
    		});*/
    		
    		this.previousSlide.removeClassName(this.selectors.selected);
    		this.nextSlide.addClassName(this.selectors.selected);
    		this.nextController();
    	}.bind(this));
   },
   
   goBackSlide : function(e) {
	   this.slideshowWrapper.select('.' + this.selectors.selected).each(function(item) {
	   		if (!item.previous()) {
	   			this.previousSlide = item;
	   			this.nextSlide = this.lastSlide;
	   		} else {
	   			this.previousSlide = item;
	   			this.nextSlide = item.previous();
	   		}	
	   		
	   		this.previousSlide.hide();
    		this.nextSlide.show();
    		
	   		/*new Effect.Parallel([
	   		  new Effect.Fade(this.previousSlide), 
	   		  new Effect.Appear(this.nextSlide) 
	   		], { 
	   		  duration: 0.6
	   		});*/
	   		
	   		this.previousSlide.removeClassName(this.selectors.selected);
	   		this.nextSlide.addClassName(this.selectors.selected);
	   		this.previousController();
	   	}.bind(this));
  }
});

Coursorama.AddProduct = Class.create({
	initialize: function(element, options) {
		this.element = element;
		this.initAddButtons();
		this.initRemoveButtons();
		this.enableChangeQuantity();
    },
    
    initAddButtons : function() {
    	$$('.cr-icons-add').each(function(item){
    		item.observe('click', function(e){
    			e.stop();
    			this.addButtonsOnClick(e);
    		}.bind(this));
    	}.bind(this));
    },
    
    addButtonsOnClick : function(e) {
    	if (!e.element().up('.ajax-product')) {
    		this.addCustomProduct(e);
    	} else {
	    	var id = e.element().up('.ajax-product').id.split('_');
	    	var identify = id[2];
	    	this.addProduct(identify , 1);
    	}
    },
    
    addProduct : function(identify, quantity) {
    	new Ajax.Request('products/add/'+identify, {
    		parameters: {q : quantity } ,
    		onLoading: function() {
    			$("products-loader").show();
    		},
    		onComplete : function () {
    				this.refreshList(identify);
    				$("products-loader").hide();
    		}.bind(this)
    	});
    },
    
    enableChangeQuantity : function() {
    	$$('.up').each(function(item) {
			item.observe('click', function(e) {
				e.element().up('.list-product').down('.quantity_input input').value = parseInt(e.element().up('.list-product').down('.quantity_input input').value) + 1;
				this.setQuantityProduct(e);
			}.bind(this));
		}.bind(this));
		
		$$('.down').each(function(item) {
			item.observe('click', function(e) {
				e.element().up('.list-product').down('.quantity_input input').value = parseInt(e.element().up('.list-product').down('.quantity_input input').value) - 1;
				this.setQuantityProduct(e);
			}.bind(this));
		}.bind(this));
    },
    
    setQuantityProduct : function(e) {
    	//Determinate product
    	var index = e.element().up('.list-product').down('.quantity_input').id.split('_');
		var identify = index[2];
		if (e.element().hasClassName('down')) {
			this.removeProduct(e , 1);
		}else {
			this.addProduct(identify , 1);
		}
    },
    
    refreshList : function(identify) {
    	new Ajax.Updater('list-content','list/index', {
			parameters: {id : identify},
			onComplete: function() {
				this.enableChangeQuantity();
				this.initRemoveButtons();
			}.bind(this)
		});
    },
    
    addCustomProduct : function(e) {
    	var id = e.element().up('.custom-product').down('.input-custom').id.split('_');
    	var identify = id[3];
    	var quantity = 1;
    	var label = $("custom_product_label_"+identify).value;
    	var price = $("custom_product_price_"+identify).value;
    	new Ajax.Request('products/addcustom', {
    		parameters: {label : label , q : quantity, price : price } ,
    		onLoading: function() {

    		},
    		
    		onComplete : function (e) {
    			new Ajax.Updater('list-content','list/index', {
    				parameters: {id : identify, q : quantity},
    				onComplete: function() {
    					this.enableChangeQuantity();
    					this.initRemoveButtons();
    				}.bind(this)
    			});
    			
    		}.bind(this)
    	});
    },
    
    initRemoveButtons : function(e) {
    	$$('.cr-icons-delete').each(function(item){
    		item.observe('click',function(e){
    			this.removeProduct(e,0);
    		}.bind(this));
    	}.bind(this));
    },
    
    removeProduct : function(e , quantity) {
    	var id = e.element().up('.list-product').down('.quantity_input').id.split('_');
    	if (e.element().up('.list-product').down('.quantity_input input').value == 0) 
    	{
    		e.element().up('.cr-list-item').fade({ 
    			duration: 1.0,
    			afterFinish:function(){
    		    }
    		});
    	}
    	var identify = id[2];
    	new Ajax.Request('products/delete', {
    		parameters: {id : identify , q : quantity} ,
    		onLoading: function() {

    		},
    		onComplete : function () {
    			this.refreshList();
    		}.bind(this)
    	});
    }
});

function resetList()
{
	validation = confirm('Voulez vous vraiment vider votre liste de course actuelle?');
	if (validation==true){
		new Ajax.Request('list/reset', {
			onComplete : function () {
				
				new Ajax.Updater('list-content','list/index', {
					onLoading: function() {
						$('list_ajax').setStyle({
							  display: 'block'
							});
					},
					
					onComplete: function() {
						$('list_ajax').setStyle({
							  display: 'none'
							});
					}
					
				});
				
			}
		});
	}
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

Coursorama.Sections = Class.create({
	
	initialize: function(element) {
		this.wrapperSections = $(element);
		this.initObserve();
		this.initSections();
		this.prototipPrice();
	},
	
	initSections : function() {
		$$('.section').first().up('li').addClassName('selected');
		$$('.section').first().up('li').down('ul').show();
		this.currentSection = $$('.section').first();
		this.currentCategories = this.currentSection.up('li').down('.categories');
		this.section_id = this.currentSection.id.split('_').reverse().first();
	},
	
	initObserve : function(e) {
		this.wrapperSections.select('.section').each(function(item){
			item.observe('click',function(e) {
				e.stop();
				if (this.currentSection) {
					this.currentSection.up('li').removeClassName('selected');
					$('categories_'+this.section_id).hide();
				}
				
				this.currentSection = e.element();
				this.currentSection.up('li').addClassName('selected');
				this.section_id = this.currentSection.id.split('_').reverse().first();
				this.currentCategories = this.currentSection.up('li').down('.categories');
				new Effect.BlindDown('categories_'+this.section_id, { duration: 0.7 });
				this.loadProducts(e);
			}.bind(this));
		}.bind(this));
	},
	
	loadProducts : function(e) {
		new Ajax.Updater('products_list', this.currentSection.readAttribute('href'), {
			method: 'get',
			parameters: {},
			onLoading: function() {
				e.element().up('li').down('.loader').show();
			}.bind(this),
			onComplete: function() {
				e.element().up('li').down('.loader').hide();
				new Coursorama.AddProduct('product-content');
				this.prototipPrice();
			}.bind(this)
		});
	},
	
	prototipPrice : function() {
		$$(".change-price").each(function(item) {
			var value = item.readAttribute('id').split('_');
			var id = value[1];
			if ($("connected")) {
				new Tip(item.readAttribute('id'), {
						title : "Changez le prix de l'article '"+$("product_"+id+"_label").innerHTML+"'",
						showOn: 'click',
						ajax: {
							url: 'product/price/'+id,
							options: {
								onComplete: function(transport) {
									$('product_price_'+id).observe('submit', function(e){
										Event.stop(e);
										if ($('product_price_'+id).down('#price').value) {
										new Ajax.Request('product/new_price/id/'+id, {
											method: 'post',
											parameters: {price : $('product_price_'+id).down('#price').value },
											onLoading: function() {
												$$('.product_ajax_'+id).each(function(item){
													item.setStyle({
														display: 'block'
													});
												});
											},
											onSuccess: function(response) {
												$('product_price_'+id).down('#price').disabled = true;
												$('product_price_'+id).down('#submit').disabled = true;
												$('product_price_'+id).down('#submit').writeAttribute('src','public/images/icons/success.jpg');
												$$('.product_ajax_'+id).each(function(item){
													item.setStyle({
														display: 'none'
													});
												});
												$("product_original_price_"+id).innerHTML = $('product_price_'+id).down('#price').value + " €";
											  }
										});
										} else {
											alert('Vous devez rentrer une valeur!');
										}
									});
								}
						    }
						},
						hideOn: { element: 'closeButton', event: 'click' },
						width: 'auto', // We don't want the default 250px.
						// Images inside the tooltip will need to have dimensions set since Prototip needs to fixate width for proper rendering.
						hook: { target: 'topMiddle', tip: 'bottomLeft' },
						stem: 'bottomLeft',
						hideAfter: 5,
						offset: { x: 0, y: -2 }
					});
			} else {
				new Tip(item.readAttribute('id'),"<span style='font-size:12px'>Vous devez être connecté pour changer le prix d'un article.<br /><center><a href='user/register'><b>Cliquez ici</b></a> pour vous inscrire</center></span>", {
					title : "Changez le prix de l'article '"+$("product_"+id+"_label").innerHTML+"'",
					showOn: 'click',
					hideOn: { element: 'closeButton', event: 'click' },
					width: 'auto', // We don't want the default 250px.
					// Images inside the tooltip will need to have dimensions set since Prototip needs to fixate width for proper rendering.
					hook: { target: 'topMiddle', tip: 'bottomLeft' },
					stem: 'bottomLeft',
					hideAfter: 5,
					offset: { x: 0, y: -2 }
				});
			}
		});
	}
});

