/**************************************************************
	Script		: flyShoppingCart
	Version		: 1.0
	Authors		: Guillaume Rabelle
**************************************************************/

var flyShoppingCart = new Class({

	getOptions: function(){
		return {
			initialWidth: 120,
			initialHeight: 120,
			container: document.body,
			prefixImg:"img",
			remoteScript:"/response/ajax-caddie.php"
		};
	},
	
	initialize: function(className, options){
		// on initialise les options
		this.setOptions(this.getOptions(), options);
		
		// La div qui va contenir le panier
		this.container = $('flyShoppingCartContainer');
		this.box = $$('.flyShoppingCartContent')[0];

		// Le contenu
		this.content = $$('.'+className);
		this.content.each(function(el,i){
			el.index = i;
			el.addEvent('click', function(e){
				new Event(e).stop();
				this.addToCart(el);
			}.bind(this));
			
			if(el.href.indexOf('#') > -1){
				el.content = $(el.href.substr(el.href.indexOf('#')+1));
				if(el.content){el.content.setStyle('display','none');}
			}
		}, this);
		
		//
	},
	
	suppFromCart : function (id){
		// Mise à jour du panier  avec un appel server (AJAX)
		var myOptions = Hash.toQueryString({"action":"supp","refId":id});
		new Request.HTML({'url':this.options.remoteScript,method: 'get',update: this.box,encoding:'utf8',evalScripts : true}).send(myOptions);
		return false;
	},
	
	addToCart: function(el){
		
		var imgId = el.id;
		var refId = el.id;
		var diesePos = refId.indexOf('#');
		// el.id peut contenir un # si option
		if(diesePos > -1)
		{
				// pour envoyer l'image, on prend l'id parent (avt le #)
				// pour le refId on mets bien la ref complete sans le #
				tempRefId = refId;
				refId = tempRefId.substring(0,diesePos) + tempRefId.substring(diesePos+1,tempRefId.length);
				imgId = tempRefId.substring(0,diesePos);
		}
		// Image du produit à cloner
		var newEl = $(this.options.prefixImg+imgId);
		
		// Coordonnées de départ pour le clone (correction de la marge)
		var myClone = newEl.clone().setStyles(newEl.getCoordinates()).addClass('FlyBox').injectInside(document.body);
		var myEffects = new Fx.Morph(myClone, {duration: 500, transition: Fx.Transitions.Sine.easeInOut});
		myEffects.start({width:20,height:20,top:$(this.options.imgPanier).getCoordinates().top,left:$(this.options.imgPanier).getCoordinates().left,opacity:0.8});
		(function(){myClone.dispose()}).delay(600);
		
		// Mise à jour du panier  avec un appel server (AJAX)
		var myOptions = Hash.toQueryString({"action":"add","refId": refId});

		new Request.HTML({'url':this.options.remoteScript,method: 'get',update: this.box,encoding:'utf8',evalScripts : true}).send(myOptions);
		return false;
	}
});
flyShoppingCart.implement(new Options);
flyShoppingCart.implement(new Events);
