

var viewport = {x:0,y:0,width:600,height:400};
var zoom = 1;
var paintsize = {width:600,height:400};
var svg_source = "";

if (typeof printNode=='undefined') {
printNode= function (el) {
   return (new XMLSerializer()).serializeToString(el);
};
}

function parseSVG(str) {
  str = '<g xmlns="http://www.w3.org/2000/svg">' + str + '</g>';
  return new DOMParser().parseFromString(str, "text/xml").childNodes[0];
}

function load_source(source)
{
	jQuery(parseSVG(source)).appendTo(jQuery('svg'));
}

//functions to get mouse position in all browsers
function getMousePageX(e)
{
	var posx = 0;
	var isOpera = (navigator.userAgent.indexOf('Opera') != -1);
	var isIE = (!isOpera && navigator.userAgent.indexOf('MSIE') != -1)

	if (!e) var e = window.event;
	if (e.pageX)
	{
		posx = e.pageX;
	}
	else if (e.clientX)
	{
		posx = e.clientX;
		if (isIE)
		{
			posx += document.body.scrollLeft;
		}
	}
	return posx;
}

function getMousePageY(e)
{
	var posy = 0;
	var isOpera = (navigator.userAgent.indexOf('Opera') != -1);
	var isIE = (!isOpera && navigator.userAgent.indexOf('MSIE') != -1)

	if (!e) var e = window.event;
	if (e.pageY)
	{
		posy = e.pageY;
	}
	else if (e.clientY)
	{
		posy = e.clientY;
		if (isIE)
		{
			posy += document.body.scrollTop;
		}
	}
	return posy;
}


function getMouseX(evt) {
	var a = jQuery("#paint").offset().left;//10;//jQuery("svg").offset().left;
	var b = paintsize.width;
	var c = viewport.width;
	var d = c / b;
	var e  = viewport.x;
	
	
	return (getMousePageX(evt) - a)*d+ e;
	
}

function getMouseY(evt) {
	var a = jQuery("#paint").offset().top;//20;//jQuery("svg").offset().top;
	var b = paintsize.height;
	var c = viewport.height;
	var d = c / b;
	var e  = viewport.y;
	
	return (getMousePageY(evt) - a )*d+ e;
}
//########################


// <tools>
function Tool_pen()
{
	this.element = null;
	this.currentpath = "";
	this.prev_x;
	this.prev_y;
}

Tool_pen.prototype.onMouseDown = function(event)
{
	var x = getMouseX(event);
	var y = getMouseY(event);
	var svg = jQuery('#paint').svg('get');	
		
	setSmoothPos(x,y);
	this.currentpath = "M"+x+","+y;
	this.element = svg.path(this.currentpath,  {'stroke-linejoin': 'round','stroke-linecap': 'round','stroke-opacity': currentopacity, 'fill-opacity': currentbackopacity, fill: 'none', stroke: currentcolor, 'stroke-width': currentwidth});
	this.prev_x = x;
	this.prev_y = y;
}

Tool_pen.prototype.onMouseMove = function(event)
{
	var x = getSmoothMouseX(event);
	var y = getSmoothMouseY(event);
	var minlen = currentwidth*currentwidth/10;
	var len = (x-this.prev_x)*(x-this.prev_x) + (y-this.prev_y)*(y-this.prev_y);
	
	if (minlen < len)
	{
		this.currentpath +="L"+x+","+y;
		this.element.setAttributeNS(null,"d",this.currentpath);
		this.prev_x = x;
		this.prev_y = y;
	}
}

Tool_pen.prototype.onMouseUp = function(event)
{
	var x = getSmoothMouseX(event);
	var y = getSmoothMouseY(event);
	var svg = jQuery('#paint').svg('get');	
	
	this.currentpath +="L"+x+","+y;
	this.element.setAttributeNS(null,"d",this.currentpath);	
	this.element = null;	
}


function Tool_polygon()
{
	this.element = null;
	this.currentpoints = "";
	this.prev_x;
	this.prev_y;
}

Tool_polygon.prototype.onMouseDown = function(event)
{
	var x = getMouseX(event);
	var y = getMouseY(event);
	var svg = jQuery('#paint').svg('get');	
		
	setSmoothPos(x,y);
	this.currentpoints = x+" "+y;
	this.element = svg.polygon([[x,y],[x+1,y+1]],  {'stroke-linejoin': 'round','stroke-linecap': 'round', 'stroke-opacity': currentopacity, 'fill-opacity': currentbackopacity, stroke: currentcolor, 'stroke-width': currentwidth, fill: currentbackcolor});
	this.prev_x = x;
	this.prev_y = y;
}

Tool_polygon.prototype.onMouseMove = function(event)
{
	var x = getSmoothMouseX(event);
	var y = getSmoothMouseY(event);
	var minlen = currentwidth*currentwidth/10;
	var len = (x-this.prev_x)*(x-this.prev_x) + (y-this.prev_y)*(y-this.prev_y);
	
	if (minlen < len)
	{
		this.currentpoints +=" "+x+" "+y;
		this.element.setAttributeNS(null,"points",this.currentpoints);
		this.prev_x = x;
		this.prev_y = y;
	}
}

Tool_polygon.prototype.onMouseUp = function(event)
{
	var x = getSmoothMouseX(event);
	var y = getSmoothMouseY(event);
	var svg = jQuery('#paint').svg('get');	
	
	this.currentpoints +=" "+x+" "+y;
	this.element.setAttributeNS(null,"points",this.currentpoints);
	this.element = null;	
}

function Tool_line()
{
	this.element = null;
}

Tool_line.prototype.onMouseDown = function(event)
{
	var x = getMouseX(event);
	var y = getMouseY(event);
	var svg = jQuery('#paint').svg('get');
	
	this.element = svg.line(x,y,x+1,y+1,{'stroke-opacity': currentopacity, 'fill-opacity': currentbackopacity, stroke: currentcolor, 'stroke-width': currentwidth});
}

Tool_line.prototype.onMouseMove = function(event)
{
	this.element.setAttributeNS(null,"x2",getMouseX(event));
	this.element.setAttributeNS(null,"y2",getMouseY(event));
}

Tool_line.prototype.onMouseUp = function(event)
{
	this.element.setAttributeNS(null,"x2",getMouseX(event));
	this.element.setAttributeNS(null,"y2",getMouseY(event));
	this.element = null;
}

function Tool_ellipse()
{
	this.element = null;
	this.cx = 0;
	this.cy = 0;
}

Tool_ellipse.prototype.onMouseDown = function(event)
{
	var x = getMouseX(event);
	var y = getMouseY(event);
	var svg = jQuery('#paint').svg('get');
	this.cx = x;
	this.cy = y;
	this.element = svg.ellipse(x,y,1,1,{'stroke-opacity': currentopacity, 'fill-opacity': currentbackopacity, stroke: currentcolor, 'stroke-width': currentwidth, fill: currentbackcolor});
}

Tool_ellipse.prototype.onMouseMove = function(event)
{
	this.element.setAttributeNS(null,"rx",Math.abs(getMouseX(event)-this.cx));
	this.element.setAttributeNS(null,"ry",Math.abs(getMouseY(event)-this.cy));
}

Tool_ellipse.prototype.onMouseUp = function(event)
{
	this.element.setAttributeNS(null,"rx",Math.abs(getMouseX(event)-this.cx));
	this.element.setAttributeNS(null,"ry",Math.abs(getMouseY(event)-this.cy));
	this.element = null;
}

function Tool_rect()
{
	this.element = null;
	this.cx = 0;
	this.cy = 0;
}

Tool_rect.prototype.onMouseDown = function(event)
{
	var x = getMouseX(event);
	var y = getMouseY(event);
	var svg = jQuery('#paint').svg('get');
	this.cx = x;
	this.cy = y;
	this.element = svg.rect(x,y,1,1,{'stroke-opacity': currentopacity, 'fill-opacity': currentbackopacity, stroke: currentcolor, 'stroke-width': currentwidth, fill: currentbackcolor});
}

Tool_rect.prototype.onMouseMove = function(event)
{
	var x = getMouseX(event);
	var y = getMouseY(event);
	if (x < this.cx)
	{
		this.element.setAttributeNS(null,"x",x);
		this.element.setAttributeNS(null,"width",this.cx-x);
	}
	else
	{
		this.element.setAttributeNS(null,"x",this.cx);
		this.element.setAttributeNS(null,"width",x-this.cx);
	}
	if (y < this.cy)
	{
		this.element.setAttributeNS(null,"y",y);
		this.element.setAttributeNS(null,"height",this.cy-y);
	}
	else
	{
		this.element.setAttributeNS(null,"y",this.cy);
		this.element.setAttributeNS(null,"height",y-this.cy);
	}
}

Tool_rect.prototype.onMouseUp = function(event)
{
	var x = getMouseX(event);
	var y = getMouseY(event);
	if (x < this.cx)
	{
		this.element.setAttributeNS(null,"x",x);
		this.element.setAttributeNS(null,"width",this.cx-x);
	}
	else
	{
		this.element.setAttributeNS(null,"x",this.cx);
		this.element.setAttributeNS(null,"width",x-this.cx);
	}
	if (y < this.cy)
	{
		this.element.setAttributeNS(null,"y",y);
		this.element.setAttributeNS(null,"height",this.cy-y);
	}
	else
	{
		this.element.setAttributeNS(null,"y",this.cy);
		this.element.setAttributeNS(null,"height",y-this.cy);
	}
	this.element = null;
}


function Tool_text()
{
	this.element = null;
	this.dummyinput = null;
}
var lasttext = null;

Tool_text.prototype.onMouseDown = function(event)
{
	var x = getMouseX(event);
	var y = getMouseY(event);
	var svg = jQuery('#paint').svg('get');
	
	//delete old stuff
	if (this.dummyinput != null)
	{
		jQuery(this.dummyinput).remove();
	}
	
	this.element = svg.text(x,y,"",{'fill-opacity': currentopacity, fill: currentcolor,'font-size': (10*currentwidth)});
	lasttext = this.element;
	this.dummyinput = jQuery("<input>").appendTo("#Tools_Paint")
		.attr("id","dummy_input")
		.attr("style","")
		.focus()
		.keydown(function()
		{
			window.setTimeout(function()
			{
				jQuery(lasttext).text(jQuery("#dummy_input").attr("value"));
			},1);
		}		
		);
}

Tool_text.prototype.onMouseMove = function(event)
{
	
}

Tool_text.prototype.onMouseUp = function(event)
{
	
}

Tool_text.prototype.onDeselect = function(event)
{
	if (this.dummyinput != null)
	{
		jQuery(this.dummyinput).remove();
	}
}


function Tool_image()
{
	this.element = null;
	this.cx;
	this.cy;
	this.href;
	this.status = 0;
}


Tool_image.prototype.onMouseDown = function(event)
{
	var x = getMouseX(event);
	var y = getMouseY(event);
	var svg = jQuery('#paint').svg('get');
	
	var imgratio = 1.0;
	
	if (this.status == 0)
	{
		
		this.cx = x;
		this.cy = y;
		
		this.href = window.prompt("Geben Sie Die Adresse zum Bild ein:");
		
		var newImg = new Image();
		newImg.src = this.href;
		if (newImg.height > 0) {
			this.ratio = newImg.width / newImg.height;
			//alert("ratio = " + this.ratio);
			
			this.element = svg.image(x,y,1,1,this.href,{'opacity': currentopacity, 'fill' : '#ffcc00'});
			
			/*jQuery(this.element).click = function (event) {
				alert("oO");
				event.preventDefault();
				return false;
			};*/
			
			
			
			this.status = 1;
		} else {
			alert("Kein gültiges Bild.");
			this.status = 0;
		}
	}
	else
	{
		this.cx = x;
		this.cy = y;
		
		this.cover = svg.rect(x,y,1,1,{'stroke-opacity': 0, 'fill-opacity': 0});

		
		this.status = 2;
	}
	
}

Tool_image.prototype.onMouseMove = function(event)
{
	if (this.status == 2)
	{
		var x = getMouseX(event);
		var y = getMouseY(event);
		
		var width = this.cx-x;
		var height = this.cy-y;
		var ratio = width / height;
		
		if (this.ratio < ratio) {
			width = Math.abs(this.cx-x);
			height = width / this.ratio;
		} else {
			height = Math.abs(this.cy-y);
			width = height * this.ratio;
		}		
		
		if (x < this.cx) {
			this.element.setAttributeNS(null,"x",x);
		} else 	{
			this.element.setAttributeNS(null,"x",this.cx);
		}
		if (y < this.cy) {
			this.element.setAttributeNS(null,"y",y);
		} else {
			this.element.setAttributeNS(null,"y",this.cy);
		}
		this.element.setAttributeNS(null,"width",width);
		this.element.setAttributeNS(null,"height",height);
	}
}

Tool_image.prototype.onMouseUp = function(event)
{
	if (this.status == 2)
	{
		var x = getMouseX(event);
		var y = getMouseY(event);
		
		var width = this.cx-x;
		var height = this.cy-y;
		var ratio = width / height;
		
		if (this.ratio < ratio) {
			width = Math.abs(this.cx-x);
			height = width / this.ratio;
		} else {
			height = Math.abs(this.cy-y);
			width = height * this.ratio;
		}		
		
		if (x < this.cx) {
			this.element.setAttributeNS(null,"x",x);
			this.cover.setAttributeNS(null,"x",x);
		} else 	{
			this.element.setAttributeNS(null,"x",this.cx);
			this.cover.setAttributeNS(null,"x",this.cx);
		}
		if (y < this.cy) {
			this.element.setAttributeNS(null,"y",y);
			this.cover.setAttributeNS(null,"y",y);
		} else {
			this.element.setAttributeNS(null,"y",this.cy);
			this.cover.setAttributeNS(null,"y",this.cy);
		}
		this.element.setAttributeNS(null,"width",width);
		this.cover.setAttributeNS(null,"width",width);
		this.element.setAttributeNS(null,"height",height);
		this.cover.setAttributeNS(null,"height",height);
		this.status = 0;
	}
}

Tool_image.prototype.onDeselect = function(event)
{
	if (this.dummyinput != null)
	{
		jQuery(this.dummyinput).remove();
	}
}

function Tool_curve()
{
	this.element = null;
	this.currentpath = "";
	this.s_x;
	this.s_y;
	this.a_x;
	this.a_y;
	this.b_x;
	this.b_y;
	this.status=0;
	this.helperpath;
	this.currenthelperpath;
}

Tool_curve.prototype.onMouseDown = function(event)
{
	var x = getMouseX(event);
	var y = getMouseY(event);
	var svg = jQuery('#paint').svg('get');	
	if (this.status == 0)
	{	
		this.s_x = x;
		this.s_y = y;
		this.currentpath = "M"+x+","+y;
		this.element = svg.path(this.currentpath,  {'stroke-linejoin': 'round','stroke-linecap': 'round','stroke-opacity': currentopacity, 'fill-opacity': currentbackopacity, fill: 'none', stroke: currentcolor, 'stroke-width': currentwidth});
		this.currenthelperpath = "M"+x+","+y;
		this.helperpath = svg.path(this.currenthelperpath,  {'stroke-linejoin': 'round','stroke-linecap': 'round','stroke-opacity': .5, fill: 'none', stroke: "#000000", 'stroke-width': Math.round(currentwidth/2)});
		this.status = 1;
	}
	else if (this.status == 1)
	{
		this.status = 2;
		this.a_x = x;
		this.a_y = y;
		this.currenthelperpath += "L"+x+" "+y;
		this.helperpath.setAttributeNS(null,"d",this.currenthelperpath);	
	}
	else if (this.status == 2)
	{
		this.status = 3;
		this.b_x = x;
		this.b_y = y;
		this.currenthelperpath += "L"+x+" "+y;
		this.helperpath.setAttributeNS(null,"d",this.currenthelperpath);
	}
	else if (this.status == 3)
	{
		this.status = 1;
		this.currentpath += "C"+this.a_x+" "+this.a_y+" "+this.b_x+" "+this.b_y+" "+x+" "+y;
		this.element.setAttributeNS(null,"d",this.currentpath);	
		this.currenthelperpath = "M"+x+" "+y+"L"+(x-10*(this.b_x-x))+" "+(y-10*(this.b_y-y))+"M"+x+" "+y;
		this.helperpath.setAttributeNS(null,"d",this.currenthelperpath);
		//BezierAbstandDraw2(this.s_x,this.s_y, this.a_x,this.a_y, this.b_x,this.b_y, x,y);
		this.s_x = x;
		this.s_y = y;
	}
}

Tool_curve.prototype.onMouseMove = function(event)
{
	
}

Tool_curve.prototype.onMouseUp = function(event)
{
	
}

Tool_curve.prototype.onDeselect = function(event)
{
	if (this.helperpath != null)
	{
		jQuery(this.helperpath).remove();
	}
}


//debug:
function Tool_curvedebug()
{
	this.element = null;
	this.currentpath = "";
	this.start_x;
	this.start_y;
	this.a_x;
	this.a_y;
	this.b_x;
	this.b_y;
	this.status=0;
	this.helperpath;
	this.currenthelperpath;
}

Tool_curvedebug.prototype.onMouseDown = function(event)
{
	var x = getMouseX(event);
	var y = getMouseY(event);
	var svg = jQuery('#paint').svg('get');	
	if (this.status == 0)
	{	
		this.start_x = x;
		this.start_y = y;
		
		this.currentpath = "M"+x+","+y;
		this.element = svg.path(this.currentpath,  {'stroke-linejoin': 'round','stroke-linecap': 'round','stroke-opacity': currentopacity, 'fill-opacity': currentbackopacity, fill: 'none', stroke: 'black', 'stroke-width': currentwidth});
		this.currenthelperpath = "M"+x+","+y;
		this.helperpath = svg.path(this.currenthelperpath,  {'stroke-linejoin': 'round','stroke-linecap': 'round','stroke-opacity': .5, fill: 'none', stroke: "#000000", 'stroke-width': Math.round(currentwidth/2)});
		this.status = 1;
	}
	else if (this.status == 1)
	{
		this.status = 2;
		this.a_x = x;
		this.a_y = y;
		this.currenthelperpath += "L"+x+" "+y;
		this.helperpath.setAttributeNS(null,"d",this.currenthelperpath);	
	}
	else if (this.status == 2)
	{
		this.status = 3;
		this.b_x = x;
		this.b_y = y;
		this.currenthelperpath += "L"+x+" "+y;
		this.helperpath.setAttributeNS(null,"d",this.currenthelperpath);
	}
	else if (this.status == 3)
	{
		this.status = 0;
		for (var its = 1; its <= 12; its++) {
			
			
			
			
			
			//this.currentpath += "C"+this.a_x+" "+this.a_y+" "+this.b_x+" "+this.b_y+" "+x+" "+y;
			this.currentpath = "M"+this.start_x+","+this.start_y+"C"+this.a_x+" "+this.a_y+" "+this.b_x+" "+this.b_y+" "+x+" "+y;
			
			//this.element.setAttributeNS(null,"d",this.currentpath);	
			
			BezierAbstandDraw2(this.start_x,this.start_y, this.a_x,this.a_y, this.b_x, this.b_y, x,y, PointX, PointY, PointT);	
			
			
			this.currenthelperpath = "M"+this.start_x+","+this.start_y+"L"+this.a_x+","+this.a_y+"L"+this.b_x+","+this.b_y+"L"+x+","+y;
			this.helperpath.setAttributeNS(null,"d",this.currenthelperpath);
			
			//interpolate
			
			var PointX = new Array();
			var PointY = new Array();
			var PointT = new Array();
			

			var prev_x = this.start_x;
			var prev_y = this.start_y;
			var len = 0;;
			
			for (var t = 0; t <= 1; t += 0.01) {
				var bx = (1-t)*(1-t)*(1-t)*this.start_x + 3*(1-t)*(1-t)*t*this.a_x + 3*(1-t)*t*t*this.b_x + t*t*t*x;
				var by = (1-t)*(1-t)*(1-t)*this.start_y + 3*(1-t)*(1-t)*t*this.a_y + 3*(1-t)*t*t*this.b_y + t*t*t*y
				PointX.push(bx);
				PointY.push(by);
				
				len+= PointDistance(prev_x,prev_y, bx,by);
				
				
				PointT.push(len);
				
				prev_x = bx;
				prev_y = by;
			}
		
		
		
			var points = BezierkurveTCI(PointX[0], PointY[0], x, y, PointX, PointY, PointT, its);
			
			
			//var points = BezierkurveTI(PointX[0], PointY[0], x, y, PointX, PointY, PointT, its);
			//var points = BezierkurveI(PointX[0], PointY[0], x, y, PointX, PointY, PointT, 10);
			//var points = BezierkurveT(PointX[0], PointY[0], x, y, PointX, PointY, PointT);
			

			
			var path = "M"+PointX[0]+","+PointY[0];
			path += "C"+points[0]+" "+points[2]+" "+points[1]+" "+points[3]+" "+x+" "+y;
			
			var curve = svg.path(path,  {'stroke-linejoin': 'round','stroke-linecap': 'round','stroke-opacity': currentopacity, 'fill-opacity': currentbackopacity, fill: 'none', stroke: currentcolor, 'stroke-width': currentwidth});
			
			BezierAbstandDraw2(PointX[0],PointY[0], points[0],points[2], points[1],points[3], x,y);			
			
			var debugpath = "M"+PointX[0]+","+PointY[0] + "L"+points[0]+","+points[2]+"L"+points[1]+","+points[3]+"L"+x+","+y;
			var debug = svg.path(debugpath,  {'stroke-linejoin': 'round','stroke-linecap': 'round','stroke-opacity': currentopacity/2, 'fill-opacity': currentbackopacity, fill: 'none', stroke: currentcolor, 'stroke-width': currentwidth/2});
		
			//shift everything down
			var shift = 200;
			
			this.start_y += shift;
			this.a_y += shift;
			this.b_y += shift;
			y+=shift;
			
			
			this.currentpath = "M"+this.start_x+","+this.start_y;
			this.element = svg.path(this.currentpath,  {'stroke-linejoin': 'round','stroke-linecap': 'round','stroke-opacity': currentopacity, 'fill-opacity': currentbackopacity, fill: 'none', stroke: 'black', 'stroke-width': currentwidth});
			this.currenthelperpath = "M"+this.start_x+","+this.start_y;
			this.helperpath = svg.path(this.currenthelperpath,  {'stroke-linejoin': 'round','stroke-linecap': 'round','stroke-opacity': .5, fill: 'none', stroke: "#000000", 'stroke-width': Math.round(currentwidth/2)});
			
		}
	}
}

Tool_curvedebug.prototype.onMouseMove = function(event)
{
	
}

Tool_curvedebug.prototype.onMouseUp = function(event)
{
	
}

Tool_curvedebug.prototype.onDeselect = function(event)
{
	if (this.helperpath != null)
	{
		jQuery(this.helperpath).remove();
	}
}


/*

function Tool_curvepen()
{
	this.element = null;
	this.currentpath = "";
	this.prev_x;
	this.prev_y;
	
	this.PointX = new Array();
	this.PointY = new Array();
	
	this.curve = null;
}

Tool_curvepen.prototype.onMouseDown = function(event)
{
	var x = getMouseX(event);
	var y = getMouseY(event);
	var svg = jQuery('#paint').svg('get');	
		
	setSmoothPos(x,y);
	if (this.currentpath == "") {
		this.currentpath = "M"+x+","+y;
		this.element = svg.path(this.currentpath,  {'stroke-linejoin': 'round','stroke-linecap': 'round','stroke-opacity': currentopacity/2, 'fill-opacity': currentbackopacity, fill: 'none', stroke: currentcolor, 'stroke-width': currentwidth});
	}
	else
	{
		this.currentpath +="L"+x+","+y;
		this.element.setAttributeNS(null,"d",this.currentpath);
	}
	this.prev_x = x;
	this.prev_y = y;
	
	this.PointX.push(x);
	this.PointY.push(y);
	
	//---
	if (this.PointX.length >=4) {
		var points = Bezierkurve(this.PointX[0], this.PointY[0], x, y, this.PointX, this.PointY);
		
		var path = "M"+this.PointX[0]+","+this.PointY[0];
		path += "C"+points[0]+" "+points[2]+" "+points[1]+" "+points[3]+" "+x+" "+y;
		if (this.curve != null) {
			jQuery(this.curve).remove();
		}
		this.curve = svg.path(path,  {'stroke-linejoin': 'round','stroke-linecap': 'round','stroke-opacity': currentopacity, 'fill-opacity': currentbackopacity, fill: 'none', stroke: currentcolor, 'stroke-width': currentwidth});
	}
}

Tool_curvepen.prototype.onMouseMove = function(event)
{

}

Tool_curvepen.prototype.onMouseUp = function(event)
{

}


*/

function Tool_curvepen()
{
	this.element = null;
	this.currentpath = "";
	this.prev_x;
	this.prev_y;
	
	this.preview = null;
	
	this.len = 0;
	
	this.PointX = new Array();
	this.PointY = new Array();
	this.PointT = new Array();
}

Tool_curvepen.prototype.onMouseDown = function(event)
{
	var x = getMouseX(event);
	var y = getMouseY(event);
	var svg = jQuery('#paint').svg('get');	
		
	setSmoothPos(x,y);
	this.currentpath = "M"+x+","+y;
	this.element = svg.path(this.currentpath,  {'stroke-linejoin': 'round','stroke-linecap': 'round','stroke-opacity': currentopacity/2, 'fill-opacity': currentbackopacity, fill: 'none', stroke: currentcolor, 'stroke-width': currentwidth});
	this.prev_x = x;
	this.prev_y = y;
	
	this.segmentlen = Math.max(currentwidth, currentwidth / zoom);
	
	this.PointX.push(x);
	this.PointY.push(y);
	this.PointT.push(this.len);
}

Tool_curvepen.prototype.onMouseMove = function(event)
{
	var x = getSmoothMouseX(event);
	var y = getSmoothMouseY(event);
	var minlen = this.segmentlen*this.segmentlen;
	var len = (x-this.prev_x)*(x-this.prev_x) + (y-this.prev_y)*(y-this.prev_y);
	
	if (minlen < len)
	{
		this.currentpath +="L"+x+","+y;
		this.element.setAttributeNS(null,"d",this.currentpath);
		
		var d = PointDistance(x,y,this.prev_x,this.prev_y);
		
		var dx = x - this.prev_x;
		var dy = y - this.prev_y;
		
		var dlen = Math.sqrt(dx*dx + dy*dy);
		dx /= dlen;
		dy /= dlen;
		
		
		for (var done = this.segmentlen; done < d; done+=this.segmentlen) {
			if (done > d) {
				done = d;				
			}	
			this.PointX.push(this.prev_x + dx * done);
			this.PointY.push(this.prev_y + dy * done);
			this.PointT.push(this.len + done);			
		}
				
		this.len += d;
		
		this.prev_x = x;
		this.prev_y = y;
		
		//this.PointX.push(x);
		//this.PointY.push(y);
		//this.PointT.push(this.len);
		
		if (this.PointX.length >= 4) {
			var points = BezierkurveTI(this.PointX[0], this.PointY[0], x, y, this.PointX, this.PointY, this.PointT, 2);
			
			
			
			
			var path = "M"+this.PointX[0]+","+this.PointY[0];
			path += "C"+points[0]+" "+points[2]+" "+points[1]+" "+points[3]+" "+x+" "+y;
			
			if (this.preview == null) {
				var svg = jQuery('#paint').svg('get');	
				this.preview = svg.path(path,  {'stroke-linejoin': 'round','stroke-linecap': 'round','stroke-opacity': currentopacity, 'fill-opacity': currentbackopacity, fill: 'none', stroke: currentcolor, 'stroke-width': currentwidth});
			} else {
				this.preview.setAttributeNS(null,"d",path);
			}
		}
		
	}

}

Tool_curvepen.prototype.onMouseUp = function(event)
{
	var x = getSmoothMouseX(event);
	var y = getSmoothMouseY(event);
	var svg = jQuery('#paint').svg('get');	
	
	this.currentpath +="L"+x+","+y;
	this.element.setAttributeNS(null,"d",this.currentpath);	
	
	
	//calculate the curve...
	if (this.PointX.length >= 4) {
	
		var points = BezierkurveTI(this.PointX[0], this.PointY[0], x, y, this.PointX, this.PointY, this.PointT, 2);
		
		

		
		var path = "M"+this.PointX[0]+","+this.PointY[0];
		path += "C"+points[0]+" "+points[2]+" "+points[1]+" "+points[3]+" "+x+" "+y;
		
		if (this.preview == null) {
			this.preview = svg.path(path,  {'stroke-linejoin': 'round','stroke-linecap': 'round','stroke-opacity': currentopacity, 'fill-opacity': currentbackopacity, fill: 'none', stroke: currentcolor, 'stroke-width': currentwidth});
		} else {
			this.preview.setAttributeNS(null,"d",path);
		}	
		//BezierAbstandDraw(this.PointX[0],this.PointY[0], points[0][0],points[2][0], points[1][0],points[3][0], x,y, this.PointX, this.PointY, this.PointT);			
		
		//var debugpath = "M"+this.PointX[0]+","+this.PointY[0] + "L"+points[0]+","+points[2]+"L"+points[1]+","+points[3]+"L"+x+","+y;
		//var debug = svg.path(debugpath,  {'stroke-linejoin': 'round','stroke-linecap': 'round','stroke-opacity': currentopacity/2, 'fill-opacity': currentbackopacity, fill: 'none', stroke: currentcolor, 'stroke-width': currentwidth/2});
		
	}
	else
	{
		var path = "M"+this.PointX[0]+","+this.PointY[0];
		path += "L"+x+" "+y;
		var element = svg.path(path,  {'stroke-linejoin': 'round','stroke-linecap': 'round','stroke-opacity': currentopacity, 'fill-opacity': currentbackopacity, fill: 'none', stroke: currentcolor, 'stroke-width': currentwidth});
		
	}
	
	if (this.element != null) {
		//this.element.setAttributeNS(null,"stroke","black");	
		jQuery(this.element).remove();
	}
	
	this.element = null;
	this.currentpath = "";
	this.preview = null;
	
	this.len = 0;
	
	this.PointX = new Array();
	this.PointY = new Array();
	this.PointT = new Array();
}




function Tool_splinepen()
{
	this.dummyelement = null;
	this.element = null;
	this.currentpath = "";
	this.path = "";
	this.prev_x;
	this.prev_y;
	
	this.len = 0;
	

	
	this.PointX = new Array();
	this.PointY = new Array();
	this.PointT = new Array();
}

Tool_splinepen.prototype.reset = function() {
	this.dummyelement = null;
	this.element = null;
	this.currentpath = "";
	this.path = "";

	this.len = 0;
	
	this.PointX = new Array();
	this.PointY = new Array();
	this.PointT = new Array();	
}


Tool_splinepen.prototype.onMouseDown = function(event)
{
	var x = getMouseX(event);
	var y = getMouseY(event);
	var svg = jQuery('#paint').svg('get');	
		
	setSmoothPos(x,y);
	this.currentpath = "M"+x+","+y;
	this.dummyelement = svg.path(this.currentpath,  {'stroke-linejoin': 'round','stroke-linecap': 'round','stroke-opacity': currentopacity, 'fill-opacity': currentbackopacity, fill: 'none', stroke: currentcolor, 'stroke-width': currentwidth});
	this.prev_x = x;
	this.prev_y = y;
	
	this.segmentlen = Math.max(currentwidth, currentwidth * zoom);
	
	
	this.PointX.push(x);
	this.PointY.push(y);
	this.PointT.push(this.len);
}

Tool_splinepen.prototype.onMouseMove = function(event)
{
	var x = getSmoothMouseX(event);
	var y = getSmoothMouseY(event);
	var minlen = this.segmentlen*this.segmentlen;
	var len = (x-this.prev_x)*(x-this.prev_x) + (y-this.prev_y)*(y-this.prev_y);
	var svg = jQuery('#paint').svg('get');
	
	if (minlen < len)
	{
		this.currentpath +="L"+x+","+y;
		this.dummyelement.setAttributeNS(null,"d",this.currentpath);
		
		
		var d = PointDistance(x,y,this.prev_x,this.prev_y);
		
		var dx = x - this.prev_x;
		var dy = y - this.prev_y;
		
		var dlen = Math.sqrt(dx*dx + dy*dy);
		dx /= dlen;
		dy /= dlen;
		
		
		for (var done = this.segmentlen; done < d; done+=this.segmentlen) {
			if (done > d) {
				done = d;				
			}	
			this.PointX.push(this.prev_x + dx * done);
			this.PointY.push(this.prev_y + dy * done);
			this.PointT.push(this.len + done);			
		}
				
		this.len += d;
		
		this.prev_x = x;
		this.prev_y = y;
		
		//old
		/*
		var d = PointDistance(x,y,prev_x,prev_y);
		
		this.len += d;
		
		this.prev_x = x;
		this.prev_y = y;
		
		this.PointX.push(x);
		this.PointY.push(y);
		this.PointT.push(this.len);
		*/
		//Try to draw curve...
		
		if (this.PointX.length >= 4) {
			
			var points = BezierkurveTI(this.PointX[0], this.PointY[0], x, y, this.PointX, this.PointY, this.PointT,0);
						
			
			var dist = BezierAbstandMax(this.PointX[0],this.PointY[0], points[0][0],points[2][0], points[1][0],points[3][0], x,y, this.PointX, this.PointY, this.PointT);			
			
				
			//if ((dist > this.len / 5000) && (dist > 5)) {
			if ((dist > this.len / 5000) && (dist > 5) && (this.PointX.length > 10)) {
				//start new curve (Abstand sonst zu groß)
				
			
				//ein par Schritte zurück gehen...
				var cutpos = Math.floor( this.PointX.length / 1.618 );
				//cutpos = this.PointX.length - 1
				
				//vorne abschneiden
				var PointX_vorn = this.PointX.slice(0, cutpos+1);
				var PointY_vorn = this.PointY.slice(0, cutpos+1);
				var PointT_vorn = this.PointT.slice(0, cutpos+1);
				
				//hinten aktualisieren
				this.PointX = this.PointX.slice(cutpos, this.PointX.length);
				this.PointY = this.PointY.slice(cutpos, this.PointY.length);
				this.PointT = this.PointT.slice(cutpos, this.PointT.length);
				
				//t soll wieder bei 0 beginnen:
				for (var i=1; i < this.PointX.length; i++) {
					this.PointT[i] -= this.PointT[0];
				}
				this.PointT[0] = 0;				
				this.len = this.PointT[ this.PointT.length-1];
				
				
	
				
				points = BezierkurveTI(PointX_vorn[0], PointY_vorn[0], PointX_vorn[PointX_vorn.length-1], PointY_vorn[PointY_vorn.length-1], PointX_vorn, PointY_vorn, PointT_vorn,0);
				
				
				if (this.path == "") {
					this.path = "M"+PointX_vorn[0]+","+PointY_vorn[0];
				}
				
				//test
				//this.path += "M"+PointX_vorn[0]+","+PointY_vorn[0];
				
				this.path += "C"+points[0]+" "+points[2]+" "+points[1]+" "+points[3]+" "+PointX_vorn[PointX_vorn.length-1]+" "+PointY_vorn[PointY_vorn.length-1];
				
				if (this.element == null) {
					this.element = svg.path(this.path,  {'stroke-linejoin': 'round','stroke-linecap': 'round','stroke-opacity': currentopacity, 'fill-opacity': currentbackopacity, fill: 'none', stroke: currentcolor, 'stroke-width': currentwidth});
				} else {
					this.element.setAttributeNS(null,"d",this.path);
				}
				
				
				if (this.dummyelement != null) {
					jQuery(this.dummyelement).remove();
				}
				
				this.dummyelement = null;

	
				this.currentpath = "M"+this.PointX[0] + "," + this.PointY[0];
				
				for (var i=1; i < this.PointX.length; i++) {
					this.currentpath += "L" + this.PointX[i] + "," + this.PointY[i];
				}
				
				this.dummyelement = svg.path(this.currentpath,  {'stroke-linejoin': 'round','stroke-linecap': 'round','stroke-opacity': currentopacity, 'fill-opacity': currentbackopacity, fill: 'none', stroke: currentcolor, 'stroke-width': currentwidth});
				
				
				
			}	
			

			
		}
	}
}

Tool_splinepen.prototype.onMouseUp = function(event)
{
	var x = getSmoothMouseX(event);
	var y = getSmoothMouseY(event);
	var svg = jQuery('#paint').svg('get');	
	
	this.currentpath +="L"+x+","+y;
	this.dummyelement.setAttributeNS(null,"d",this.currentpath);	
	
	
	if (this.path == "") {
		this.path = "M"+this.PointX[0]+","+this.PointY[0];
	}
	
	//calculate the curve...
	if (this.PointX.length >= 4) {
	
		var points = BezierkurveTI(this.PointX[0], this.PointY[0], x, y, this.PointX, this.PointY, this.PointT,0);
		
		//this.path = "M"+this.PointX[0]+","+this.PointY[0];
		this.path += "C"+points[0]+" "+points[2]+" "+points[1]+" "+points[3]+" "+x+" "+y;
		
		//var element = svg.path(path,  {'stroke-linejoin': 'round','stroke-linecap': 'round','stroke-opacity': currentopacity, 'fill-opacity': currentbackopacity, fill: 'none', stroke: currentcolor, 'stroke-width': currentwidth});
			
		

		
	}
	else
	{
		//var path = "M"+this.PointX[0]+","+this.PointY[0];
		this.path += "L"+x+" "+y;
		//var element = svg.path(path,  {'stroke-linejoin': 'round','stroke-linecap': 'round','stroke-opacity': currentopacity, 'fill-opacity': currentbackopacity, fill: 'none', stroke: currentcolor, 'stroke-width': currentwidth});
		
	}
	
	
	if (this.element == null) {
		this.element = svg.path(this.path,  {'stroke-linejoin': 'round','stroke-linecap': 'round','stroke-opacity': currentopacity, 'fill-opacity': currentbackopacity, fill: 'none', stroke: currentcolor, 'stroke-width': currentwidth});
	} else {
		this.element.setAttributeNS(null,"d",this.path);
	}
	
	if (this.dummyelement != null) {
		jQuery(this.dummyelement).remove();
	}
	
	this.reset();
}




// </tools>

var tool = new Tool_pen;


var currentcolor = "#000000";
var currentopacity = 1.0;
var currentbackcolor = "#ffffff";
var currentbackopacity = 1.0;
var currentwidth = 3;

var lastXi=0;var lastYi=0;
var lastX = [];
var lastY = [];
var smoothingsteps=2;

var zoom_per_step = 1.0 + 1.0/8.0;

var resizing = false;

var LBM_down = false;
var MBM_down = false;

function setSmoothPos(x,y)
{
	for (var i=0;i<smoothingsteps;i++)
	{
		lastX[i] = x;
		lastY[i] = y;
	}
}

function appendMouseX(x)
{
	lastXi++;
	lastXi %= smoothingsteps;
	lastX[lastXi] = x;
}

function getSmoothMouseX(evt)
{
	var current = getMouseX(evt);
	//return current;
	appendMouseX(current);
	var x = current;
	for (var i=0;i<smoothingsteps;i++)
	{
		x = x + lastX[i];
	}
	x /= smoothingsteps+1;
	
	return x;
}

function appendMouseY(y)
{
	lastYi++;
	lastYi %= smoothingsteps;
	lastY[lastYi] = y;
}

function getSmoothMouseY(evt)
{
	var current = getMouseY(evt);
	//return current;
	appendMouseY(current);
	var y = current;
	for (var i=0;i<smoothingsteps;i++)
	{
		y = y + lastY[i];
	}
	y /= smoothingsteps+1;
	return y;
}


var prev_x=0;
var prev_y=0;

var pan_prev_x=0;
var pan_prev_y=0;
function OnMouseMove(obj, event)
{
	event.preventDefault();
	if (resizing)
		return;
		
	if (LBM_down)
	{
		tool.onMouseMove(event);
	}
	if (MBM_down)
	{
		var x = getMouseX(event);
		var y = getMouseY(event);
		var dx = x - pan_prev_x;
		var dy = y - pan_prev_y;
		
		viewport.x -= dx;
		viewport.y -= dy;
		jQuery('svg').get(0).setAttribute('viewBox',viewport.x+" "+viewport.y+" "+viewport.width+" "+viewport.height);
		
		pan_prev_x = x-dx;
		pan_prev_y = y-dy;
	}
}

function OnMouseDown(obj, event)
{
	
	if (resizing)
		return;
	
	if (event.button == 0)
	{
		LBM_down = true;
		tool.onMouseDown(event);
	}
	if (event.button == 1)
	{
		MBM_down = true;
		
		pan_prev_x = getMouseX(event);
		pan_prev_y = getMouseY(event);
	}
	
	event.preventDefault();
}

function OnMouseUp(obj, event)
{
	if (resizing)
		return;
	event.preventDefault();
	
	if (LBM_down)
	{
		tool.onMouseUp(event);
		LBM_down = false;
	}
	if (MBM_down)
	{
		MBM_down = false;
		event.preventDefault();
	}
	
//alert(event);
}

function resizestart()
{
	resizing = true;
	LBM_down = false;
	if (tool.element != null)
	{
		jQuery(tool.element).remove();
	}
}

function resizestop()
{
	resizing = false;
	
	var old_viewport_width = viewport.width;
	var old_viewport_height = viewport.height;
	
	var old_ratio = paintsize.width / paintsize.height;
		
	paintsize.width = jQuery('#paint').innerWidth();
	paintsize.height = jQuery('#paint').innerHeight();
	
	var new_ratio = paintsize.width / paintsize.height;
	
	if (new_ratio > old_ratio)
	{
		viewport.width = viewport.height * new_ratio;
		viewport.x -= (viewport.width - old_viewport_width)/2;
	}
	else if (new_ratio < old_ratio)
	{
		viewport.height = viewport.width / new_ratio;
		viewport.y -= (viewport.height - old_viewport_height)/2;
	}
	jQuery('svg').get(0).setAttribute('viewBox',viewport.x+" "+viewport.y+" "+viewport.width+" "+viewport.height);
	jQuery('svg').get(0).setAttribute('width',paintsize.width);
	jQuery('svg').get(0).setAttribute('height',paintsize.height);
	
	jQuery("#colors").magnifier("destroy");
	jQuery("#colors").magnifier({ 
	    overlap: true,
		distance: 50,
		magnification: 1.5
	});
}

function change_currentbackopacity(delta)
{
	currentbackopacity+=delta;
	
	if (currentbackopacity > 1.0)
		currentbackopacity = 1.0;
	if (currentbackopacity < 0.0)
		currentbackopacity = 0.0;
	jQuery("#currentbackcolor").fadeTo(1,currentbackopacity);
}

function change_currentopacity(delta)
{
	currentopacity+=delta;
	
	if (currentopacity > 1.0)
		currentopacity = 1.0;
	if (currentopacity < 0.0)
		currentopacity = 0.0;
	if (tool.element != null)
	{
		if (tool instanceof Tool_text)
		{
			jQuery(tool.element).attr("fill-opacity",currentopacity);
		}
	}
	jQuery("#currentcolor").fadeTo(1,currentopacity);
}

function zoomIn(event)
{
	event.preventDefault();
	if (zoom < 0.05)
		return;
	var x = getMouseX(event);
	var y = getMouseY(event);
	
	var px = (x - viewport.x) / viewport.width;
	var py = (y - viewport.y) / viewport.height;
	
	zoom/=zoom_per_step;
		
	viewport.width /= zoom_per_step; 
	viewport.height /= zoom_per_step;
	
	
	viewport.x = x - viewport.width * px;
	viewport.y = y - viewport.height * py;
	
	
	
	jQuery('svg').get(0).setAttribute('viewBox',viewport.x+" "+viewport.y+" "+viewport.width+" "+viewport.height);
	
	

}

function zoomOut(event)
{
	event.preventDefault();
	if (zoom > 10.0)
		return;
	var x = getMouseX(event);
	var y = getMouseY(event);
	
	var px = (x - viewport.x) / viewport.width;
	var py = (y - viewport.y) / viewport.height;
	
	zoom*=zoom_per_step;
		
	viewport.width *= zoom_per_step; 
	viewport.height *= zoom_per_step;
	
	
	viewport.x = x - viewport.width * px;
	viewport.y = y - viewport.height * py;
	
	
	

	jQuery('svg').get(0).setAttribute('viewBox',viewport.x+" "+viewport.y+" "+viewport.width+" "+viewport.height);
}

jQuery(document).ready(function() {
   // do stuff when DOM is ready
   
	//jQuery("#test").attr("style","width:150px;height:200px; background-color:blue;border:1px solid green;");
	jQuery("#paint").resizable({start: resizestart, stop: resizestop });
	
	//create SVG element
	jQuery('#paint').svg();
	
	var svg = jQuery('#paint').svg('get'); 
	//var svg = jQuery('svg').get(0);
	
	
	
	//this.element = svg.path("M 20 20 L 18 22 C 24 28 14 25 10 40 Q 20 45 15.33 60",  {fill: 'none', stroke: currentcolor, 'stroke-width': currentwidth});
	
	/*
	var r = 50;
	while (r < 1000)
		svg.circle(130, 75, r+=50, {fill: 'none', stroke: 'red', 'stroke-width': 3}); 
	var g = svg.group({stroke: 'black', 'stroke-width': 2}); 
	svg.line(g, 70, 75, 190, 75); 
	svg.line(g, 130, 15, 130, 135);
	
	*/
	
	jQuery('svg').attr('style',"position:absolute;left:0px;top;0px;width:100%;height:100%;");
	
	//viewport.x = 0;
	//viewport.y = 0;

	//load the source
	var pic_id = jQuery("#parent").attr("value");
	if (pic_id > 0)
	{
		svg.load("svg.php?id="+pic_id, {addTo: false, changeSize: false, onLoad: function()
			{
				//jQuery('svg').get(0).setAttribute('viewBox',viewport.x+" "+viewport.y+" "+viewport.width+" "+viewport.height);
				var temp = jQuery('svg').attr("viewBox").baseVal;
				viewport.x = temp.x;
				viewport.y = temp.y;
				viewport.width = temp.width;
				viewport.height = temp.height;
				
				var viewport_ratio = viewport.width / viewport.height;
				var paint_ratio = paintsize.width / paintsize.height;
				if (viewport_ratio > paint_ratio)
				{
					viewport.height = viewport.width / paint_ratio; 
				}
				else if (viewport_ratio < paint_ratio)
				{
					viewport.width = viewport.height * paint_ratio;
				}
				jQuery('svg').get(0).setAttribute('viewBox',viewport.x+" "+viewport.y+" "+viewport.width+" "+viewport.height);
			}		
		}); 
	}
	jQuery('svg').get(0).setAttribute('viewBox',viewport.x+" "+viewport.y+" "+viewport.width+" "+viewport.height);
	
	//events:
	jQuery('#paint').mousemove(function(eventObject){OnMouseMove(this,eventObject);});
	jQuery('#paint').mousedown(function(eventObject){OnMouseDown(this,eventObject);});
	jQuery('body').mouseup  (function(eventObject){OnMouseUp  (this,eventObject);});

	//zoom-evet:
	var isOpera = (navigator.userAgent.indexOf('Opera') != -1);
	jQuery('#paint').bind('wheel',function(event,delta){ (((delta < 0) && isOpera)|| ((delta > 0) && !isOpera)) ? zoomIn(event) : zoomOut(event); }); 
	
	
	//Tools:
	jQuery("#Tools_tabbar").tabs({ 
					    fx: { 
					        opacity: "toggle" 
					    } 
					});
					
	//Pen-Bar
	jQuery("<div>").appendTo("#pensettings")
		.attr("style","z-index:1;background-image:url('kacheln.png');position:absolute;float:left;width:45px;height:45px;border:1px solid black;margin:5px;margin-left:20px;margin-top:20px;");
		
	jQuery("<div>").appendTo("#pensettings")
		.attr("id","currentbackcolor")
		.attr("style","z-index:2;position:absolute;float:left;width:45px;height:45px;border:1px solid black;background-color:#ffffff;margin:5px;margin-left:20px;margin-top:20px;")
		.bind('wheel',function(event,delta){ (((delta < 0) && isOpera)|| ((delta > 0) && !isOpera)) ? change_currentbackopacity(.05) : change_currentbackopacity(-.05);event.preventDefault(); }); 
	
	jQuery("<div>").appendTo("#pensettings")
		.attr("style","z-index:100;background-image:url('kacheln.png');position:absolute;float:left;width:45px;height:45px;border:1px solid black;margin:5px;");	
	jQuery("<div>").appendTo("#pensettings")
		.attr("id","currentcolor")
		.attr("style","z-index:101;position:absolute;float:left;width:45px;height:45px;border:1px solid black;background-color:#000000;margin:5px;")
		.bind('wheel',function(event,delta){ (((delta < 0) && isOpera)|| ((delta > 0) && !isOpera)) ? change_currentopacity(.05) : change_currentopacity(-.05);event.preventDefault(); }); 
	jQuery("<div>").appendTo("#pensettings")
		.attr("id","switchcolors")
		.attr("innerHTML","")
		.attr("style","background-image:url('switch.png');font-size:5px;z-index:140;position:absolute;float:left;width:12px;height:12px;border:1px solid black;background-color:#ff0000;margin:5px;margin-top:52px;")
		.click(function(){
			var temp = currentbackcolor;
			currentbackcolor = currentcolor;
			currentcolor = temp;
			jQuery("#currentcolor").colorBlend([{param:"background-color", fromColor:currentbackcolor, toColor:currentcolor,duration:500,cycles:1, isFade:false}]);
			jQuery("#currentbackcolor").colorBlend([{param:"background-color", fromColor:currentcolor, toColor:currentbackcolor,duration:500,cycles:1, isFade:false}]);
		});
	
	
	jQuery("<div>").appendTo("#pensettings")
		.attr("id","colors")
		.attr("style","float:left;height:75px;width:420px;margin-left:15px;border:1px solid black;margin-left:75px;");
	
	var colors = ["#000000","#ff0000","#00ff00","#0000ff","#ffff00","#ff00ff","#00ffff","#003300","#993300","#3366cc","#ff9900","#33cc00","#ccff66","#ffffff","#cccccc","#999999","#666666","#333333","#666633","#336600","#3366cc","#ff6666","#ff3300","#000033","#ffcc66","#339966"];
	
	function create_color_selecter(color,CID)
	{
		jQuery('<div>').appendTo("#colors")
			.attr("id","colorpicker"+CID)
			.attr("style","float:left;width:20px;height:20px;border:1px solid black;background-color:"+color+";margin:5px;")
			.click(function()
			{
					var oldcolor = currentcolor;
					currentcolor = this.style.backgroundColor;
					jQuery("#currentcolor").colorBlend([{param:"background-color", fromColor:oldcolor, toColor:currentcolor,duration:500,cycles:1, isFade:false}]);
					
					if (tool instanceof Tool_text)
					{
						jQuery(tool.element).attr("fill",currentcolor);
						jQuery(tool.dummyinput).focus();
					}
			})
			.bind("contextmenu", function(event)
			{
				var oldcolor = currentbackcolor;
				currentbackcolor = this.style.backgroundColor;
				jQuery("#currentbackcolor").colorBlend([{param:"background-color", fromColor:oldcolor, toColor:currentbackcolor,duration:500,cycles:1, isFade:false}]);
				event.preventDefault();
			})
			.ColorPicker({
				eventName: 'dblclick',
				color: color,
				onShow: function (colpkr) {
					jQuery(colpkr).fadeIn(500);
					return false;
				},
				onHide: function (colpkr) {
					jQuery(colpkr).fadeOut(500);
					return false;
				},
				onChange: function (hsb, hex, rgb) {
					jQuery("#colorpicker"+CID).css('backgroundColor', '#' + hex);
				}
			});

			
	}
	
	for (i in colors)
	{
		create_color_selecter(colors[i],i);
		
	}
	
	
	jQuery("#colors").magnifier({ 
	    overlap: true,
		distance: 50,
		magnification: 1.5
	});
	
	//pen-size slider
	jQuery("<div>").appendTo("#pensettings")
		.attr("id","pen_size_slider")
		.attr("style","float:left;width:300px;height:50px;background-image:url('slider.jpg');border:1px solid silver;margin-left:10px;margin-top:10px;");
	jQuery("<div>").appendTo("#pen_size_slider")
		.attr("id","pen_size_slider_handle")
		.attr("style","height:62px;")
		.attr("class","ui-slider-handle");
	jQuery("#pen_size_slider").slider({startValue:currentwidth, min:1, max:20, id:"penwidth",change: function() 
	{
		currentwidth = jQuery("#pen_size_slider").slider("value");
		if (tool instanceof Tool_text)
		{
			jQuery(tool.element).attr("font-size",(10*currentwidth));
			jQuery(tool.dummyinput).focus();
		}
	
	}});	
	
	
	//Paint Tools:
	function switch_tool(button, newtool)
	{
		if (typeof tool.onDeselect == 'function')
		{
			tool.onDeselect();
		}
		jQuery("li.Tools_Paint").removeClass("Tools_Paint_Selected");
		jQuery(button).addClass("Tools_Paint_Selected");
		tool = newtool;
	}
	
	jQuery("#Tools_Paint_Pen").addClass("Tools_Paint_Selected").click(function()
	{
		switch_tool("#Tools_Paint_Pen", new Tool_pen);
	});
	jQuery("#Tools_Paint_Line").click(function()
	{
		switch_tool("#Tools_Paint_Line", new Tool_line);
	});
	jQuery("#Tools_Paint_Ellipse").click(function()
	{
		switch_tool("#Tools_Paint_Ellipse", new Tool_ellipse);
	});
	jQuery("#Tools_Paint_Rect").click(function()
	{
		switch_tool("#Tools_Paint_Rect", new Tool_rect);
	});
	jQuery("#Tools_Paint_Text").click(function()
	{
		switch_tool("#Tools_Paint_Text", new Tool_text);
	});
	
	jQuery("#Tools_Paint_Curve").click(function()
	{
		switch_tool("#Tools_Paint_Curve", new Tool_curve);
	});
	
	jQuery("#Tools_Paint_Polygon").click(function()
	{
		switch_tool("#Tools_Paint_Polygon", new Tool_polygon);
	});
	
	jQuery("#Tools_Paint_Image").click(function()
	{
		switch_tool("#Tools_Paint_Image", new Tool_image);
	});
	
	jQuery("#Tools_Paint_CurvePen").click(function()
	{
		switch_tool("#Tools_Paint_CurvePen", new Tool_curvepen);
	});
	
	//jQuery("#Tools_Paint_CurveDebug").click(function()
	//{
	//	switch_tool("#Tools_Paint_CurveDebug", new Tool_curvedebug);
	//});
	
	
	//debug:
	jQuery("#Tools_Paint_SplinePen").click(function()
	{
		switch_tool("#Tools_Paint_SplinePen", new Tool_splinepen);
	});
	
	//Paint-settings:
	jQuery("#Tools_Settings_Smoothing").keydown(function()
	{
		window.setTimeout(function()
		{
			smoothingsteps=Math.round(jQuery("#Tools_Settings_Smoothing").attr("value"));
			
			for (var i=0;i<smoothingsteps;i++)
			{
				lastX[i] = lastX[0];
				lastY[i] = lastY[0];
			}
		}, 1);
	});
	
	//undo:
	jQuery("#undo").click(function(){jQuery("svg > :last").remove();});
	
	//reset view
	jQuery("#reset_view").click(function()
	{
		viewport.width = jQuery('#paint').innerWidth();
		viewport.height = jQuery('#paint').innerHeight();
		viewport.x = 0;
		viewport.y = 0;
		zoom = 1.0;
		jQuery('svg').get(0).setAttribute('viewBox',viewport.x+" "+viewport.y+" "+viewport.width+" "+viewport.height);
	});
	
	//speichern
	jQuery("#save").click(function()
	{
		var p = jQuery('svg').get(0);
		var html = printNode(p);
		
		var pos1 = html.indexOf(">")+1;
		var pos2 = html.indexOf("</svg>");
		var parent = jQuery("#parent").attr("value");
		html = html.substring(pos1,pos2);
		
		//alert(html);
		
		jQuery("#save_feedback").attr("innerHTML",'<img src="loading.gif" alt="loading" />Bild wird gespeichert, bitte warten.');
		
		jQuery.post("ajax_drawsave.php",{'parent':parent, 'html':html, 'viewport_x':viewport.x, 'viewport_y':viewport.y, 'viewport_width':viewport.width, 'viewport_height':viewport.height },
		function(data)
		{
			if (data != "")
			{
				jQuery("#save_feedback").attr("innerHTML",data);
			}
			else
			{
				jQuery("#save_feedback").attr("innerHTML","Fehler beim speichern.");
			}
		});
		
	});
	
});

