/* Cross-Browser Split 1.0.1
(c) Steven Levithan <stevenlevithan.com>; MIT License
An ECMA-compliant, uniform cross-browser split method */

var cbSplit;

// avoid running twice, which would break `cbSplit._nativeSplit`'s reference to the native `split`
if (!cbSplit) {

cbSplit = function (str, separator, limit) {
    // if `separator` is not a regex, use the native `split`
    if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
        return cbSplit._nativeSplit.call(str, separator, limit);
    }

    var output = [],
        lastLastIndex = 0,
        flags = (separator.ignoreCase ? "i" : "") +
                (separator.multiline  ? "m" : "") +
                (separator.sticky     ? "y" : ""),
        separator = RegExp(separator.source, flags + "g"), // make `global` and avoid `lastIndex` issues by working with a copy
        separator2, match, lastIndex, lastLength;

    str = str + ""; // type conversion
    if (!cbSplit._compliantExecNpcg) {
        separator2 = RegExp("^" + separator.source + "$(?!\\s)", flags); // doesn't need /g or /y, but they don't hurt
    }

    /* behavior for `limit`: if it's...
    - `undefined`: no limit.
    - `NaN` or zero: return an empty array.
    - a positive number: use `Math.floor(limit)`.
    - a negative number: no limit.
    - other: type-convert, then use the above rules. */
    if (limit === undefined || +limit < 0) {
        limit = Infinity;
    } else {
        limit = Math.floor(+limit);
        if (!limit) {
            return [];
        }
    }

    while (match = separator.exec(str)) {
        lastIndex = match.index + match[0].length; // `separator.lastIndex` is not reliable cross-browser

        if (lastIndex > lastLastIndex) {
            output.push(str.slice(lastLastIndex, match.index));

            // fix browsers whose `exec` methods don't consistently return `undefined` for nonparticipating capturing groups
            if (!cbSplit._compliantExecNpcg && match.length > 1) {
                match[0].replace(separator2, function () {
                    for (var i = 1; i < arguments.length - 2; i++) {
                        if (arguments[i] === undefined) {
                            match[i] = undefined;
                        }
                    }
                });
            }

            if (match.length > 1 && match.index < str.length) {
                Array.prototype.push.apply(output, match.slice(1));
            }

            lastLength = match[0].length;
            lastLastIndex = lastIndex;

            if (output.length >= limit) {
                break;
            }
        }

        if (separator.lastIndex === match.index) {
            separator.lastIndex++; // avoid an infinite loop
        }
    }

    if (lastLastIndex === str.length) {
        if (lastLength || !separator.test("")) {
            output.push("");
        }
    } else {
        output.push(str.slice(lastLastIndex));
    }

    return output.length > limit ? output.slice(0, limit) : output;
};

cbSplit._compliantExecNpcg = /()??/.exec("")[1] === undefined; // NPCG: nonparticipating capturing group
cbSplit._nativeSplit = String.prototype.split;

} // end `if (!cbSplit)`

// for convenience...
String.prototype.split = function (separator, limit) {
    return cbSplit(this, separator, limit);
};


var validStep = function(step){
	var form = false;
	//vérification du formulaire et des champs obligatoires
	tab = new Array();
	$(step).getElements('input').each(function(el,i){
			name = new Array();
			name = el.name.split('-');
			if(name[3] == 'o'){
				el.getParent().getParent().setStyle('background','none');
				if(el.value.trim() == '')
					tab.include(el);
			}
	});
	$(step).getElements('textarea').each(function(el,i){
			name = el.name.split('-');
			if(name[3] == 'o'){
				el.getParent().getParent().setStyle('background','none');
				if(el.value.trim() == '')
					tab.include(el);
			}
	});
	$(step).getElements('.formulaire_error').each(function(item){
		item.dispose();
	});
	
	
	//attribution du message d'erreur pour les champs obligatoires vides
	var errorMessage = "Ce champ est obligatoire, veuillez le renseigner s'il vous plaît.";
	tab.each(function(el){
		el.getParent().getParent().adopt(new Element('div', {
							'class': 'formulaire_error',
							'html': errorMessage,
							'style': 'height: 40px;color:#fff;'
						}).morph({height: 40}));
		el.getParent().getParent().setStyle('background-color','#6B221C');
		el.getParent().getParent().setStyle('padding','10px');
	});
	
	if(tab.length == 0)
		form = true;
		
	//vérification du choix d'un élément
	var cpt=0;
	var nb_el=0;
	
	$(step).getElements('.element').each(function(el){
		if(el.getElement('.bouton').checked){
  			cpt++;
  		}
  		nb_el++;
	});
		
	if(form){
		if(nb_el>0){
			if(cpt==1)
				return true;
			else
				return false;
		}
		else{
			return true;
		}
	}
	else{
		return false;
	}
	
	
}

var checkSteps = function(type){
	if(type=='total')
		var etapes = $$('.etape');
	else
		var etapes = $$('.visited');
		
	var bool = true;
	etapes.each(function(item){
		id_step = item.get('id');
		var num_etape = id_step.substr(5,(id_step.length-5)); 
		
		//on check si l'étape a correctement été renseignée
		var id = 'statut-img-'+num_etape;
		if(validStep(id_step)){
			$(id).set('src',wwwroot+'/media/img/img_conception/ok.png');
			$(id).set('alt','ok');
		}
		else{ //sinon 
			$(id).set('src',wwwroot+'/media/img/img_conception/ko.png');	
			$(id).set('alt','ko');
			bool = false;
		}
	});
	return bool;
}


//fonction qui coche le bouton si on click dans la case du produit
var checkOnClick = function(el){
	if(el.getElement('.bouton').checked){
  		el.getElement('.bouton').set('checked', '');
  		el.set('class','element');
  	}
  	else{
  		var checkbox = el.getParent().getParent().getElements('.bouton');
  		checkbox.each(function(item){
  			item.set('checked', '');
  			item.getParent().getParent().set('class','element');
  		});
  		
  		el.getElement('.bouton').set('checked', 'checked');
  		el.set('class','element select');
  	}
}

//fonction qui switch à l'étape cliquée dans le menu an haut de page
var switchStep = function(lien, id_lien){
	
	$$('.etape').setStyle('display','none');
	var num_etape = id_lien.substr(6,(id_lien.length-6)); 
	var etape_cur = 'step-'+num_etape;
	$(etape_cur).setStyle('display','block');
	$(etape_cur).addClass('visited');
	checkSteps();
	switchButton();
	selectCur();
	this.refreshSlider(0);
	var myFx = new Fx.Scroll('etapes', {wheelStops: false}).toElement('etapes');
	
}

//fonction qui permet de passer à l'étape suivante à l'aide du bouton bas de page
var nextStep = function(){
	var done = false;
	var etapes = $$('.etape');
	etapes.each(function(item){
		if(item.isDisplayed() && !done){
			id_step = item.get('id');
			var num_etape = id_step.substr(5,(id_step.length-5)); 
			etapes.setStyle('display','none');
			var etape_cur = 'step-'+(parseInt(num_etape)+1);
			$(etape_cur).setStyle('display','block');
			$(etape_cur).addClass('visited');
			done = true;
		}	
	});
	checkSteps();
	switchButton();
	affichageEtapes('next');
	selectCur();
	this.refreshSlider(0);
	var myFx = new Fx.Scroll('etapes', {wheelStops: false}).toElement('etapes');
	
}

//fonction qui permet de passer à l'étape suivante à l'aide du bouton bas de page
var prevStep = function(){
	var done = false;
	var etapes = $$('.etape');
	etapes.each(function(item){
		if(item.isDisplayed() && !done){
			id_step = item.get('id');
			var num_etape = id_step.substr(5,(id_step.length-5)); 
			etapes.setStyle('display','none');
			var etape_cur = 'step-'+(parseInt(num_etape)-1);
			$(etape_cur).setStyle('display','block');
			$(etape_cur).addClass('visited');
			done = true;
		}	
	});
	checkSteps();
	switchButton();
	affichageEtapes('prev');
	selectCur();
	this.refreshSlider(0);
	var myFx = new Fx.Scroll('etapes', {wheelStops: false}).toElement('etapes');
	
}

//fonction gerant l'affichage de la barre de choix d'étape en haut de page (8 etapes à l'affichage maxi)
var affichageEtapes = function(type){
	checkSteps();
	var etapes = $$('.select_etape');
	var tab = new Array();
	if(etapes.length > 7){
		etapes.each(function(item){
			if(item.isDisplayed()){
				tab.include(item);
			}
		});
		if(tab.length > 6){
			if(type == 'next'){
				id_last = tab.getLast().get('id');
				var num_etape = id_last.substr(6,(id_last.length-6));
				var etape_next = 'etape-'+(parseInt(num_etape)+1);
				if($(etape_next)){
					id_first = tab[0].get('id');
					$(id_first).setStyle('display', 'none');
					$(etape_next).setStyle('display', 'block');
				}

			}
			else if(type == 'prev'){
				id_first = tab[0].get('id');
				var num_etape = id_first.substr(6,(id_first.length-6));
				var etape_prev = 'etape-'+(parseInt(num_etape)-1);
				if($(etape_prev)){
					$(etape_prev).setStyle('display', 'block');
					id_last = tab.getLast().get('id');
					$(id_last).setStyle('display', 'none');
				}
			}
			else{}
		}
	}
	this.refreshSlider(0);
	var myFx = new Fx.Scroll(document, {wheelStops: false}).toElement('etapes');
	
}

var switchButton = function(){

	var etapes = $$('.etape');
	/*
	* affichage du bouton pour valider le formulaire et on efface celui pour passer à l'étape suivante
	* Si on est à la derniere étape
	*/
	
	//récupération des 2 boutons
	var bnext = $$('#next_step');
	var bprev = $$('#prev_step');
	var bnext2 = $$('#next_fleche');
	var bprev2 = $$('#prev_fleche');
	
	etapes.each(function(item){
		if(item.isDisplayed()){
			id_step = item.get('id');
			var num_etape = id_step.substr(5,(id_step.length-5)); 
			var etape_next = 'step-'+(parseInt(num_etape)+1);
			var etape_prev = 'step-'+(parseInt(num_etape)-1);

			if(!$(etape_next)){ //alors on change de bouton
				bnext.setStyle('display', 'none');
				bnext2.setStyle('display', 'none');
				$('finalisation').setStyle('display','block');
			}
			else{
				bnext.setStyle('display', 'block');
				bnext2.setStyle('display', 'block');
				$('finalisation').setStyle('display','none');
			}
			if(!$(etape_prev)){
				bprev.setStyle('display', 'none');
				bprev2.setStyle('display', 'none');
				$('btns_etapes').setStyle('margin-left','18px');
			}
			else{
				bprev.setStyle('display', 'block');
				bprev2.setStyle('display', 'block');
				$('btns_etapes').setStyle('margin-left','0px');
			}
		}	
	});
}

var selectCur = function(){

	var step = $$('.select_etape');
	var num_etape = 1;
	var num_etape2 = 1;
	var cur = step[0];
	var id;
	step.each(function(item){
		//on recupère le num de l'étape courante
		var etapes = $$('.etape');
		etapes.each(function(item2){
			if(item2.isDisplayed()){
				cur = item2.get('id');
				num_etape = cur.substr(5,(cur.length-5)); 
			}
		});
		
		//on attribut ou on eneleve la class selon le cas
		id = item.get('id');
		num_etape2 = id.substr(6,(id.length-6)); 
		if(item.hasClass('etape_active') && (num_etape2 != num_etape)){ //Si il a la class active et qu'il est différent de l'étape courante 
			//alors on lui enlève la class
			item.removeClass('etape_active');
		}
		else if(num_etape2 == num_etape){ //si c'est l'etape active
			//alors on lui ajoute la class active
			item.addClass('etape_active');
		}
	});
	
}




GestionProduit = new Class({
  Implements: [Options, Events],
  
  options: {
    pid:          0,
    values:       [],
    stockNumber:  0
  },
  
  initialize: function(option) {
    this.setOptions(option);
    this.pid = this.options.pid;
    this.values = this.options.values;
    this.stockNumber = this.options.stockNumber;
    this.cart = $('nb_article');
    this.more = $('img_more');
    this.less = $('img_less');
    this.quantity = $('quantite');
    this.stockStars = $('stock_img');
    
    this.price = $('oldprice');     
    this.promotionalPrice = $('price');
    this.cartButton = $('bouton_ajouteraupanier');

    this.setCartButtonListener();
    this.setQuantifierListener();

    this.isCorrectQuantity();
  },

  setQuantifierListener: function() {
    this.eventMoreClick = this.moreQuantity.bind(this); // Passage en référence obligatoire à cause du bind
    this.eventLessClick = this.lessQuantity.bind(this); // Passage en référence obligatoire à cause du bind
    this.eventQuantityChange = this.isCorrectQuantity.bind(this); // Passage en référence obligatoire à cause du bind

    this.more.addEvent('click', this.eventMoreClick);
    this.less.addEvent('click', this.eventLessClick);
    this.quantity.addEvent('change', this.eventQuantityChange);
  },

  setCartButtonListener: function() {
    this.eventCartButtonClick = this.addToCart.bind(this); // Passage en référence obligatoire à cause du bind
    this.cartButton.addEvent('click', this.eventCartButtonClick);
  },

  /**
   * Vérifie la suffisance du stock
   *
   * @return true|false true si le stock est suffisant, false sinon
   */
  hasSufficientStock: function() {
    var quantity = parseInt(this.quantity.value);
    
    return (this.stockNumber >= quantity || this.stockNumber == -1);
  },

  isCorrectQuantity: function() {
    var quantity = parseInt(this.quantity.value);
    
    if (!this.hasSufficientStock()) {
      if (this.stockNumber == 0 || this.stockNumber == -2) {
        this.quantity.value = 0;
        alert('Désolé, le stock pour ce produit est actuellement épuisé.');
      } else {
        this.quantity.value = this.stockNumber;
        alert('Nous n\'avons pas suffisament de stock pour satisfaire votre demande. Nous vous avons indiqué dans le champs quantité la quantité maximale que nous pouvons vous fournir ('+ this.quantity.value +').');
      }
      return false;
    }

    if (quantity <= 0)
      return false;

 
    return true;
  },
  
  moreQuantity: function() {
    this.quantity.value++;
    return this.isCorrectQuantity();
       
  },

  lessQuantity: function() {
      if (this.quantity.value > 0) this.quantity.value--;
      return this.isCorrectQuantity(); 
  },

  setStockStars: function() {
    if (this.stockNumber > 0 || this.stockNumber == -1)
      this.stockStars.src = wwwroot + '/media/img/enstock.jpg';
    else if (this.stockNumber <= -2)
      this.stockStars.src = wwwroot + '/media/img/prochainement.jpg';
    else
      this.stockStars.src = wwwroot + '/media/img/epuise.jpg';
  },

  addToCart: function() {    
    var formatHTML;
     
    // verification du stock disponible et de ce que l'on a déjà ajouté au panier
    if (this.isCorrectQuantity()) {
      // on lance l'appel ajax pour ajouter au panier
      var remote = new Remote({ name:'commerce' , command:'addProductToCart' , params:{ product_id:this.pid, values_ids:this.values , quantity:this.quantity.value , perso:1} });
  
      remote.addEvent('complete', function(remote) {
  
      if(remote.getResponseCode() == 1) {
         
        var nb_article = remote.getResponseData();

        if (nb_article == 0)
          formatHTML = 'Votre panier est vide';
        else {
          formatHTML = '<a href="' + wwwroot + '/commande/panier.html" title="Voir votre panier">';
          formatHTML += nb_article + ' ' + ((nb_article > 1) ? 'articles' : 'article') + ' dans votre panier';
          formatHTML += '</a>';	    
        }

        this.cart.innerHTML = formatHTML;
      
        Growl.Bezel({
          title: 'Panier',
          text: 'Le produit a &eacute;t&eacute; ajout&eacute; &agrave; votre panier. Quantit&eacute;: '+this.quantity.value+' produit'+(this.quantity.value>1  ?'s':'')+'',
          image: wwwroot+'/media/module/Commerce/cart-logo.png',
          duration: 2
        });
      
      } else {
        var text = remote.getResponseText();
        this.stockNumber = remote.getResponseData();        
        if (text.trim() == 'already_on_cart') {
          alert('Vous avez déjà commandé la quantité maximale pour ce produit');
          this.quantity.value = 0;
        } else       
          this.isCorrectQuantity();
      }
  
      // getResponseCode()
      // getResponseText()
      // getResponseData()
  
      }.bind(this));
  
    remote.call();
    
    }
  }

});







/**
 * MooFlow - Image gallery
 *
 * Dependencies: MooTools 1.2
 *
 * @version			0.2.1
 *
 * @license			MIT-style license
 * @author			Tobias Wetzel <info [at] outcut.de>
 * @copyright		Author
 * @docmentation	http://outcut.de/MooFlow/Docmentation.html
 */ 

var MooFlow = new Class({

	Implements: [Events, Options],
	
	options: {
		onStart: $empty,
		onClickView: $empty,
		onAutoPlay: $empty,
		onAutoStop: $empty,
		onRequest: $empty,
		onResized: $empty,
		onEmptyinit: $empty,
		reflection: 0.3,
		heightRatio: 0.55,
		offsetY: -50,
		startIndex: 0,
		interval: 3000,
		factor: 110,
		bgColor: '',
		useCaption: true,
		useResize: true,
		useSlider: true,
		useWindowResize: true,
		useMouseWheel: true,
		useKeyInput: true,
		useViewer: true
	},
	
	initialize: function(element, options){
		this.MooFlow = element;
		this.setOptions(options);
		this.foc = 150;
		this.factor = this.options.factor;
		this.offY = this.options.offsetY;
		this.isFull = true;
		this.isAutoPlay = true;
		this.isLoading = false;
		this.inMotion = true;
		
		this.MooFlow.addClass('mf').setStyles({
			'overflow':'hidden',
			'background-color':this.options.bgColor,
			'position':'relative',
			'opacity':0
		});
		
		if(this.options.useWindowResize) window.addEvent('resize', this.update.bind(this, 'init'));
		if(this.options.useMouseWheel || this.options.useSlider) this.MooFlow.addEvent('mousewheel', this.wheelTo.bind(this));
		if(this.options.useKeyInput) document.addEvent('keydown', this.keyTo.bind(this));
		
		this.getElements(this.MooFlow);
	},
	
	clearInit: function(){
		this.fireEvent('emptyinit');
	},
	
	getElements: function(el){
		this.master = {'images':[]};
		var els = el.getChildren();
		if(!els.length) {this.clearInit(); return;}
		$$(els).each(function(el){
			var hash = $H(el.getElement('img').getProperties('src','title','alt','longdesc'));
			if(el.get('tag') == 'a') hash.combine(el.getProperties('href','rel','target'));
			this.master['images'].push(hash.getClean());
			el.dispose();
		}, this);
		this.clearMain();
	},
	
	clearMain: function(){
		if(this.cap){this.cap.fade(0);}
		if(this.nav){
			new Fx.Tween(this.nav, {
				'onComplete': function(){
					this.MooFlow.empty();
					this.createAniObj();
				}.bind(this)
			}).start('bottom', -50);
		}
		if(!this.nav && !this.cap){
			this.MooFlow.empty();
			this.createAniObj();
		}
	},
	
	getMooFlowElements: function(key){
		var els = [];
		this.master.images.each(function(el){ 
			els.push(el[key]); 
		});
		return els;
	},
	
	createAniObj: function(){
		this.aniFx = new Fx.Value({
			'transition': Fx.Transitions.Expo.easeOut,
			'link': 'cancel',
			'duration': 750,
			onMotion: this.process.bind(this),
			'onStart': this.flowStart.bind(this),
			'onComplete': this.flowComplete.bind(this)
		});
		this.addLoader();
	},
	
	addLoader: function(){
		this.MooFlow.store('height', this.MooFlow.getSize().y);
		this.loader = new Element('div',{'class':'loader'}).inject(this.MooFlow);
		new Fx.Tween(this.MooFlow, {
			'duration': 800,
			'onComplete': this.preloadImg.bind(this)
		}).start('opacity', 1);
	},
	
	preloadImg: function(){
		this.loadedImages = new Asset.images(this.getMooFlowElements('src'), {
			'onComplete': this.loaded.bind(this),
			'onProgress': this.createMooFlowElement.bind(this)
		});
	},
	
	createMooFlowElement: function(counter, i){
		var obj = this.getCurrent(i);
		var img = this.loadedImages[i];
		obj['width'] = img.width;
		obj['height'] = img.height;
		img.removeProperties('width','height');

		obj['div'] = new Element('div').setStyles({
			'position':'absolute',
			'display':'none',
			'height': this.MooFlow.getSize().y
		}).inject(this.MooFlow);
		obj['con'] = new Element('div').inject(obj['div']);
		img.setStyles({'vertical-align':'bottom', 'width':'100%', 'height':'50%'});
		img.addEvents({'click': this.clickTo.bind(this, i), 'dblclick': this.viewCallBack.bind(this, i)});
		img.inject(obj['con']);
		
		new Element('div').reflect({ 'img': img,
			'ref': this.options.reflection,
			'height': obj.height,
			'width': obj.width,
			'color': this.options.bgColor
		}).setStyles({'width':'100%','height':'50%','background-color': this.options.bgColor}).inject(obj['con']);
		
		this.loader.set('text', (counter+1) + ' / ' + this.loadedImages.length);
	},
	
	loaded: function(){
		this.index = this.options.startIndex;
		this.iL = this.master.images.length-1;
		new Fx.Tween(this.loader, {
			'duration': 800,
			'onComplete': this.createUI.bind(this)
		}).start('opacity', 0);
	},
	
	createUI: function(){
		this.loader.dispose();
		if(this.options.useCaption){
			this.cap = new Element('div').addClass('caption').set('opacity',0).inject(this.MooFlow);
		}	
		this.nav = new Element('div').addClass('mfNav').setStyle('bottom','-50px');
		this.autoPlayCon = new Element('div').addClass('autoPlayCon');
		this.sliderCon = new Element('div').addClass('sliderCon');
		this.resizeCon = new Element('div').addClass('resizeCon');		
		if(this.options.useAutoPlay){
			this.autoPlayCon.adopt(
				new Element('a',{'class':'stop','events': {'click':this.stop.bind(this)}}), 
				new Element('a',{'class':'play','events': {'click':this.play.bind(this)}})
			);
		}
		if(this.options.useSlider){
			this.sliPrev = new Element('a',{'class':'sliderNext','events': {'click':this.prev.bind(this)}});
			this.sliNext = new Element('a',{'class':'sliderPrev','events': {'click':this.next.bind(this)}});
			this.knob = new Element('div',{'class':'knob'});
			this.knob.adopt(new Element('div',{'class':'knobleft'}));
			this.slider = new Element('div',{'class':'slider'}).adopt(this.knob);
			this.sliderCon.adopt(this.sliPrev,this.slider,this.sliNext);
			this.slider.store('parentWidth', this.sliderCon.getSize().x-this.sliPrev.getSize().x-this.sliNext.getSize().x);
		}
		if(this.options.useResize){
			this.resizeCon.adopt(new Element('a',{'class':'resize','events': {'click':this.setScreen.bind(this)}}));
		}		
		this.MooFlow.adopt(this.nav.adopt(this.autoPlayCon, this.sliderCon, this.resizeCon));	
		this.showUI();
	},
	
	showUI: function(){
		if(this.cap) this.cap.fade(1);
		this.nav.tween('bottom', 20);
		this.fireEvent('start');
		this.update();
	},
	
	update: function(e){
		if(e == 'init') return;
		this.oW = this.MooFlow.getSize().x;
		this.sz = this.oW * 0.5;
		if(this.options.useSlider){	
			this.slider.setStyle('width',this.slider.getParent().getSize().x-this.sliPrev.getSize().x-this.sliNext.getSize().x-1);
			this.knob.setStyle('width',(this.slider.getSize().x/this.iL));
			this.sli = new SliderEx(this.slider, this.knob, {steps: this.iL}).set(this.index);
			this.sli.addEvent('onChange', this.glideTo.bind(this));
		}
		this.glideTo(this.index);
		this.isLoading = false;
	},
	
	setScreen: function(){
		if(this.isFull = !this.isFull){
			this.holder = new Element('div').inject(this.MooFlow,'after');
			this.MooFlow.wraps(new Element('div').inject(document.body));
			this.MooFlow.setStyles({'position':'absolute','z-index':'100','top':'0','left':'0','width':window.getSize().x,'height':window.getSize().y});
			if(this.options.useWindowResize){
				this._initResize = this.initResize.bind(this);
				window.addEvent('resize', this._initResize);
			}
		} else {
			this.MooFlow.wraps(this.holder);
			window.removeEvent('resize', this._initResize);
			delete this.holder, this._initResize;
			this.MooFlow.setStyles({'position':'relative','z-index':'','top':'','left':'','width':'','height':this.MooFlow.retrieve('height')});
			this.slider.setStyle('width',this.slider.retrieve('parentWidth'));
		}
		this.fireEvent('resized', this.isFull);
		this.update();
	},
	
	initResize: function(){
		this.MooFlow.setStyles({'width':window.getSize().x,'height':window.getSize().y});
		this.update();
	},
	
	getCurrent: function(index){
		return this.master.images[$chk(index) ? index : this.index];
	},
	
	loadJSON: function(url){
		if(!url || this.isLoading) return;
		this.isLoading = true;
		new Request.JSON({
			'onComplete': function(data){
				if($chk(data)){
					this.master = data;
					this.clearMain();
					this.fireEvent('request', data);
				}
			}.bind(this)
		}, this).get(url);
	},
	
	loadHTML: function(url, filter){
		if(!url || !filter || this.isLoading) return;
		this.isLoading = true;
		new Request.HTML({
			'onSuccess': function(tree, els, htm){
				var result = new Element('div', {'html': htm}).getChildren(filter);
				this.getElements(result);
				this.fireEvent('request', result);
			}.bind(this)
		}, this).get(url);
	},
	
	flowStart: function(){
		this.inMotion = true;
	},
	
	flowComplete: function(){
		this.inMotion = false;
	},
	
	viewCallBack: function(index){
		if(this.index != index || this.inMotion) return;
		var el = $H(this.getCurrent());
		var returnObj = {};
		returnObj['coords'] = el.div.getElement('img').getCoordinates();
		el.each(function(v, k){
			if($type(v) == 'number' || $type(v) == 'string') returnObj[k] = v;
		}, this);
		this.fireEvent('clickView', returnObj);
	},
	prev: function(){
		if(this.index > 0) this.clickTo(this.index-1);
	},
	next: function(){
		if(this.index < this.iL) this.clickTo(this.index+1);
	},
	stop: function(){
		$clear(this.autoPlay);
		this.isAutoPlay = false;
		this.fireEvent('autoStop');
	},
	play: function(){
		this.autoPlay = this.auto.periodical(this.options.interval, this);
		this.isAutoPlay = true;
		this.fireEvent('autoPlay');
	},
	auto: function(){
		if(this.index < this.iL) this.next();
		else if(this.index == this.iL) this.clickTo(0);
	},
	keyTo: function(e){
		switch (e.code){
			case 37: e.stop(); this.prev();	break;
			case 39: e.stop(); this.next();
		}
	},
	wheelTo: function(e){
		if(e.wheel > 0) this.prev();
		if(e.wheel < 0) this.next();
		e.stop().preventDefault();
	},
	clickTo: function(index){
		if(this.index == index) return;
		//this.aniFx.cancel();
		if(this.sli) this.sli.set(index);
		this.glideTo(index);
	},
	glideTo: function(index){
		this.index = index;
		this.aniFx.start(this.aniFx.get(), index*-this.foc);
		if(this.cap) this.cap.set('html', this.getCurrent().title);
	},
	process: function(x){
		var z,W,H,zI=this.iL,foc=this.foc,f=this.factor,sz=this.sz,oW=this.oW,offY=this.offY,div,elh,elw;
		this.master.images.each(function(el){
			div = el.div.style;
			elw = el.width;
			elh = el.height;
			if(x>-foc*6 && x<foc*6){
				with (Math) {
					z = sqrt(10000 + x * x) + 100;
					H = round((elh / elw * f) / z * sz);
					W = round(elw * H / elh);
					if(H >= elw * 0.5) {W = round(f / z * sz);}
					div.left = round(((x / z * sz) + sz) - (f * 0.5) / z * sz) + 'px';
					div.top = round(oW * 0.4 - H) + offY + 'px';
				}	
				el.con.style.height = H*2 + 'px';		
				div.width = W + 'px';
				div.zIndex = x < 0 ? zI++ : zI--;
				div.display = 'block';
			} else {
				div.display = 'none';
			}
			x += foc;
		});
	}
});

var SliderEx = new Class({
	Extends: Slider,
	set: function(step){
		this.step = Math.round(step);
		this.fireEvent('tick', this.toPosition(this.step));
		return this;
    },
	clickedElement: function(event){
		var dir = this.range < 0 ? -1 : 1;
		var position = event.page[this.axis] - this.element.getPosition()[this.axis] - this.half;
		position = position.limit(-this.options.offset, this.full -this.options.offset);
		this.step = Math.round(this.min + dir * this.toStep(position));
		this.checkStep();
		this.fireEvent('tick', position);
	}
});

Fx.Value = new Class({
	Extends: Fx,
	compute: function(from, to, delta){
		this.value = Fx.compute(from, to, delta);
		this.fireEvent('motion', this.value);
		return this.value;
	},
	get: function(){
		return this.value || 0;
	}
});

Element.implement({
	reflect: function(arg){
		var i = arg.img.clone().set('src', arg.img.src);
		if(Browser.Engine.trident){
			i.style.filter = 'flipv progid:DXImageTransform.Microsoft.Alpha(opacity=20, style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy='+100*arg.ref+')';
			i.setStyles({'width':'100%', 'height':'100%'});
			return new Element('div').adopt(i);
		} else {
			var can = new Element('canvas').setProperties({'width':arg.width, 'height':arg.height});
			if(can.getContext){
				var ctx = can.getContext("2d");
				ctx.save();
				ctx.translate(0,arg.height-1);
				ctx.scale(1,-1);
				try {
					ctx.drawImage(i, 0, 0, arg.width, arg.height);
				} catch(err) {}
				ctx.restore();
				ctx.globalCompositeOperation = "destination-out";
				ctx.fillStyle = arg.color;
				ctx.fillRect(0, arg.height*0.5, arg.width, arg.height);
				var gra = ctx.createLinearGradient(0, 0, 0, arg.height*arg.ref);					
				gra.addColorStop(1, "rgba(255, 255, 255, 1.0)");
				gra.addColorStop(0, "rgba(255, 255, 255, "+(1-arg.ref)+")");
				ctx.fillStyle = gra;
				ctx.rect(0, 0, arg.width, arg.height);
				ctx.fill();
				delete ctx, gra;
			}
			return can;
		}
	}
});


 var myMooFlowPage = {
 
 	start: function(){ 
 		milkbox = new Milkbox();
		var mf = new MooFlow($('MooFlow'), { 
			useSlider: true, 
			useCaption: true, 
			useMouseWheel: true, 
			useKeyInput: true, 
			useViewer: true, 
			useResize: false,
			onClickView: function(obj){
				milkbox.showThisImage(obj.href);
			} 
		}); 
	}
	
 }

window.addEvent('domready', function(){

	$$('.element').addEvent('click',function(){
		checkOnClick(this);
	});
	
	
	$$('.select_etape').addEvent('click',function(){
		switchStep(this, this.get('id'));
	});
	
	
	$$('#next_step').addEvent('click', function(){
		nextStep();
	});
	
	$$('#prev_step').addEvent('click', function(){
		prevStep();
	});
	
	$$('#next_fleche').addEvent('click', function(){
		nextStep();
	});
	
	$$('#prev_fleche').addEvent('click', function(){
		prevStep();
	});
	
	selectCur();
	if($('MooFlow'))
		myMooFlowPage.start();

	$$('#finalisation').addEvent('click',function(){
		if(checkSteps('total'))
			$('form_conception').submit();
		else
			alert("un ou plusieurs champs n'ont pas été renseignés, ou vous avez oublié de sélectionner un ou plusieurs éléments, veuillez vous reporter aux étapes concernées avant de continuer, merci");
	});
	
	if($('min') && $('max')){
	$('min').addEvent('keyup',function(){
		$('min').value = $('min').value.toInt();		
		if($('min').value == 'NaN')
			$('min').value = 0;
	});
	$('max').addEvent('keyup',function(){
		$('max').value = $('max').value.toInt();
		if($('max').value == 'NaN')
			$('max').value = 0;
	});
	}
});

