/**
 * Script:	Qattern
 * Author:	Quentin T
 * URL:		http://toki-woki.net
*/
var sel=document.selectedItems;
if (sel.length>1) {
	var limits;
	var objects=[];
	for (var i=0; i<sel.length; i++) {
		var o=sel[i];
		if (o.style.fill.color==null && o.style.stroke.color==null) limits=o;
		else objects.push(o);
	}
	if (limits) {
		var g=new Group();
		g.appendChild(limits.clone());
		var lb=limits.bounds;
		for (var i=0; i<objects.length; i++) {
			var o=objects[i].clone();
			g.appendChild(o);
			// On ne s'intéresse qu'aux objets qui touchent les limites
			var ob=o.bounds;
			var touchedTop=false;
			var touchedBottom=false;
			var touchedLeft=false;
			var touchedLeft=false;
			// Les limites horizontales
			if (ob.right>lb.left && ob.left<lb.right) {
				// Les objets sur la barre du haut
				if (ob.bottom<lb.top && ob.top>lb.top) {
					handleClone(o, 0, -lb.height);
					touchedTop=true;
				}
				// La barre du bas
				if (ob.bottom<lb.bottom && ob.top>lb.bottom) {
					handleClone(o, 0, lb.height);
					touchedBottom=true;
				}
			}
			// Les limites verticales
			if (ob.bottom<lb.top && ob.top>lb.bottom) {
				// La barre gauche
				if (ob.left<lb.left && ob.right>lb.left) {
					handleClone(o, lb.width, 0);
					var touchedLeft=true;
				}
				// La barre droite
				if (ob.left<lb.right && ob.right>lb.right) {
					handleClone(o, -lb.width, 0);
					var touchedRight=true;
				}
			}
			// L'objet touchait les 2 axes, il faut le dupliquer ŕ nouveau !
			if (touchedTop && touchedLeft) {
				handleClone(o, lb.width, -lb.height);
			} else if (touchedTop && touchedRight) {
				handleClone(o, -lb.width, -lb.height);
			} else if (touchedBottom && touchedLeft) {
				handleClone(o, lb.width, lb.height);
			} else if (touchedBottom && touchedRight) {
				handleClone(o, -lb.width, lb.height);
			}
		}
		document.deselectAll();
	} else {
		Dialog.alert("You also need to select a blank rectangle (no fill, no stroke) to be used as the pattern's limits!");
	}
}
function handleClone(o, tx, ty) {
	var copy=o.clone();
	copy.translate(tx, ty);
	g.appendChild(copy);
}
