/*  geom
 *  (c) 2005-2007 Pictopia (pictopia.com)
 *	basic geometry operations on NEW browsers
 *
/*--------------------------------------------------------------------------*/


/* in ptp.js
function setIdProperty(id,property,value) {
	var styleObject = document.getElementById( id );
	if (styleObject != null) {
		styleObject = styleObject.style;
		styleObject[ property ] = value;
	}
}
*/

function move(id,x,y,additive) {

	//values may have units attached (ALWAYS assume pixels!)
	var left = parseValue(getIdProperty(id, "left"));
	var top = parseValue(getIdProperty(id, "top"));
	
	if (additive) {
		setIdProperty(id,"left", (left.num + x) + left.units);
		setIdProperty(id,"top", (top.num + y) + top.units);
	}
	else {
		setIdProperty(id,"left",x + left.units);
		setIdProperty(id,"top",y + left.units);
	}
}


//returns an array of left,top,width,height
function getRect(id) {
	
	var obj = (typeof(id) == 'string' ? document.getElementById(id) : id);

	var x;
	var y;
	var arr;

	arr = new Array();

	if (0 && obj.x) {
		arr['x'] = obj.x;
		arr['y'] = obj.y;
	} else {
		x = 0;
		y = 0;
		tmp = obj;
		while (tmp.offsetParent != null) {
			x += tmp.offsetLeft;
			y += tmp.offsetTop;
			tmp = tmp.offsetParent;
		}
		x += tmp.offsetLeft;
		y += tmp.offsetTop;
		arr['x'] = x;
		arr['y'] = y;
	}
	arr['width'] = 0;
	arr['height'] = 0;
	var loop = ['width', 'height'];
	for(F in loop){
		F = loop[F];
		//add try cause of Netscape 7
		try{
			if(document.defaultView 
					&& document.defaultView.getComputedStyle(obj, null)
					&& document.defaultView.getComputedStyle(obj, null)[F]
					&& parseInt(document.defaultView.getComputedStyle(obj, null)[F])){
				arr[F] = document.defaultView.getComputedStyle(obj, null)[F];
				continue;
			}
		} catch(e) {}
		if (obj.currentStyle &&  parseInt(obj.currentStyle[F])) {
				arr[F] = obj.currentStyle[F];
				continue;
		}
		if(obj.style && obj.style[F]){
			arr[F] = obj.style[F];
			continue;
		}
		if(obj[F]){
			arr[F] = obj[F];
			continue;
		}
	}

	//make everything numbers
	if (arr['width'].toString().match('px')) {
		arr['width'] = parseInt(arr['width'].replace(/px/,''));
	}
	if (arr['height'].toString().match('px')) {
		arr['height'] = parseInt(arr['height'].replace(/px/,''));
	}
	return arr;

}

//sets position (absolute in window in Safari)
function setRect(id, baseId, x, y, width, height) {

	var obj = document.getElementById(id);
	var baseRect = baseId != null ? getRect(baseId) : null;

	move(
			id, 
			(baseRect != null ? baseRect['x'] : 0) +  x,
			(baseRect != null ? baseRect['y'] : 0) +  y,
			false
			);

	setWidth(obj, width);
	setHeight(obj, height);
}

function setRectAbsolute(id, baseId, x, y, width, height) {

	var obj = document.getElementById(id);
	//var rect = getRect(id);
	var left = parseValue(getIdProperty(id, "left"));
	var top = parseValue(getIdProperty(id, "top"));

	if (baseId != null) {
		var baseRect = getRect(baseId);

		move(
				id, 
				baseRect.x + x - left.num,
				baseRect.y + y - top.num,
				true
				);

	} else {
		move(
				id, 
				x - left.num,
				y - top.num,
				true
				);
	}
	setWidth(obj, width);
	setHeight(obj, height);
}

//ANOTHER attempt at geting this right 
function realSetRectAbsolute(id, baseId, x, y, width, height) {

	//must be at least displayed to set
	var currentDisplay = getIdProperty(id, "display");
	setIdProperty(id,"display","block");

	var rect = getRect(id);
	var left = parseValue(getIdProperty(id, "left"));
	var tp = parseValue(getIdProperty(id, "top"));
	var baseX = rect.x - left.num;
	var baseY = rect.y - tp.num;
	
	var obj = typeof(id) == 'object' ? id : document.getElementById(id);
	
	if (baseId != null) {
		var baseRect = getRect(baseId);
		
		setIdProperty(id,"left", 
				(baseRect.x + x - (rect.x -left.num)) + left.units);
		setIdProperty(id,"top", 
				(baseRect.y + y - (rect.y -tp.num)) + tp.units);

	} else {
		move(id, (x - baseX), (y - baseY), false);
		//obj.style.left = (x - baseX) + left.units;
		/*
		setIdProperty(id,"left", (x - baseX) + left.units);
		setIdProperty(id,"top", (y - baseY) + tp.units);
		*/

	}
	setWidth(obj, width);
	setHeight(obj, height);
	//reset display
	setIdProperty(id,"display",currentDisplay);

}

function setWidth(obj, width) {
	if (width == null) 
		return;

	if (typeof(obj.width) != 'undefined') {
		if (obj.width) {
			var w = parseValue(obj.width);
			obj.width = width + w.units;
		} else {
			//default to pixels
			obj.width = width + 'px';
		}
	} else { //ASSERT obj.style[width] exists
		if (obj.style['width']) {
			var w = parseValue(obj.style['width']);
			obj.style['width'] = width + w.units;
		} else {
			//default to pixels
			obj.style['width'] = width + 'px';
		}
	} 

	/*
	if (obj.width) {
		var w = parseValue(obj.width);
		obj.width = width + w.units;
	} else { //ASSERT obj.style[width] exists
		var w = parseValue(obj.style['width']);
		obj.style['width'] = width + w.units;
	} 
	*/
}

function setHeight(obj, height) {
	if (height == null) 
		return;

	if (typeof(obj.height) != 'undefined') {
		if (obj.height) {
			var h = parseValue(obj.height);
			obj.height = height + h.units;
		} else {
			//default to pixels
			obj.height = height + 'px';
			//obj.style['height'] = height + 'px';
		}
	} else { //ASSERT obj.style[height] exists
		if (obj.style['height']) {
			var h = parseValue(obj.style['height']);
			obj.style['height'] = height + h.units;
		} else {
			//default to pixels
			obj.style['height'] = height + 'px';
		}
	} 
}

//breaks element into its numeric value and any units 
function parseValue(v) {
	var ret = new Array();
	ret['num'] = parseFloat(v);
	if (isNaN(ret['num'])) 
		return;

	ret['units'] = v.replace(/^-?[\d\.]+/,'');
	return ret;
}

//debug function
function rectToString(rect) {
  return rect.width + 'x' + rect.height + ' at (' + rect.x + 'x' + rect.y + ')';
}


function inchesRounded(pix, ppi) {
  return Math.round(pix / ppi * 100)/100;
}



//COMPONENTS for DIVS and Photo Renditions
//div related pieces ... uses viewDivs

//basic loader
function loadOpCurrentDiv() {
	//tweak previous forward and in order to reet current
	var nextDiv = currentDiv;
	currentDiv = previousDiv;
	//and pass pr as default
	selectDivAct(
			nextDiv, 
			dataToPhotoRendition(photoRenditions[0]),
			'loadOp');
}

function selectDiv(dv, param) {
	selectDivAct(dv, param, 'selectOp');
}

function selectDivAct(dv, param, type) {
	
	var dvName = typeof(dv) == 'object' ? dv.name : dv;
	dv = typeof(dv) == 'object' ? dv : viewDivs[dv];

  for (var key in viewDivs) {
		if (dvName != key) {
			hide(key);
		}
	}
	
	previousDiv = currentDiv;
	//now compute change...returning selectOp
	show(dvName);
	if (typeof(dv) != 'undefined') {
		currentDiv = dv;
		if (dv[type] != '') {
			gooby('calling ', dv[type]);
			eval(dv[type] + "(previousDiv, param)");
		}
	} else  {
		//no data on current
		currentDiv = null;
	}
	show(dvName);

	//adjust cellMarker height with some fudge factor
	var fudge = 50;
	var dRect = getRect(dvName);
	var h = getRect(dvName + 'End').y - dRect.y;
	//use offsets cause IE doesn't find height; but use Max for firefox 
	//setHeight(document.getElementById('cellMarker'), dRect.height + fudge);
	setHeight(document.getElementById('cellMarker'), 
			Math.max(h, dRect.height) + fudge);

	/*
	//ugly kludge for ie to push down footer
	var tmp = document.getElementById('cellMarker');
  while (tmp.parentNode != null) {
		tmp = tmp.parentNode;
		if (tmp.tagName == 'TD') {
			setHeight(tmp, dRect.height + fudge);
			break;
		}
	}
	*/

}

/* pr is either key to photoRendtions array or a canonically formed pr string */
function selectPrForDiv(dv, prInx) {


	var renditionParams = null;
	if (prInx == null) {
		//nothing to do

	} else if (typeof(prInx) == 'object'
			&& typeof(prInx.printWidth) != 'undefined') {
		//just passing it back
		renditionParams = prInx;

	} else if (typeof(prInx) == 'string') {
		//then this is an object with a prString and the origPhoto 
		renditionParams = prDataToPhotoRendition(prInx);

		/* included direcly
		renditionParams.origWidth = prInx.orig.width; 
		renditionParams.origHeight = prInx.orig.height; 
		*/
		//add in selector components
		addPrSelectorComponents(renditionParams);


	} else {
		//must be a number
		renditionParams = dataToPhotoRendition(photoRenditions[prInx]);
	}
		gooby('<br/>STRING is now=', renditionParams);

	selectDiv(dv, renditionParams);
}

/* data is an array in canonical order
 * photo_rendition_id photo_id
 * print_width print_height
 * crop_rotation crop_x crop_y crop_width crop_height
 * border_color border_left border_right border_top border_bottom 
 * type 
 * orig_width orig_height - both AT CORRECTED orientation
 */
function dataToPhotoRendition(data) {

	var pr = [];

	//rememember as a string
	pr.asString = data[0];

 	pr.photoRenditionId = parseInt(data[0]);
	pr.photoId = data[1];
	pr.printWidth = data[2];
	pr.printHeight = data[3];

	pr.cropRotation = data[4];
	pr.cropX = data[5];
	pr.cropY = data[6];
	//always use width if from orig case
	pr.cropWidth = data[7] == 0 ? data[15] : data[7];
	pr.cropHeight = data[8] == 0 ? data[16] : data[8];

	pr.borderColor = data[9];
	pr.borderLeft = data[10];
	pr.borderRight = data[11];
	pr.borderTop = data[12];
	pr.borderBottom = data[13];

	pr.type = data[14];

	pr.origWidth = data[15];
	pr.origHeight = data[16];

	addPrSelectorComponents(pr);
	return pr;

}

function addPrSelectorComponents(pr) {

	//also add in for use by selector...always in equal units
	//supporting only fixed border and crop_only; 
	//minimum borders extends borders to fit print size 

	//first handle dynamic crop_only case (comes from cropper)
	if (pr.type == 'crop_only' 
			&& typeof(pr.dynamic) != 'undefined' 
			&& pr.dynamic) {

		pr.rotation = pr.cropRotation;

		//ALL the flips required here!
		if (pr.cropRotation % 180 == 90) {
			pr.height = pr.cropWidth;
			pr.width = pr.cropHeight;
			pr.excessTop = pr.cropX;
			pr.excessLeft = pr.cropY;

			//orig values already set to adjusted orientation!
			pr.totalWidth = pr.origWidth;
			pr.totalHeight = pr.origHeight;
		} else {
			//standard case
			pr.excessLeft = pr.cropX;
			pr.excessTop = pr.cropY;
			pr.width = pr.cropWidth;
			pr.height = pr.cropHeight;
			pr.totalWidth = pr.origWidth;
			pr.totalHeight = pr.origHeight;
		}
		//flip around excesses
		if (pr.cropRotation == 90) 
			//using pre-adjusted origs
			pr.excessLeft = pr.origWidth - pr.cropY - pr.cropHeight;
		if (pr.cropRotation == 180) {
			pr.excessLeft = pr.origWidth - pr.excessLeft - pr.cropWidth;
			pr.excessTop = pr.origHeight - pr.excessTop - pr.cropHeight;
		}
		if (pr.cropRotation == 270) 
			//using pre-adjusted origs
			pr.excessTop = pr.origHeight - pr.cropX - pr.cropWidth;
			
	} else if (pr.type == 'crop_only'
			|| pr.printWidth == 0 || pr.printHeight == 0) {
		//handle degenerative cases like a simple crop
			
		pr.excessLeft = 0;
		pr.excessTop = 0;


		//ALL the flips required here!
		if (pr.cropRotation % 180 == 90) {
			pr.height = pr.cropWidth;
			pr.width = pr.cropHeight;
			pr.totalWidth = pr.cropHeight;
			pr.totalHeight = pr.cropWidth;

		} else {
			//standard case
			pr.width = pr.cropWidth;
			pr.height = pr.cropHeight;
			pr.totalWidth = pr.cropWidth;
			pr.totalHeight = pr.cropHeight;
		}

		pr.rotation = 0; //pr.cropRotation;

	} else if (pr.type == 'fixed_border') {
		pr.rotation = 0; //pr.cropRotation;
			
		//no flips required -all data relative to output
		pr.totalWidth = pr.printWidth;
		pr.totalHeight = pr.printHeight;
		pr.excessLeft = pr.borderLeft;
		pr.excessTop = pr.borderTop;
		
		pr.width = pr.printWidth - pr.borderLeft - pr.borderRight;
		pr.height = pr.printHeight - pr.borderTop - pr.borderBottom;

	} else if (pr.type == 'minimum_border') {
		var pixPerInch = 1;
		pr.totalWidth = pr.printWidth;
		pr.totalHeight = pr.printHeight;

		//start with min borders
		pr.excessLeft = pr.borderLeft;
		pr.excessTop = pr.borderTop;

		var outCropWidth = pr.cropRotation % 180 == 90
				? pr.cropHeight
				: pr.cropWidth;
		var outCropHeight = pr.cropRotation % 180 == 90
				? pr.cropWidth
				: pr.cropHeight;
		var avlRatio = (pr.printWidth - pr.borderLeft - pr.borderRight)
			/ (pr.printHeight - pr.borderTop - pr.borderBottom);
		if (outCropWidth * avlRatio > outCropHeight) {
			pixPerInch = outCropWidth/(pr.printWidth - pr.borderLeft - pr.borderRight);
			pr.excessTop += ((outCropHeight - outCropWidth * avlRatio) /2 ) / pixPerInch;
			pr.width = outCropWidth / pixPerInch;
			pr.height = outCropHeight / pixPerInch;
		} else {
			pixPerInch = outCropHeight/(pr.printHeight - pr.borderTop - pr.borderBottom);
			pr.excessLeft += ((outCropWidth - outCropHeight / avlRatio) /2 ) / pixPerInch;
		}

		pr.width = outCropWidth / pixPerInch;
		pr.height = outCropHeight / pixPerInch;
		pr.rotation = 0; //pr.cropRotation;
	} else {
		//nothing added! (only border-only case missing)
	}
	return pr;
}

function prDataToPhotoRendition(prData) {

	var prArray = [];
	var asString = prData;
	var shorthand = '';
	if (prData.match(/\</)) {
		shorthand = prData.replace(/.*\</,'').replace(/\>.*/,'');
		//get rid of end
		prData = prData.replace(/\<.*/, '');
	}

	for (var i = 0; i < 15; i++) {
		var inx = prData.indexOf(',');
		if (inx == -1) {
			prArray[i] = '';
			continue;
		}
		prArray[i] = prData.substr(0, inx);
		//move on
		prData = prData.substr(inx + 1);
	}
	
	var pr = [];
	//remember initial value
	pr.asString = asString;
	if (shorthand != '') {
		pr.shorthand = shorthand;
	}

	pr.printWidth = (prArray[0] != '' ? parseFloat(prArray[0]) : 0);
	pr.printHeight = (prArray[1] != '' ? parseFloat(prArray[1]) : 0);

	pr.cropRotation = (prArray[2] != '' ? parseInt(prArray[2]) : 0);
	pr.cropX = (prArray[3] != '' ? parseInt(prArray[3]) : 0);
	pr.cropY = (prArray[4] != '' ? parseInt(prArray[4]) : 0);
	pr.cropWidth = (prArray[5] != '' ? parseInt(prArray[5]) : 0);
	pr.cropHeight = (prArray[6] != '' ? parseInt(prArray[6]) : 0);

	pr.borderColor = (prArray[7] != '' ? prArray[7] : 'white');
	pr.borderLeft = (prArray[8] != '' ? parseFloat(prArray[8]) : 0);
	pr.borderRight = (prArray[9] != '' ? parseFloat(prArray[9]) : 0);
	pr.borderTop = (prArray[10] != '' ? parseFloat(prArray[10]) : 0);
	pr.borderBottom = (prArray[11] != '' ? parseFloat(prArray[11]) : 0);
	
	pr.type = (prArray[12] != '' ? prArray[12] : 'crop_only');
	
	pr.origWidth = (prArray[13] != '' ? parseInt(prArray[13]) : 0);
	pr.origHeight = (prArray[14] != '' ? parseInt(prArray[14]) : 0);

	//and remember on the fly
	pr.dynamic = true;

	return pr;
}

/*places photoRendition Image in place
 *params include: maxSize = pixel area for pr (default 320)
 *bordersHidden true/false (default false)
 *padding (in inches, used in fixed_border case only
 *
 *name implies names of divs: either just name
 * and then <name>ImgBox <name>ImgDiv and <name>Img are used
 *
 *orig is orig.width and orig.height
 */
function setPhotoRenditionImage(src, prOrig, name, params) {
	gooby('<br/>spri', src, prOrig, name, params);

	var pr = orientedPhotoRenditionClone(prOrig);
	gooby('oriented', pr);
		
	var els = name;
	if (typeof(name) == 'string') {
		els = [];
		els.box = name + 'ImgBox';
		els.div = name + 'ImgDiv';
		els.img = name + 'Img';
	}

	var boxRect = getRect(els.box);

	//ratio of original to crop
	var ratio = [];

	//assure params set
	var defaultParams = [];
	defaultParams.bordersHidden = true;
	defaultParams.size = 320;
	defaultParams.padding = 0;
	for (var key in defaultParams) {
		if (typeof(params[key]) == 'undefined') 
			params[key] = defaultParams[key];
	}

	//compute visible size 
	var iRect = [];
	var vis= [];
	var clip = null;
	if (pr.type == 'crop_only') {
		//against now rotated view
		//for purposes here orig=crop
		if (typeof(pr.dynamic) != 'undefined' && pr.dynamic) {
			ratio['width'] = pr.origWidth/pr.cropWidth;
			ratio['height'] = pr.origHeight/pr.cropHeight;
		} else {
			pr.origWidth = pr.cropWidth;
			pr.origHeight = pr.cropHeight;
			ratio['width'] = 1; //pr.origWidth/pr.cropWidth;
			ratio['height'] = 1; //pr.origHeight/pr.cropHeight;
		} 

		//bordersHidden ignored in this case
		if (pr.cropWidth > pr.cropHeight) {
			vis.width = params.maxSize;
			vis.height = Math.floor(params.maxSize 
					* pr.cropHeight/pr.cropWidth);
			ratio.display = params.maxSize/pr.cropWidth;
		} else {
			vis.height = params.maxSize;
			vis.width = Math.floor(params.maxSize * pr.cropWidth/pr.cropHeight);
			ratio.display = params.maxSize/pr.cropHeight;
		}
		if (typeof(pr.dynamic) != 'undefined' && pr.dynamic) {
			vis.x = Math.floor(ratio.display * pr.cropX);
			vis.y = Math.floor(ratio.display * pr.cropY);
		}  else {
			vis.x = 0; //Math.floor(ratio.display * pr.cropX);
			vis.y = 0; //Math.floor(ratio.display * pr.cropY);
		} 
		iRect.width = Math.floor(ratio.width * vis.width);
		iRect.height = Math.floor(ratio.height * vis.height);
		//and center in box
		iRect.x = Math.floor((boxRect.width - vis.width)/2) - vis.x;
		iRect.y = Math.floor((boxRect.height - vis.height)/2) - vis.y;

	} else if (pr.type == 'fixed_border') {
		//padding is part of borders; but included within maxSize
		var visInch = [];
		visInch.width = pr.printWidth - pr.borderLeft - pr.borderRight;
		visInch.height = pr.printHeight - pr.borderTop - pr.borderBottom;

		if (params.bordersHidden) {
			ratio.ppi = visInch.width > visInch.height 
					? params.maxSize/(visInch.width + params.padding * 2)
					: params.maxSize/(visInch.height + params.padding * 2);
		} else {
			ratio.ppi = pr.printWidth > pr.printHeight
				?  params.maxSize/pr.printWidth
				:  params.maxSize/pr.printHeight;
		}
		if (pr.cropWidth > pr.cropHeight) {
			vis.width = params.maxSize;
			vis.height = Math.floor(params.maxSize 
					* pr.cropHeight/pr.cropWidth);
		} else {
			vis.height = params.maxSize;
			vis.width = Math.floor(params.maxSize * pr.cropWidth/pr.cropHeight);
		}
		vis.x = Math.floor(ratio.ppi * pr.borderLeft);
		vis.y = Math.floor(ratio.ppi * pr.borderTop);

		iRect.width = Math.floor(ratio.ppi * pr.printWidth);
		iRect.height = Math.floor(ratio.ppi * pr.printHeight);
		//and center in box
		iRect.x = Math.floor((boxRect.width - vis.width)/2) - vis.x;
		iRect.y = Math.floor((boxRect.height - vis.height)/2) - vis.y;
		gooby('<br/>fb gets', iRect, 'vis=', vis, 'based on r-', ratio, 'vin', visInch, 'pr=', pr, 'parm=', params, 'boxrect=', boxRect);
		

	} else {
		//NOT YET SUPPORTED for minimum_border
	}
	gooby('using...', iRect, 'vis-', vis, 'br=', boxRect);


	show(els.div);

	/*
	setRect(els.div, els.box,
			iRect.x,
			iRect.y,
			iRect.width,
			iRect.height
			);
	*/
	realSetRectAbsolute(els.div, null,
			iRect.x + boxRect.x,
			iRect.y + boxRect.y,
			iRect.width,
			iRect.height
			);
		
	var img = document.getElementById(els.img);
	img.src = src;
	img.width = iRect.width;
	img.height = iRect.height;

	document.getElementById(els.div).style.clip = 
			'rect(' +  vis.y + 'px,' 
			+ (vis.x + vis.width - 1)
			+ 'px,'
			+ (vis.y + vis.height - 1)
			+ 'px,' 
			+ vis.x + 'px)';
			//FOR NOW
	show(els.div);


}

function orientedPhotoRenditionClone(prOrig) {;

	var pr = clone(prOrig);

	//flop pr based on rotation
	if (pr.cropRotation % 180 == 90) {

		temp = pr.cropWidth;
		pr.cropWidth = pr.cropHeight;
		pr.cropHeight = temp;

		temp = pr.cropX;
		pr.cropX = pr.cropY;
		pr.cropY = temp;
	
		//flip directions
		if (pr.cropRotation == 90) 
			pr.cropX =   pr.origWidth - pr.cropX - pr.cropWidth;
		if (pr.cropRotation == 270) 
			pr.cropY =   pr.origHeight - pr.cropY - pr.cropHeight;

	} else if (pr.cropRotation == 180) {
		pr.cropX =   pr.origWidth - pr.cropX - pr.cropWidth;
		pr.cropY =   pr.origHeight - pr.cropY - pr.cropHeight;
	}

	return pr;
}

//used by cart and done page to render a phtooRendition
function loadDynSetViews() {
	for (var i = 0; i < dynSetDivs.length; i++) {
		var inf = dynSetDivs[i];
		//contains dv,provider_id,ptp_photo_id,pr_string
		var pr = prDataToPhotoRendition(inf[3]);
		setPhotoRenditionImage(dynsetUrlPrefix
				+ '?provider_id=' +  inf[1]
				+ '&amp;size=150_art&amp;ptp_photo_id=' + inf[2]
				+ '&amp;photo_rendition_id=0'
				+ '&amp;rot=' + pr.cropRotation, pr, 'pr_' + inf[0], dynsetParams);
	}
}

//simple color conversion
function colorToRgb(clr) {

	//assure a string
	clr = '' + clr;
	if (clr.match(/rgb/)) 
		return clr;

	//now make a number 
	clr = parseInt(clr.match(/\#/) 
			?  clr.replace(/\#/,'0x')
			: clr);

	return 'rgb('
			+ Math.floor(clr/256/256) + ','
			+ (Math.floor(clr/256) % 256) + ',' 
			+ (clr % 256) 
			+ ')';
}

/*
* compute all info about this photo rendition from crop rect and img
* assume display from original
* cRect is crop window
* rect is image
* params include origWidth, origHeight, rotation, ppi
* note: ppi is of crop area
*/
function makePhotoRenditionHash(cRect, rect, params) {
	
	var out = {
		type : params.type,
		printWidth : cRect.width,
		printHeight : cRect.height,
		cropRotation : params.rotation,
		borderColor : 'white',
		ppi : params.ppi,
		origWidth : params.origWidth,
		origHeight : params.origHeight
	};

	//convert everything to relative to orig width/height

	var v = {};
	if (rect.x <= cRect.x) {
		v.borderLeft = 0;
		v.cropX = cRect.x - rect.x;
	} else {
		v.borderLeft = rect.x - cRect.x;
		v.cropX = 0;
	}
	if (rect.x + rect.width <= cRect.x + cRect.width) {
		v.borderRight = (cRect.x + cRect.width - rect.x + rect.width);
		v.cropWidth = (rect.x + rect.width) - Math.max(rect.x, cRect.x);
	} else {
		v.borderRight = 0;
		v.cropWidth = (cRect.x + cRect.width) - Math.max(rect.x, cRect.x);
	}

	if (rect.y <= cRect.y) {
		v.borderTop = 0;
		v.cropY = cRect.y - rect.y;
	} else {
		v.borderTop = (rect.y - cRect.y);
		v.cropY = 0;
	}
	if (rect.y + rect.height <= cRect.y + cRect.height) {
		v.borderBottom = 
				(cRect.y + cRect.height - rect.y + rect.height);
		v.cropHeight = (rect.y + rect.height) - Math.max(rect.y, cRect.y);
	} else {
		v.borderBottom = 0;
		v.cropHeight = (cRect.y + cRect.height) - Math.max(rect.y, cRect.y);
	}

	//now set results based on rotation and multiply by ratio
	//and put in standard photo rendition terms
	var ratio = params.origWidth/ (params.rotation % 180 == 90
			? rect.height : rect.width);

	if (params.rotation % 180 == 90) {
		out.cropWidth = Math.floor(v.cropHeight * ratio);
		out.cropHeight = Math.floor(v.cropWidth * ratio);
		if (params.rotation == 90) {
			out.cropX = Math.floor(v.cropY * ratio);
			out.cropY = params.origHeight 
					- Math.floor((v.cropX + v.cropWidth) * ratio);
			out.borderLeft = v.borderBottom;
			out.borderRight = v.borderTop;
			out.borderTop = v.borderLeft;
			out.borderBottom = v.borderRight;
		} else {
			out.cropX = params.origWidth 
					- Math.floor((v.cropY + v.cropHeight) * ratio);
			out.cropY = v.cropX;
			out.borderLeft = v.borderTop;
			out.borderRight = v.borderBottom;
			out.borderTop = v.borderRight;
			out.borderBottom = v.borderLeft;
		}
	} else {
		out.cropWidth = Math.floor(v.cropWidth * ratio);
		out.cropHeight = Math.floor(v.cropHeight * ratio);
		out.borderLeft = v.borderLeft;
		out.borderRight = v.borderRight;
		if (params.rotation == 180) {
			out.cropX = params.origWidth 
					- Math.floor((v.cropX + v.cropWidth) * ratio);
			out.cropY = params.origHeight 
				- Math.floor((v.cropY + v.cropHeight) * ratio);
			out.borderTop = v.borderBottom;
			out.borderBottom = v.borderTop;
		} else {
			out.cropX = Math.floor(v.cropX * ratio);
			out.cropY = Math.floor(v.cropY * ratio);
			out.borderTop = v.borderTop;
			out.borderBottom = v.borderBottom;
		}
	}

	//because of rounding issues - we have to twiddle these down to size
	if (out.cropX + out.cropWidth > params.origWidth) {
		out.cropWidth = params.origWidth - out.cropX;
	}
	if (out.cropY + out.cropHeight > params.origHeight) {
		out.cropHeight = params.origHeight - out.cropY;
	}

	return out;
}
/*
 * delivers in canonical format:
 * print_width,print_height,crop_rotation,crop_x,crop_y,width,crop_height,
 * border_color,border_left,border_right,border_top,border_bottom
 *
 */
function prHashToString(out, selectedViewName) {

	//print size and borders are in rounded inches 
	var pr = inchesRounded(out.printWidth, out.ppi) + ',' 
			+ inchesRounded(out.printHeight, out.ppi) + ',' 
			+ out.cropRotation + ',' 
			+ out.cropX + ',' + out.cropY + ',' 
			+ out.cropWidth + ',' + out.cropHeight + ',' 
			+ out.borderColor + ',' 
			+ inchesRounded(out.borderLeft, out.ppi) + ',' 
			+ inchesRounded(out.borderRight, out.ppi) + ',' 
			+ inchesRounded(out.borderTop, out.ppi) + ',' 
			+ inchesRounded(out.borderBottom, out.ppi) + ','
			+ out.type + ','
			+ out.origWidth + ','
			+ out.origHeight + ','
			+ selectedViewName;
	return pr;
}

function inchesRounded(pix, ppi) {
	return Math.round(pix / ppi * 100)/100;
}

//function for rejiggering image
function fitme(c, imgg) {
	var w = imgg.width;
	var h = imgg.height;
	var asp = w / h;
	var R = getRect(c);
	if(h > w){
		imgg.height = R.height - 1;
		imgg.width = Math.floor(imgg.height * asp);
	}else{
		imgg.width = R.width - 1;
		imgg.height = Math.floor(imgg.width / asp);
	}
}

function setJiggerPhotoCell() {
	if ((its.ie && its.major < 7) || (navigator.appVersion.toLowerCase().match(/safari/))) {
		var __old_load = window.onload;
		function __oo(){
			if(__old_load)
				__old_load();
				var c = document.getElementsByClassName('ptpPhotoCell')[0];
				fitme(c, c.getElementsByTagName('img')[1]);
			}
		window.onload = __oo;
	}
}


	






