/*
Image Crop
js library that crops an image
*/

function ImageCrop(params) {
    	checkNamedParameters(params, ["imgUrl", "imgWidth", "imgHeight", "cropX", "cropY", 
									"cropWidth", "cropHeight", "cropScale"]);
	var imgUrl = getValue(params, "imgUrl", "");
	var imgWidth = getValue(params, "imgWidth", 0);
	var imgHeight = getValue(params, "imgHeight", 0);
	var cropScale = getValue(params, "cropScale", 1);
	var cropX = getValue(params, "cropX", 0) * cropScale;
	var cropY = getValue(params, "cropY", 0) * cropScale;
	var cropWidth = getValue(params, "cropWidth", 0) * cropScale;
	var cropHeight = getValue(params, "cropHeight", 0) * cropScale;
	
	var svgDoc;
	
	init();
	
	this.getBaseSvg = function(){
		return svgDoc;
	};
	
	this.getImgHref = function(){
		return $(svgDoc).find("image[id='i1']").attr("xlink:href");
	};
	
	this.getInnerSvgWidth = function(){
		return $(svgDoc).find("svg[id='childsvg']").attr("width");
	};
	
	this.getInnerSvgHeight = function(){
		return $(svgDoc).find("svg[id='childsvg']").attr("height");
	};

	this.getSvgWidth = function(){
		return $(svgDoc).find("svg:first").attr("width");
	};
	
	this.getSvgHeight = function(){
		return $(svgDoc).find("svg:first").attr("height");
	};	

	this.serializedSvg = function(){
		return getSVGString();	
	};
	
	function init(){
		svgDoc = baseSVG();

		var rootElem = $(svgDoc).find("svg:first");
		rootElem.attr("width",imgWidth);
		rootElem.attr("height",imgHeight);
		
		setInnerSvgDimensions();
		
		cropImage();
		
		$(svgDoc).find("image[id='i1']").attr("xlink:href",imgUrl);
	}
	
	function setInnerSvgDimensions(){
		var innerSvg = $(svgDoc).find("svg[id='childsvg']");
		var length = (imgWidth > imgHeight) ? imgWidth : imgHeight;
		innerSvg.attr("width",length);
		innerSvg.attr("height",length);
	}
	
	function cropImage(){
		var length = (imgWidth > imgHeight) ? imgWidth : imgHeight;
		
		var calcCropX = (imgHeight > imgWidth) ? ((imgHeight-imgWidth)/2)+cropX : cropX;
		var calcCropY = (imgWidth > imgHeight) ? ((imgWidth-imgHeight)/2)+cropY : cropY;

		var clipRect = $(svgDoc).find("rect");
		clipRect.attr("x",calcCropX);
		clipRect.attr("y",calcCropY);
		clipRect.attr("width",cropWidth);
		clipRect.attr("height",cropHeight);
		
		var aspectRatio = Round2Decimals(cropWidth/cropHeight);
		var calcScale = (aspectRatio == 1) ? imgWidth/cropWidth : (aspectRatio > 1) ? (length/cropWidth) : (length/cropHeight);
		var calcImgWidth = cropWidth*calcScale;
		var calcImgHeight = cropHeight*calcScale;				
		var transform = "scale(" + Round2Decimals(calcScale) + "),";
		transform += "matrix(1 0 0 1 " + (calcCropX*-1) + " " + (calcCropY*-1) + ")";
		
		var imageElem = $(svgDoc).find("image[id='i1']");
		imageElem.attr("transform",transform);
		
		var rootSvg = $(svgDoc).find("svg:first");
		rootSvg.attr("width",Math.round(calcImgWidth));
		rootSvg.attr("height",Math.round(calcImgHeight));		
	}
	
	function getSVGString(){
		if (window.ActiveXObject)     
			return svgDoc.xml;
		else if (window.XMLSerializer)
			return (new XMLSerializer()).serializeToString(svgDoc);   
	}
	
	function baseSVG(){
		var basesvgstring = '<?xml version="1.0"?>';	
		basesvgstring += '<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://web.resource.org/cc/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:cpbv="http://www.cafepress.com/splash" xmlns:cpDTS="http://xml.cafepress.com/dts" xmlns:cpExt="http://xml.cafepress.com/batik/ext">';
		basesvgstring += '<svg id="childsvg">';
		basesvgstring += '<defs>';
		basesvgstring += '<clipPath id="clipsettings">';
		basesvgstring += '<rect x="" y="" width="" height=""/>';
		basesvgstring += '</clipPath>';
		basesvgstring += '</defs>';
		basesvgstring += '<g cpbv:class="image" cpbv:editable="true" transform="matrix(1,0,0,1,0,0)">';
		basesvgstring += '<image width="100%" height="100%" xlink:href="" id="i1" transform="scale(1),matrix(1 0 0 1 0 0)" clip-path="url(#clipsettings)"/>';
		basesvgstring += '</g>';
		basesvgstring += '</svg>';
		basesvgstring += '</svg>';
		
		return loadXMLString(basesvgstring);
	}
	
	function loadXMLString(txt)
	 {
		if (window.ActiveXObject)  {
			xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
			xmlDoc.async = "false";
			xmlDoc.loadXML(txt);		
		} else if (window.DOMParser){
			parser = new DOMParser();
			xmlDoc = parser.parseFromString(txt, "text/xml");
		}
		return xmlDoc;
	}
		
}

/**
 * Check that there are no unrecognized named parameters.
 *
 * @param   the attributes object (e.g., { foo: 1, bar: false })
 * @param   an array of valid parameter names (e.g., ["foo", "bar"])
 */
function checkNamedParameters(attrs, allowed)
{
    for (var a in attrs) {
        //assert(allowed.contains(a), "Not a valid parameter: " + a);
    }
}

/**
 * @param attribs   a JavaScript object (usually one created via JSON)
 * @param key       key of the value to retrieve
 * @param dflt      default to return if no value found
 * @return  The value corresponding to key or default value.
 */
function getValue(attribs, key, defaultVal)
{
    var val = attribs[key];
    return typeof(val)!="undefined"? val : defaultVal;
}

function Round2Decimals(origVal)
{
	return Math.round(origVal*100)/100;
}



