AddCss('/view/canvasResizer.css');

const resizeMinGap = 20; //%

var CanvasResizer = function(canvas) {
	var leftMover = D.div({cls: 'canvas-resizer--mover canvas-resizer--mover-left'});
	var rightMover = D.div({cls: 'canvas-resizer--mover canvas-resizer--mover-right'});
	var els = [leftMover, rightMover];
	var position = [0, 100];
	canvas.addEventListener('mousedown', function(e) {
		var percent = e.offsetX/e.currentTarget.clientWidth*100,
				moving;
		if(percent<position[0]){
			moving = 0;
		}else if(percent>position[1]){
			moving = 1;
		}else{
			moving = Math.abs(position[0] - percent) < Math.abs(position[1] - percent) ? 0 : 1;
		}
		var rect = D.getRect(canvas);

		var move = function(e) {
			var percent = ((e.clientX-rect.left)/(rect.width)*100);
			percent = Math.min(percent, 100);
			percent = Math.max(percent, 0);

			if(moving === 0){
				percent = Math.min(position[1]-resizeMinGap, percent);
			}

			if(moving === 1){
				percent = Math.max(position[0]+resizeMinGap, percent);
			}

			position[moving] = ((percent*10)|0)/10;

			els[0].style.width = position[0]+'%';
			els[1].style.width = (100-position[1])+'%';

			e.preventDefault();
			e.stopPropagation();
		};
		var up = function(e) {
			document.removeEventListener('mousemove', move);
			document.removeEventListener('mouseup', up);
			e.preventDefault();
			e.stopPropagation();
		}
		document.addEventListener('mousemove', move);
		document.addEventListener('mouseup', up);
	});

	var dom = D.div({cls: 'canvas-resizer'}, canvas, leftMover, rightMover);
	canvas.position = position;
	return dom;
}