// <![CDATA[

var Background = Class.create({
	initialize: function()
	{
		this.locked = false;
		this.size   = document.viewport.getDimensions();
		this.el     = new Element('div', {id: 'shop-bg'});

		this.el.setStyle({
			width:this.size.width + 'px',
			height:this.size.height + 'px'
		});
		
		$(document.body).insert(this.el.hide());
	},
	
	show: function()
	{
		if(!(this.locked || this.el.visible()))
		{
			this.locked = true;
			new Effect.toggle(this.el, 'appear', {to: .75, duration: .3, afterFinish: function(){ this.locked = false; }.bind(this)});
		}
	},
	
	hide: function()
	{
		if(!this.locked && this.el.visible())
		{
			this.locked = true;
			new Effect.toggle(this.el, 'appear',  {from:.75, duration: .3, afterFinish: function(){ this.locked = false; }.bind(this)});
		}
	},
	
	refresh: function()
	{
		this.size = document.viewport.getDimensions();
		this.el.setStyle({
			width: this.size.width + 'px',
			height: this.size.height + 'px'
		});
	}
});

var ShopGUI = Class.create({
	initialize: function()
	{
		this.bg = new Background();

		pane = '<div id="shop-pane">' +
				'<a href="#" id="shop-btn-close" title="fermer">fermer</a>' +
				'<div id="shop-preview-area">' +
					'<a href="#" id="shop-btn-next" title="suivant">suivant</a>' +
					'<a href="#" id="shop-btn-prev" title="précédent">précédent</a>' +
					'<ul id="shop-navigation-thumbnails">' +
					'</ul>' +
					'<img id="shop-preview" src="/images/empty.gif" alt="" />' +
					'<div id="shop-preview-navigation">' +
						'<div id="shop-navigation-page"></div>' +
						
					'</div>' +
				'</div>' +
				'<div id="shop-commands-area">' +
					'<div id="shop-price"></div>' +
					'<div id="shop-name"></div>' +
					'<div id="shop-description"></div>' +
					'<form action="/Ajax/addtobasket" id="shop-form" method="post">' +
						'<fieldset>' +
							'<p id="referenceIDField">' +
								'<label>Taille</label>' +
							'</p>' +
							'<p id="quantityField">' +
								'<label>Quantité</label>' +
								'<select id="shop-quantity" name="quantity">' +
								'</select>' +
							'</p>' +
							'<p>' +
								'<input type="image" id="shop-btn-ajouter" src="/images/boutique/shop/bg_shop-btn-ajouter.gif" />' +
							'</p>' +
						'</fieldset>' +
					'</form>'
				'</div>' +
			'</div>';
		$(document.body).insert(pane);

		this.el = $('shop-pane').hide().setStyle({
			top:  Math.round((this.bg.size.height-336)/2) + 'px',
			left: Math.round((this.bg.size.width-522)/2)  + 'px'
		});
	},
	
	show: function()
	{
		this.bg.show();
		setTimeout(function(){ this.el.show(); }.bind(this), 300);
	},
	
	hide: function()
	{
		this.bg.hide();
		setTimeout(function(){ this.el.hide(); }.bind(this), 175);
	},
	
	refresh: function()
	{
		this.bg.refresh();
		this.el.setStyle({
			top: Math.round((this.bg.size.height-336)/2) + 'px',
			left: Math.round((this.bg.size.width-522)/2) + 'px'
		});
	}
});

var Shop = Class.create({
	initialize: function()
	{
		if($('productsList'))
		{
			this._pane        = new ShopGUI();
			this._form        = $('shop-form');
			this._name        = $('shop-name');
			this._description = $('shop-description');
//			this._referenceID = $('shop-referenceID');
			this._quantity    = $('shop-quantity');
			this._price       = $('shop-price');
			this._preview     = $('shop-preview');
			this._page        = $('shop-navigation-page');
			this._thumbnails  = $('shop-navigation-thumbnails');
			this._btnClose    = $('shop-btn-close');
			this._btnPrev     = $('shop-btn-prev');
			this._btnNext     = $('shop-btn-next');

			this._btnClose.observe('click', this.onClose.bindAsEventListener(this));
			this._btnPrev.observe('click',  this.onPrevious.bindAsEventListener(this));
			this._btnNext.observe('click',  this.onNext.bindAsEventListener(this));
			this._form.observe('submit',    this.addToBasket.bindAsEventListener(this));
			

			$$('ul#l1 a.shop-command').each(function(p)
			{
				p.observe('click', this.onCategorySelected.bindAsEventListener(this, p));
			}.bind(this));
			
			
			$$('div#productsList ul li a').each(function(p)
			{
				p.observe('click', this.onCategorySelected.bindAsEventListener(this, p));
			}.bind(this));
			
			/(.+)\/(.+)\/(.+)-(.)+/.exec(window.location.href);
			
			var index = parseInt(RegExp.$3);
			
			if(index>0)
			{
				this.autoLoad(index);
			}
			
			Event.observe(window, 'resize', this.onWindowResized.bind(this));
		}
	},

	autoLoad: function(index)
	{
		var categoryID = index;

		this._data = [];
		this._page.update('');
		this._thumbnails.update('');
		this._pane.bg.show();

		new Ajax.Request(
			'/Ajax/getproducts/categoryID/' + categoryID,
			{
				method: 'get',
				onSuccess: function(transport)
				{
					this._data = transport.responseJSON;
					
					this.initData();
				}.bind(this)
			}
		);
	},

	onCategorySelected: function(event, product)
	{
		event.stop();
		product.blur();
		
		var categoryID = product.id.substr(2);

		this._data = [];
		this._page.update('');
		this._thumbnails.update('');

		new Ajax.Request(
			'/Ajax/getproducts/categoryID/' + categoryID,
			{
				method: 'get',
				onSuccess: function(transport)
				{
					this._data = transport.responseJSON;

					this.initData();
				}.bind(this)
			}
		);
	},

	onReferenceSelected: function(event)
	{
		var ref = $F(this._referenceID);
		var references = this._data[this.index].references;
		var qmax = 0;

		this.available = true;

		this._quantity.update('');
		if(references.length>1)
		{
			references.each(function(r){
				if(r.referenceID===ref)
				{
					qmax = r.available;
				}
			}.bind(this));
		}
		else
		{
			qmax = this._data[0].references[0].available;
		}
		
		if(qmax<1)
		{
			this.available = false;
			this._quantity.insert('<option value="0">indisponible</option>');
		}
		else
		{
			qmax = 15; // TODO HERE...
			for(var i=1;i<=qmax; i++)
			{
				this._quantity.insert('<option value="' + i + '">' + i + '</option>');
			}
	
			this._quantity.options.selectedIndex = 0;
		}
	} ,

	initData: function()
	{
		this.index = 0;
		this.last  = this._data.length;

		this._page.update('produit ' +  (this.index+1) + '/' + this.last);
	
		var thumb;
		this._data.each(function(p, i){
			var pic = new Image();
			pic.src = '/images/boutique/shop/products/' + p.productID + '.png';

			thumb = new Element('li');
			thumb.insert(new Element('img', {src: pic.src, height:40, width:40}));

			this._thumbnails.insert(thumb);
		}.bind(this));

		var thumbnails = this._thumbnails.immediateDescendants()
		thumbnails[this.index].addClassName('selected');
		
		this._name.update(this._data[this.index].pname);
		this._description.update(this._data[this.index].description);

		this._preview.src = thumbnails[this.index].childNodes[0].src;

		this.setReferences(this._data[this.index].productID);

		this._pane.show();
	},
	
	onPrevious: function(event)
	{
		event.stop();
		event.element().blur();

		if(this.index>0)
		{
			var thumbnails = this._thumbnails.immediateDescendants();

			this.index = this.index - 1;
			
			thumbnails[this.index+1].removeClassName('selected');
			thumbnails[this.index].addClassName('selected');

			this._page.update('produit ' +  (this.index+1) + '/' + this.last);
			this._name.update(this._data[this.index].pname);
			this._description.update(this._data[this.index].description);
			this._quantity.value = 1;
			this._preview.src = thumbnails[this.index].childNodes[0].src;

			this.setReferences(this._data[this.index].productID);
		}
	},
	
	onNext: function(event)
	{
		event.stop();
		event.element().blur();

		if(this.index<this.last-1)
		{
			var thumbnails = this._thumbnails.immediateDescendants();

			this.index = this.index + 1;

			thumbnails[this.index-1].removeClassName('selected');
			thumbnails[this.index].addClassName('selected');

			this._page.update('produit ' +  (this.index+1) + '/' + this.last);
			this._name.update(this._data[this.index].pname);
			this._description.update(this._data[this.index].description);
			this._quantity.value = 1;
			this._preview.src = thumbnails[this.index].childNodes[0].src;

			this.setReferences(this._data[this.index].productID);
		}
	},

	setReferences: function(productID)
	{
		var references = this._data[this.index].references;

		var referenceIDField = $('referenceIDField').hide();

		if(references.length>1)
		{
			this._referenceID = new Element('select', {id: 'shop-referenceID', name: 'referenceID'});

			references.each(function(r){
				if(r.available>0)
				{
					this._referenceID.insert('<option value="' + r.referenceID + '">' + r.size + '</option>');
					this._price.update(r.price + ' &euro;');
				}
			}.bind(this));
			this._referenceID.options.selectedIndex = 0;

			this._referenceID.observe('change', this.onReferenceSelected.bindAsEventListener(this));

			referenceIDField.update('<label>Taille</label>').insert(this._referenceID)
			referenceIDField.show();
		}
		else
		{
			this._price.update(this._data[0].references[0].price + ' &euro;');
			this._referenceID = new Element('input', {type: 'hidden', id: 'shop-referenceID', name: 'referenceID', value: references[0].referenceID});

			referenceIDField.update();
			$('quantityField').insert(this._referenceID);
		}

		this.onReferenceSelected(null);
	},

	addToBasket: function(event)
	{
		event.stop();
		
		var referenceID = $F(this._referenceID);
		var quantity    = $F(this._quantity);

		if(this.available)
		{
			new Ajax.Request(
				'/Ajax/addtobasket',
				{
					method: 'post',
					parameters: {'referenceID': referenceID, 'quantity': quantity},
					onSuccess: function(transport)
					{
						var referencesNb = transport.responseJSON;

						if(referencesNb==-1)
						{
							alert("Le nombre d’article par commande est limité à 15.\nSi vous souhaitez en commander plus, n’hésitez pas à nous contacter par téléphone au \n01 42 72 41 31 ou par mail sur boutique@leriremedecin.asso.fr");
						}
						else
						{
							if(referencesNb>1)
							{
								$('basketItemsNb').update('<a href="/Boutique/Panier" title="Voir le contenu du panier"><span>' + referencesNb + '</span> références</a>').cleanWhitespace();
							}
							else if(referencesNb = 1)
							{
								$('basketItemsNb').update('<a href="/Boutique/Panier" title="Voir le contenu du panier"><span>1</span> référence</a>').cleanWhitespace();
							}
							else
							{
								$('basketItemsNb').update('<span>0</span> référence').cleanWhitespace();
							}
	
							alert('La référence à été ajoutée à votre panier.');
						}
					}.bind(this)
				}
			);
		}
		else
		{
			alert('Cet article est momentanément indisponible.');
		}
	},

	onClose: function(event)
	{
		event.stop();
		this._pane.hide();
	},

	onWindowResized: function()
	{
		this._pane.refresh();
	}
});

document.observe("dom:loaded", function(){
	var shop = new Shop();
	if(scroll)
	{
		scroll.setMaxHeight(280);
	}
});

window.onload = function(){
	scroll.setMaxHeight(280);
};

// ]]>