var Panier = new Class({
	options : {
		currency : '&euro;'
	},
	initialize : function(options){
		this.setOptions(options);
		
		this.panier = $('panier');
		this.totalPrice = 0;
		this.panier.totalPrice = this.panier.getElement('.prixTotal');
		
		this.panier.productLines = this.panier.getElements('tr.productLines');
		this.panier.productLines.each(function(line){
			//this.putRequested(line);
			this.panier.productLines.coeff = line.getElement('select.coeff')
			this.updateLine(this.panier.productLines.coeff, true);
		}.bind(this))
		this.updateBasketTotal();
		$$('.devise').each(function(devise){
			devise.innerHTML = this.options.currency;
		},this)
	},
	updateLine : function(elm, preventBasketUpdate){
		
		if (elm.value == 0) this.removeLine(elm);
		var line = getParent(elm, {nodeName:"tr", className:"productLines"});
		var productPrice = line.getElement('.prixProduit').getText().toFloat();
		var totalProductPrice = line.getElement('.prixTotalProduit');
		totalProductPrice.setText(elm.value * productPrice);
		
		if (!preventBasketUpdate) {this.updateBasketTotal();}
	},
	removeLine : function(elm){
		var line = getParent(elm, {nodeName:"tr", className:"productLines"});
		line.remove();
		this.updateBasketTotal();
	},
	noLine : function(lines){
		if (lines.length == 0){
			this.panier.getElement('.hiddenLine').removeClass('hiddenLine');
		}else{
			
		}
	},
	updateBasketTotal : function(){
		this.totalPrice = 0;
		this.panier.productLines = this.panier.getElements('tr.productLines');
		
		this.noLine(this.panier.productLines);
		
		this.panier.productLines.each(function(line){
			var price = line.getElement('.prixTotalProduit').getText();
			this.totalPrice += price.toFloat();
		}.bind(this))
		this.panier.totalPrice.setText(this.totalPrice);
	}
})

Panier.implement(new Options);

/*
@author : Florian Harmel
@params : options - object
			. width - number // Sert à ...
@methods : 
	- doUrl - void //
	- createElms
	- setMaskDimensions
	- 
*/
var PopIn = new Class({
	options : {
		width : 750
	},
	initialize : function(options){
		
		this.setOptions(options);
		this.page = $E('body');
		this.layer = $('layer');
		
		this.createElms();
		
		//gestion echap kbd
		this.escapeLayer();
		
		
		//gestion Envoyer a un ami
		this.sendTo();
		
		//check url pour ouvrir le layer eventuellement parametre
		this.doUrl();
	},
	doUrl : function(){
		var qString = document.location.search;
		var toUse = qString.substr(1,qString.length);
		var duos = toUse.split('&');
		var number = 0;
		var param = false;
		var sendToAlreadyOpened = false;
		duos.each(function(duo){
			var array = duo.split('=');
			identifiant = current_axs_id;
			if (array[0]=='sendToOpen'){
				sendToAlreadyOpened = array[1];
			}
		});
		//ouverture layer identifie dans url		
		var identifiant = $(identifiant);
		if (!identifiant) return;
		this.show(identifiant, sendToAlreadyOpened);
		update_form_query_string();
	},
	createElms : function(){
		//on met le layer dans body
		this.page.adopt(this.layer);
		
		this.mask = new Element('div',{'class':'popMask'}).setOpacity(0);
		this.page.adopt(this.mask);
		if(IS_IE){
			this.mask.iframe = new Element('iframe')
			this.mask.iframe.src = 'javascript:void(0)';
			this.mask.adopt(this.mask.iframe);
		}
	},
	setMaskDimensions : function(){
		var coord = {};
		coord.width = window.getScrollWidth();
		coord.height = window.getScrollHeight();
		this.mask.setStyles(coord);
		if (IS_IE){
			this.mask.iframe.setStyles(coord)
		};
	},
	updateLayerPosition : function(options){
		this.posX = window.getScrollLeft()+window.getWidth()/2 - this.options.width/2;
		this.posY = window.getScrollTop()+window.getHeight()/2 - this.layer.getSize().size.y/2;
		this.layer.setStyles({'left':this.posX,'top':this.posY,'width':this.options.width});
		//this.layer.effect('top',{duration:100}).start(this.posY);
		//this.layer.setStyles({'left':this.posX,'width':this.options.width});
	},
	populate : function(ref){
		this.contenuLayer = $(ref).getElement('.detailsContent').clone();
		this.contenuLayer.setStyle('display','block');
		this.contenuLayer.injectBefore(this.switchSentToAFriendLink);
		
	},
	unPopulate : function(){
		this.contenuLayer.remove();
	},
	show : function(ref, bool) {
		this.populate(ref);
		this.updateLayerPosition();
		this.setMaskDimensions();
		this.formElms = this.contenuLayer.getElements('select');
		if (bool == 'true') this.switchSendTo();
		this.layer.effect('opacity').start(1);
		this.mask.effect('opacity').start(0.7);
		//check scroll position to update popin position
		//init transition
		//if(!window.ie6)
		this.fxLayerFollowing = new Fx.Style(this.layer, 'top', {duration:400,wait:false});
		window.addEvent('scroll',function(e){
			//if(!window.ie6)
				this.fxLayerFollowing.start(window.getScrollTop()+window.getHeight()/2 - this.layer.getSize().size.y/2);
		}.bind(this))
		
	},
	escapeLayer : function(){
		document.addEvent('keydown', function(e){
			if (e.keyCode.toInt() == 27){
				if (this.secLayer.on) this.closeZoom();
				this.hide();
			}
		}.bind(this))
	},
	hide : function() {
		
		this.mask.effect('opacity',{duration:200,
			onStart : function(){
				if (this.switchSendTo.open == true) this.switchSendTo();
			}.bind(this),
			onComplete : function(){
				this.layer.effect('opacity').start(0);
				this.unPopulate();
			}.bind(this)
		}).start(0);
	},
	zoom : function(img){
		var _self = this;
		var imgSrc = img.src
		var imgUrl = imgSrc.split('/')[imgSrc.split('/').length - 1];
		var zoomedUrl = _zoomedImagesPrefix + imgUrl;
		var zoomedUrl = imgSrc.replace(new RegExp("\\b"+imgUrl+"\\b","g"), zoomedUrl)
		//creation masque
		//_self.contenuLayer.effect('').start(0);
		//recuperation de l'image
		this.secLayer = new Element('div');
		this.secLayer.className = 'cloneLayerInside';
		this.secLayer.innerHTML = '<a class="closeBox" onclick="return false;" href="#">Fermer</a>';
		this.layer.adopt(_self.secLayer);
		this.secLayer.setStyles({
			'height' : _self.contenuLayer.scrollHeight,
			'width' : _self.contenuLayer.scrollWidth,
			'opacity': 0
		})
		this.secLayer.effect('opacity', {
			duration : 300,
			onStart : function(){
				if (IS_IE){
					_self.formElms.each(function(formElm){
						formElm.addClass('invisible');
					})
				}
			},
			onComplete : function(){
				new Asset.image(zoomedUrl, {
					onload : function(){
						var image = this;
						//formattage et positionnement image
						image.setOpacity(0);
						image.className += 'zoomedImage';
						
						// do not force image size ! use natural size
						 var heighToUse = window.ie6 ? _self.secLayer.offsetHeight : _self.secLayer.scrollHeight;
						 image.setAttribute('height', heighToUse);
						
						//insertion image + effet;
						_self.secLayer.adopt(this);
						image.style.width = 'auto';
						_self.secLayer.on = true;
						this.effect('opacity').start(1);
					}
				})
			}
		}).start(1)
		this.secLayer.addEvent('click', function(e){
			new Event(e).stop();
			_self.closeZoom();
		});
	},
	closeZoom : function(){
		var _self = this;
		this.secLayer.effect('opacity', {
			onComplete : function(){
				_self.secLayer.remove();
				_self.secLayer.on = false;
				if (IS_IE){
					_self.formElms.each(function(formElm){
						formElm.removeClass('invisible');
					})
				}
			}
		}).start(0)
	},
	sendTo : function(){
		this.switchSentToAFriendLink = this.layer.getElement('.switchSentToAFriendLink');
		this.liens =this.switchSentToAFriendLink.getElements('a');
		this.sendToAFriend = this.layer.getElement('.sendToAFriend');
		this.sendToAFriendContent = this.sendToAFriend.getElement('.sendContent');
		//size it
		this.sendToAFriend.sizeY = this.sendToAFriend.getSize().size.y;
		this.sendToAFriendContent.setStyle('margin-top', -this.sendToAFriend.sizeY);
	},
	switchSendTo : function(){
		if (this.switchSendTo.open == true){
			this.sendToAFriendContent.effect('margin-top', {onComplete : function(){
				//if(!window.ie6)
					this.fxLayerFollowing.start(window.getScrollTop()+window.getHeight()/2 - this.layer.getSize().size.y/2);
				this.liens[1].addClass('hidden');
				this.liens[0].removeClass('hidden');
			}.bind(this)}).start(-this.sendToAFriend.sizeY);
			this.switchSendTo.open = false;
		}else{
			this.layer.effect('top', {onComplete : function(){
				this.sendToAFriendContent.effect('margin-top').start(0);
				this.liens[0].addClass('hidden');
				this.liens[1].removeClass('hidden');
			}.bind(this)}).start(window.getScrollTop()+window.getHeight()/2 - this.layer.getSize().size.y/2-this.sendToAFriend.sizeY/2);
			//on flag louverture
			this.switchSendTo.open = true;
		}
	}
});
PopIn.implement(new Options)

var TipsMerch = new Class({
	initialize : function(){
		this.tds = $$('.tipIt');
		this.bloc = $('panier');
		
		this.tds.each(function(td){
			td.addEvent('mouseenter',function(){
				this.show(td);
			}.bind(this))
			td.addEvent('mouseleave',function(){
				this.hide(td);
			}.bind(this))
		}.bind(this))
		
		this.div = new Element('div').injectInside($('page'))
		.addClass('clonedTipBoxLayer')
		.setStyles({
			opacity:0,
			display:'block'
		});
		
		ifrlayer.make(this.div);
		
		this.opac = new Fx.Styles(this.div, {duration: 100, transition: Fx.Transitions.linear});
		this.opac2 = new Fx.Styles(this.div, {duration: 100, transition: Fx.Transitions.linear, onComplete:function(e){
			ifrlayer.hide(e);
		}});
	},
	show : function(td){
		this.div.empty();
		this.doClone(td);
		this.posIt(td);
		this.clone.setStyle('display','block');
		ifrlayer.make(this.div);
		this.opac.start({
		    'opacity': 1
		});
		$clear(this.time);
	},
	hide : function(td){
		this.time = (function(){
			this.opac2.start({
			    'opacity': 0
			});
		}).delay(500,this)
	},
	posIt : function(td){
		if (this.div.getCoordinates().bottom >= document.documentElement.clientHeight){
			this.div.setStyle('top', td.getCoordinates().bottom - this.div.offsetHeight)
		}
		if((td.getCoordinates().right - this.bloc.getLeft()) + this.div.offsetWidth > this.bloc.offsetWidth){
			this.div.setStyle('left', td.getLeft() - $('page').getLeft() - this.div.offsetWidth)
		}else{
			this.div.setStyle('left', td.getCoordinates().right - $('page').getLeft())
		}
	},
	doClone : function(td){
		this.layer = td.getElement('.tipBoxLayer');
		this.clone = this.layer.clone();
		this.clone.injectInside(this.div);
		this.div.setStyle('top', td.getTop());
	},
	delClone :function(){
		this.clone.remove();
	}
	
})


var BrandCriterias = new Class({
	initialize : function(){
		this.criterias = $('refineBrand').getElements('ul li input');
		//on ne prends pas en compte le dernier qui est le all
		this.criterias.pop();
	},
	selectAll : function(elm){
		if (elm.checked){
			//si checké unset allet uncheck elm
			this.setAllStatus();
		}else{
			//si non chécké set all et check elm
			this.unsetAllStatus();
		}
	},
	setAllStatus : function(){
		//itere chaque elements
		this.criterias.each(function(criteria){
			//enregistre etat before sur chaque elms
			criteria.checkedStatus = criteria.checked;
			//on les sélectionne tous
			criteria.checked = true;
			criteria.disabled = true;
			//on les mets en gris
			criteria.getParent().addClass('disabled');
		})
	},
	unsetAllStatus : function(){
		//itere chaque elements
		this.criterias.each(function(criteria){
			//recover etat before sur chaque elms
			criteria.checked = criteria.checkedStatus;
			criteria.disabled = false;
			//reprise de la couleur initiale les en normal
			criteria.getParent().removeClass('disabled');
		})
		
	}
})


function addFF2Class(){
	if(window.navigator.userAgent.match('Firefox/2'))
		$('page').addClass('IS_FF2');
	
}


var AjaxJspRefresh = new Class({
	initialize : function(urlJSP, id){
		this.oRefreshedPlace = $(id);
		this.url = urlJSP;
		//firstCall
		this.locate = document.location;
		//this.refresh();
	},
	refresh : function(params){
		var _self = this;
		this.locate = document.location;
		this.oParams = params ? params : this.getParams();
		this.oParams['q'] = getSearchString();
		this.oParams['ps'] = current_page_size;
		this.oParams['orderType'] = current_search_order;
		
//console.log('init')
		/*console.log(oParams.indexOf('u'))
		if (oParams.indexOf('#') < 0){
			oParams = oParams;
		}else{
			oParams = oParams.replace
		}*/
		      
		var myXHR = new Ajax(this.url, {
			method: 'get',
			onRequest : function()
			{
				_self.setLoader();
			},
			onSuccess : function(response){
				_self.onSuccess(response);
			},
			onComplete : function(){
				nedstat_trigger(currentMode, getCategoryId(), getCleanedSearchString());
				if (_self.oParams['navClick'])
					goToElement('zoneRecherche');
				_self.unsetLoader();
				//_self.urlInscription(oParams);
				popup.doUrl();
			}
		
		}).request(_self.oParams);
		
	},
	onSuccess : function(response){
		var _self = this;
        _self.oRefreshedPlace.setHTML(response);
	},
	getParams : function(){
		var hash = this.locate.hash;
		hash = hash.split('#')[1];
		return hash;
	},
	setLoader : function(){
		//alert('setloader');
        //$('loaderZone').addClass('loader');
	},
	unsetLoader : function(){
		//$('loaderZone').removeClass('loader');
	    //alert('unsetLoader');
    },
	urlInscription : function(oParams){
		var query;
		if (typeof oParams == 'string'){
			
		}else if(typeof oParams == 'object'){
			query =  Object.toQueryString(oParams);
		}
		this.locate.hash = query;
	}
});


var goToElement = function(sId){
	var scroll = new Fx.Scroll(window, {
		wait: true,
		duration: 1500
	});
	scroll.toElement($(sId))
}