

//Impression de composite, Copyright (c) 2008 StudioArteme.com.
window.addEvent('domready', function(){
	$$('#composite h4').addEvent('click', function(){
		comp = this.getParent();
		h = (comp.hasClass('on')) ? 17 : 155;
		comp.set('tween', {duration: 'short', onComplete:function(){ comp.toggleClass('on'); }});
		comp.tween('height', h);
	});
	if(Browser.Engine.trident4) {
		sfHover('#composite h4');
		$('composite').addEvents({
			'mouseenter': function(){
				$('composite').addClass('sfhover');
			},
			'mouseleave': function(){
				$('composite').removeClass('sfhover');
			}
		});
	}
	function addImage(imgElement,imgID){
		var comp = $('composite');
		if(compImages.length==$$('#composite div.image').length) newPage();
		goToPage($$('#composite div.image').length/6);
		var imgDiv = $$('#composite div.image:nth-child('+(compImages.length+1)+')');
		var imgClone = imgElement.clone();
		imgClone.set('id', 'c'+imgID);
		imgDiv.store('tip:title', txt_retirer);
		imgClone.addEvents({
			'click': function(){
				removeImage(imgID);
				if($chk($(imgID))) $(imgID).toggleClass('del');
			},
			'mouseover': function(){
				this.setStyle('cursor', 'url(images/ico_handdel.gif), pointer');
			}
		});
		$(imgID).store('tip:title', txt_retirer);
		imgDiv.grab(imgClone);
		
		if(!comp.hasClass('on')) {
			comp.set('tween', {duration: 'short', onComplete:function(){ comp.toggleClass('on'); }});
			comp.tween('height', 155);
		}
		compImages.push(imgID);
		updateCompCookie()
		if(compImages.length==1) {
			$('printcomposite').setStyle('display', 'block');
			compTips.attach($('printcomposite'));
			$('printcomposite').store('tip:text', '');
		}
	}
	function removeImage(imgID) {
		var imgContainer = $('c'+imgID).getParent();
		var removedImg = imgContainer.dispose();
		var newImgDiv = new Element('div', {'class': 'image', 'title': txt_ajouter2});
		newImgDiv.inject($$('#composite div.page')[0]);
		compImages.erase(imgID);
		updateCompCookie();
		if(compImages.length==0) $('printcomposite').setStyle('display', 'none');
		if($chk($(imgID))) $(imgID).store('tip:title', txt_ajouter);
		if(totalPages>1)
			if(($$('#composite div.image').length-6)==compImages.length) removePage();
	}
	function newPage(){
		var after = $$('#composite div.image:nth-child('+($$('#composite div.image').length)+')')[0];
		for(i=0;i<6;i++) {
			var newImgDiv = new Element('div', {'class': 'image'});
			newImgDiv.set('title', txt_ajouter2);
			newImgDiv.inject(after, 'after');
			compTips.attach(newImgDiv);
		}
		totalPages++;
		if(totalPages == 2) updatePagination();
	}
	function removePage(){
		for(i=0;i<6;i++) {
			var removedImgDiv = $$('#composite div.image:last-child')[0].dispose();
		}
		totalPages--;
		goToPage(totalPages);
	}
	function updatePagination() {
		$('previousPage').fade(((currentPage)==1)?'hide':'show');
		$('nextPage').fade(((currentPage+1)>totalPages)?'hide':'show');
		$('pageNum').set('text', ' page '+currentPage+' ');
	}
	function nextPage() {
		goToPage(currentPage+1);
	}
	function previousPage() {
		goToPage(currentPage-1);
	}
	function goToPage(page) {
		$$('#composite div.page')[0].scrollTo(0, (page-1)*72);
		currentPage = page;
		updatePagination();
	}
	function loadAddDeleteEvents() {
		$$('a.grande', '#images a[rel^=milkbox]').addEvents({
			'mouseenter': function(){
				this.getFirst('span.ad').setStyle('display', 'block');
			},
			'mouseleave': function(){
				this.getFirst('span.ad').setStyle('display', 'none');
			}
		});
		$$('span.ad').addEvents({
			'mouseenter':function(){
				this.setStyle('cursor', 'pointer');
			},
			'click': function(e){
				e.stop();
				this.getParent().blur();
				imgID = this.get('id');
				if(compImages.contains(imgID)) removeImage(imgID);
				else addImage(this.getPrevious('img'),imgID);
				this.toggleClass('del');
			}
		});
		if(Browser.Engine.trident4) {
			$$('a.grande span', '#images a[rel^=milkbox] span').addEvents({
				'mouseenter': function(){
					this.setStyle('backgroundPosition', (this.hasClass('del')) ? '-48px 0px' : '-16px 0px');
				},
				'mouseleave': function(){
					this.setStyle('backgroundPosition', (this.hasClass('del')) ? '-32px 0px' : '0px 0px');
				}
			});
		}
	}
	function updateCompCookie(){
		var objCookie = new Hash.Cookie('composites');
		objCookie.set(prod_id, compImages.toString());
	}
	function checkCompCookie(){
		var objCookie = new Hash.Cookie('composites');
		if(objCookie.has(prod_id) && objCookie.get(prod_id) != "") {
			//model trouvé
			$('composite').set('tween', {duration: 'short', onComplete:function(){ $('composite').toggleClass('on'); }});
			$('composite').tween('height', 155);
			
			compImages = objCookie.get(prod_id).split(",");
			$('printcomposite').setStyle('display', 'block');
			compTips.attach($('printcomposite'));
			$('printcomposite').store('tip:text', '');
			
			//Création pages
			currentPage = totalPages = 1;
			if(compImages.length>6) {
				do {
					newPage();
					currentPage = totalPages;
				} 
				while(currentPage<Math.ceil(compImages.length/6));
				goToPage(totalPages);
			}
			//remplissage pages
			var imgsAvail = compImages.filter(function(item){
				return $chk($(item));
			});
			compImages.each(function(imgID){
				var imgDiv = $$('#composite div.image:nth-child('+(compImages.indexOf(imgID)+1)+')');
				if(imgsAvail.contains(imgID)) {
					//deja sur la page
					var imgClone = $(imgID).getPrevious('img').clone();
					imgClone.set('id', 'c'+imgID);
					imgDiv.store('tip:title', txt_retirer);
					imgClone.addEvents({
						'click': function(){
							removeImage(imgID);
							if($chk($(imgID))) $(imgID).toggleClass('del');
						},
						'mouseover': function(){
							this.setStyle('cursor', 'url(images/ico_handdel.gif), pointer');
						}
					});
					$(imgID).addClass('del');
					$(imgID).store('tip:title', txt_retirer);
					imgDiv.grab(imgClone);
				} else {
					//pas sur la page, pas grave on récupère le nom du fichier en JSON
					imgDiv.setStyle('background', '#FFF url(images/butterfly.gif) no-repeat center center');
				}
			});
			var imgsUnavail = compImages.filter(function(item){
				return !$chk($(item));
			});
			var idsUnavail = imgsUnavail.map(function(item){
				return item.substr(3);
			}).toString();
			if(imgsUnavail.length>0) {
				var jsonRequest = new Request.JSON({url: "mannequin_images_json.php", onComplete: function(fichiers){
					var hashFichiers = new Hash(fichiers);
					images_path = 'client/gfx/photos/produit/';
					hashFichiers.each(function(fichier, id) {
						imgID = 'img'+id;
						var imgDiv = $$('#composite div.image:nth-child('+(compImages.indexOf(imgID)+1)+')');
						var newImg = new Element('img', {'src': images_path + fichier});
						newImg.set('id', 'c'+imgID);
						imgDiv.store('tip:title', txt_retirer);
						newImg.addEvents({
							'click': function(){
								realImgID = this.get('id').substr(1);
								removeImage(realImgID);
								if($chk($(realImgID))) $(realImgID).toggleClass('del');
							},
							'mouseover': function(){
								this.setStyle('cursor', 'url(images/ico_handdel.gif), pointer');
							}
						});
						imgDiv.grab(newImg);
					});
				}}).post({'imgs': idsUnavail});
			}									   
		} else {
			compImages = [];
			currentPage = totalPages = 1;
		}
	}
	
	tipsItems = $$('span.ad', '#composite div.image');
	var compTips = new Tips(tipsItems, {
		showDelay: 300,
		className: 'compTips',
		offsets: {x: 11, y: 23}
	});
	tipsItems.store('tip:text', '');
	
	loadAddDeleteEvents();
	loadImagePagesEvents($$('#images div.pages a'));
	$('nextPage').addEvent('click', nextPage);
	$('previousPage').addEvent('click', previousPage);
	var compImages, currentPage, totalPages;
	checkCompCookie();
	updatePagination();
	function loadImagePagesEvents(links){
		links.addEvent('click', function(e){
			e.stop();
			theLink = this;
			url = this.href;
			img = url.substr((url.lastIndexOf("=")+1),1);
			prod = prod_id;
			updateDiv = $$('#images div.page')[0];
			var myRequest = new Request.HTML({ 
				url:'mannequin_images.php', 
				update:updateDiv,
				onComplete:function(){
					$$('a.grande span.ad')[0].removeEvents('click');
					loadAddDeleteEvents();
					$$('#images a[rel^=milkbox] span').each(function(el){
						imgID = el.get('id');
						if(compImages.contains(imgID)) {
							el.toggleClass('del');
							el.store('tip:title', txt_retirer);
						}
						compTips.attach(el);
					});
					var oldSpan = $$('#images div.pages span.current')[0];
					var newLink = new Element('a',  {
						'href': '?img='+oldSpan.get('text').trim(),
						'html': oldSpan.get('text')
					});
					var newSpan = new Element('span',  {
						'class': 'current',
						'html': theLink.get('text')
					});
					newSpan.replaces(theLink);
					newLink.replaces(oldSpan);
					loadImagePagesEvents(newLink);
					Milkboite = null;
					$$('a[rel^=milkbox]', 'a[rel^=milkbox] img').each(function(el){
						el.removeEvents('click');
					});
					Milkboite = new Milkbox();
				}
			}).post({'img': img, 'prod_id': prod});
		});
	}
	Milkboite = new Milkbox();
	$('printcomposite').addEvent('click', function(){
		if(compImages.length>0) {
			this.target = '_blank';
			this.href = "composite.php?action=imprimer&model_id="+prod_id+"&imgs="+compImages.toString()+"&lang="+lang;
		} else e.stop();
	});
	//tips pola defile
	var toolsTips = new Tips("#tools h4 a", {
		hideDelay: 0,
		className: 'toolsTips',
		offset: {x: -12, y: -32},
		fixed: true,
		title: function(tip) { return tip.get('rev'); }
	});
});
