/*
Software License Agreement (BSD License)
Copyright (c) 2009, Conquex Ltd
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the Conquex Ltd nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY Conquex Ltd ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Conquex Ltd BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
Cnx.VmlRenderer=function(parent, width, height) {
	this.parent=parent;
	this.width=width;
	this.height=height;
	this.rendererName="Cnx.VmlRenderer";
};

Cnx.VmlRenderer.browserInitialized=false; // User for initial browser initialization when Cnx.VmlRenderer.prototype.init() is called for the first time

// Check if browser supports VML  
//   credits to crescentfresh for his post at http://stackoverflow.com/questions/654112/how-do-you-detect-support-for-vml-or-svg-in-a-browser
Cnx.VmlRenderer.isSupported=function() { 
	try {
		var testDiv=document.body.appendChild(document.createElement('div'));
		testDiv.innerHTML = '<v:shape id="vml_flag1" adj="1" />';
		var child = testDiv.firstChild;
		child.style.behavior = "url(#default#VML)";
		var supported = child ? typeof child.adj == "object": true;
		testDiv.removeChild(child);
		document.body.removeChild(testDiv);
		return supported;
	} catch(e) {
		return false;
	}
};

Cnx.VmlRenderer.prototype.init=function() { // Init renderer instance
	if(!Cnx.VmlRenderer.browserInitialized) { // Browser already initialized?
		// create xmlns
		if (!document.namespaces["v"]) {
			document.namespaces.add("v", "urn:schemas-microsoft-com:vml");
		}

		// setup default css
		var ss=document.createStyleSheet();
		ss.cssText="v\\:* {behavior:url(#default#VML);}";
		Cnx.VmlRenderer.browserInitialized=true;
	}
	
	// Create v:group container
	this.vml=document.createElement("v:group");
	this.vml.style.position="absolute";
	this.vml.style.top=this.parent.offsetTop+"px";
	this.vml.style.left=this.parent.offsetLeft+"px";
	this.vml.style.width=this.width+"px";
    this.vml.style.height=this.height+"px";
    this.vml.setAttribute("coordsize", this.width+" "+this.height);
	this.parent.appendChild(this.vml);
	
	// readjust coordinates on rezise
	var refVml=this.vml;
	var refParent=this.parent;
	if(!window.onresize) {
		window.onresize=function() {
			refVml.style.top=refParent.offsetTop+"px";
			refVml.style.left=refParent.offsetLeft+"px";
		};
	}
};

Cnx.VmlRenderer.prototype.removeAllChildren=function(node) { // DOM recursive remove children function
	for(var i=node.childNodes.length-1;i>=0;i--) {
		this.removeAllChildren(node.childNodes[i]);
		node.removeChild(node.childNodes[i]);
	}	
};

Cnx.VmlRenderer.prototype.reset=function() { // Reset renderer
	this.removeAllChildren(this.vml);
};


Cnx.VmlRenderer.prototype.drawImage = function(url, x, y, width, height, opacity) {
	var img=document.createElement("v:image");
	img.setAttribute("src", url);
	img.style.position="absolute";
	img.style.left=(x+1)+"px";
	img.style.top=(y+1)+"px";
	img.style.width=(width-2)+"px";
	img.style.height=(height-2)+"px";
	img.style.filter="alpha(opacity='"+Math.round(opacity*100)+"')";
	this.vml.appendChild(img);
};


Cnx.VmlRenderer.prototype.drawLine = function(x1, y1, x2, y2, strokeWidth, strokeColor) {
	var line=document.createElement("v:line");
	this.vml.appendChild(line);
	line.style.position="absolute";
	line.setAttribute("from", ""+x1+","+y1);
	line.setAttribute("to", ""+x2+","+y2);
	line.setAttribute("strokeweight", strokeWidth+"pt");
	line.setAttribute("strokecolor", strokeColor);
};

Cnx.VmlRenderer.prototype.drawDashedLine = function(x1, y1, x2, y2, strokeWidth, strokeColor) {
	var line=document.createElement("v:line");
	this.vml.appendChild(line);
	var vStroke=document.createElement("v:stroke");
	line.appendChild(vStroke);

	line.style.position="absolute";
	line.setAttribute("from", ""+x1+","+y1);
	line.setAttribute("to", ""+x2+","+y2);
	line.setAttribute("strokeweight", strokeWidth+"pt");
	line.setAttribute("strokecolor", strokeColor);
	vStroke.dashstyle="longdash";
};

Cnx.VmlRenderer.prototype.getTextDiminsions = function(text, fontFamily, fontSize, boldFlag, italicFlag) { // Helper function to determine text dimensions - creates a hidden div
	var div=document.createElement("div");
	document.body.appendChild(div);

	div.style.visibility="hidden";
	div.style.position="absolute";
	div.style.top="0px";
	div.style.left="0px";
	div.style.fontFamily=fontFamily;
	div.style.fontSize=fontSize+"px";
	if(boldFlag) div.style.fontWeight="bold";
	if(italicFlag) div.style.fontStyle="italic";
	div.innerText=text;

	var ret={width: div.offsetWidth, height: div.offsetHeight};
	this.removeAllChildren(div);
	document.body.removeChild(div);
	return ret;
};

Cnx.VmlRenderer.prototype.drawText = function(text, x, y, fontFamily, fontSize, color, boldFlag, italicFlag, anchor, translateX, translateY, rotate) { 
	// It was easier to implement it with a DIV tag
	var textDimensions=this.getTextDiminsions(text, fontFamily, fontSize, boldFlag, italicFlag);
	var div=document.createElement("div");
	this.vml.appendChild(div);

	div.style.position="absolute";
	div.style.fontFamily=fontFamily;
	div.style.fontSize=fontSize+"px";
	if(boldFlag) div.style.fontWeight="bold";
	if(italicFlag) div.style.fontStyle="italic";
	div.style.color=color;
	div.innerText=text;

	// Not tested completely, partial support for rotation, maybe not all combinations work!
	if(rotate!=0) div.style.filter="progid:DXImageTransform.Microsoft.BasicImage(rotation=3)";
	switch(anchor) {
		case "end":
			if(rotate!=0) {
				div.style.left=Math.round(translateX+x-textDimensions.height/2-1)+"px";
				div.style.top=Math.round(translateY+y-textDimensions.width+3)+"px";
			} else {
				div.style.left=Math.round(translateX+x-textDimensions.width-3)+"px";
				div.style.top=Math.round(translateY+y-(textDimensions.height+6)/2)+"px";
			}
			break;
		case "middle":
			if(rotate!=0) {
				div.style.left=Math.round(translateX+x+textDimensions.height/2-1)+"px";
				div.style.top=Math.round(translateY+y-textDimensions.width/2+3)+"px";
			} else {
				div.style.left=Math.round(translateX+x-textDimensions.width/2)+"px";
				div.style.top=Math.round(translateY+y-textDimensions.height/2-1)+"px";
			}
			break;
		default:
			if(rotate!=0) {
				div.style.left=Math.round(translateX+x+textDimensions.height/2-1)+"px";
				div.style.top=Math.round(translateY+y-textDimensions.width/2+3)+"px";
			} else {
				div.style.left=Math.round(translateX+x)+"px";
				div.style.top=Math.round(translateY+y-textDimensions.height+3)+"px";
			}
			break;
	}
};

Cnx.VmlRenderer.prototype.drawRectangleWithGradientAndTransform = function(
		x, y, width, height, drawBorderFlag, 
		startColor, startAlpha, 
		endColor, endAlpha, 
		translateX,
		translateY,
		rotate,
		shearX,
		shearY,
		vmlGradientAngle // needed to override angle, since VML doesnt rotate gradients as the shape rotates and skews
	) {
	var rect1=document.createElement("v:rect");
	this.vml.appendChild(rect1);
	if(!drawBorderFlag) rect1.stroked=false; // has border?

	if((shearX!=0) || (shearY!=0)) {
		var oSkew=document.createElement("v:skew");
		rect1.appendChild(oSkew);
		rect1.childNodes[0].on=false;
		rect1.appendChild(oSkew);

		// Matrices and offsets adjusted with tries and errors to match the SVG skew implementation
		if(rotate==0) {
			rect1.childNodes[0].matrix="1 "+Math.tan((shearX)*Math.PI/180.0)+" "+Math.tan((-shearY)*Math.PI/180.0)+" 1 0 0";
			rect1.childNodes[0].offset=(Math.tan((shearX)*Math.PI/180.0)*height)+"px "+(Math.tan((-shearY)*Math.PI/180.0)*width)+"px";
			rect1.childNodes[0].on=true;
		} else if(rotate==90) {
			rect1.childNodes[0].matrix="1 "+(Math.tan((-shearY)*Math.PI/180.0))+" "+(-Math.tan((shearX)*Math.PI/180.0))+" 1 0 0";
			rect1.childNodes[0].offset=(Math.tan((-shearY)*Math.PI/180.0)*width)+"px 0px";
			rect1.childNodes[0].on=true;
		} else if(rotate==180) {
			rect1.childNodes[0].matrix="1 "+Math.tan((shearX)*Math.PI/180.0)+" "+Math.tan((shearY)*Math.PI/180.0)+" 1 0 0";
			rect1.childNodes[0].on=true;
		}
	}
	
	// Adjust rectangle size and rotation
	rect1.style.position="absolute";
	rect1.style.width=width+"px";
	rect1.style.height=height+"px";
	rect1.style.rotation=""+rotate;

	// VML seems to rotate rectangles around their center so some calculations are needed to adjust the top and left coordinates
	var cx=x+width/2;
	var cy=y+height/2;
	var x1=cx+(Math.cos(rotate*Math.PI/180.0)*(x-cx)-Math.sin(rotate*Math.PI/180.0)*(y-cy));
	var y1=cy+(Math.sin(rotate*Math.PI/180.0)*(x-cx)+Math.cos(rotate*Math.PI/180.0)*(y-cy));
	var dx=x1-x;
	var dy=y1-y;
	rect1.style.left=Math.round(translateX+x-dx)+"px";
	rect1.style.top=Math.round(translateY+y-dy)+"px";

	// initially the gradient was too dark so had to reduce the small alpha values and lighten the black color
	if(startAlpha<.9) startAlpha/=100;
	if(endAlpha<.9) endAlpha/=100;
	if(startColor=="#000000") startColor="#888888";
	if(endColor=="#000000") endColor="#888888";

	// Create and setup the gradient
	var vFill=document.createElement("v:fill");
	rect1.appendChild(vFill);
	vFill.type="gradient";
	vFill.color=startColor;
	vFill.color2=endColor;
	vFill.opacity=Math.round(startAlpha*100)+"%";
	vFill.opacity2=Math.round(endAlpha*100)+"%";
	if(!vmlGradientAngle) vFill.angle=rotate+90; else vFill.angle=vmlGradientAngle; // override angle if needed
};

Cnx.VmlRenderer.prototype.finish = function() {
};
