/** User interface helpers **/

function changeZoom(canvas, sel) {
	var newZoom = Number(sel.value);
	changeZoomNum(canvas, newZoom);
}

function changeZoomNum(canvas, newZoom) {
	var newRes = newZoom * sres;
	var zoomEls = [canvas];
	var mx = 0;
	while (mx++<1000 && zoomEls.length>0) {
		var lastEl = zoomEls[zoomEls.length-1];
		zoomEls.length--;
		if (typeof(lastEl.style)!="undefined") {
			if (lastEl.id!="main") {
				if (elHasAttribute(lastEl, "px")) {
					lastEl.style.left = Math.round(stringToNumber(getElAttribute(lastEl, "px"))*newRes) + "px";
				}
				//else { setElAttribute(lastEl, "px", roundTo(lastEl.offsetLeft/res, 100000)); }
				/** Can't set these on arbitrary elements (like br's . . .) **/

				if (elHasAttribute(lastEl, "py")) {
					lastEl.style.top = Math.round(stringToNumber(getElAttribute(lastEl, "py"))*newRes) + "px";
				}
				//else { setElAttribute(lastEl, "py", roundTo(lastEl.offsetTop/res, 100000)); }
			}
			if (elHasAttribute(lastEl, "pw")) {
				lastEl.style.width = Math.round(stringToNumber(getElAttribute(lastEl, "pw"))*newRes) + "px";
			}
			//else { setElAttribute(lastEl, "pw", roundTo(lastEl.offsetWidth/res, 100000)); }

			if (elHasAttribute(lastEl, "ph")) {
				lastEl.style.height = Math.round(stringToNumber(getElAttribute(lastEl, "ph"))*newRes) + "px";
			}
			//else { setElAttribute(lastEl, "ph", roundTo(lastEl.offsetHeight/res, 100000)); }

			if (elHasAttribute(lastEl, "pfs")) {
				lastEl.style.fontSize = (stringToNumber(getElAttribute(lastEl, "pfs"))*newRes) + "px"
			}
			else {
				//alert(lastEl.tagName);
			}
		}
		else {

		}
		if (lastEl.childNodes) {
			for (var i=0; i<lastEl.childNodes.length; i++) {
				zoomEls.push(lastEl.childNodes[i]);
			}
		}
	}
	res = newRes;
	zoom = newZoom;
}

function toggleHighlightEl(el, toState) {
	if (toState==TOGGLEON) {
		/*if (!el.oldBorder) {
			el.oldBorder = el.style.border;
			if (el.oldBorder=="") { el.oldBorder = "none"; }
		}
		if (el.oldBorder=="none") {
			el.style.padding = '0px';
		}
		el.style.border = "dashed 1px rgb(192,192,192)";
		//dot(' g(o:'+el.oldBorder+',s:'+el.style.border+')');*/
		addClassName(el, "selected");
	}
	else {
		/*el.style.border = el.oldBorder;
		if (el.oldBorder=="none") {
			el.style.padding = '1px';
		}
		//dot(' f(o:'+el.oldBorder+',s:'+el.style.border+')');*/
		removeClassName(el, "selected");
	}
}

function setSelected(el) {
	document.getElementById("propertiesButton").disabled = false;
	selectedEl = el;
	toggleHighlightEl(selectedEl, TOGGLEON);
	newSelected = true;
}

function clearSelected() {
	document.getElementById("propertiesButton").disabled = true;
	toggleHighlightEl(selectedEl, TOGGLEOFF);
	selectedEl = null;
}

function fixDesignSpace() {
	document.getElementById("designspace").style.height
		= Math.floor((document.body.clientHeight*0.7)+30)+"px";
	document.getElementById("viewport").style.height
		= Math.floor(document.body.clientHeight*0.7)+"px";
}

/** User interface popups: menus and dialogs **/

function popupObjectProperties(evt) {
	//dot('b');
	return popupProperties(selectedEl, evt);
}

function convertHtmlToEdit(html) {
	return html.replace(/<li>(.*?)<\/li>(\r\n)?/gi, '* $1\n'
		).replace(/<ul.*?>([\s\S]*?)<\/ul>(\r\n)?/gi, '$1'
		).replace(/<br.*?>(\r\n)?/gi,"\n"
		).replace(/&lt;/gi, "<"
		).replace(/&gt;/gi, ">"
		).replace(/&quot;/gi, '"'
		).replace(/&amp;/, '&'
		).replace(/^\s*|\s*$/, '');
}

function convertEditToHtml(edit) {
	var lines = edit.split(/\r?\n/);
	var bulletLine = false;
	var lastWasBulletLine = false;
	var ln = '';
	for (var i=0; i<lines.length; i++) {
		ln = '';
		bulletLine = false;
		if (lines[i].match(/^\*/)) {
			if (!lastWasBulletLine) {
				ln += '<ul style="margin:0; padding:0; padding-left: 1em;">';
			}
			ln += '<li>'+toHtmlString(lines[i].replace(/^\*\s*/, ''))+'</li>';
			bulletLine = true;
		}
		else {
			if (lastWasBulletLine) {
				ln = '</ul>'+toHtmlString(lines[i])+'<br/>';
			}
			else {
				ln = toHtmlString(lines[i])+'<br />';
			}
		}
		lines[i] = ln;
		lastWasBulletLine = bulletLine;
	}
	return lines.join('');
}

function popupProperties(el, evt) {
	clearAllMenus();
	if (manipTarget) {
		toggleHighlightEl(manipTarget, TOGGLEOFF);
	}
	manipTarget = el;
	var isTextTarget = manipTarget.tagName != "IMG";
	if (!isTextTarget) {
		document.getElementById("propertiesmenu_textproperties").style.display = 'none';
	}
	else {
		document.getElementById("propertiesmenu_textproperties").style.display = 'block';
	}
	toggleHighlightEl(manipTarget, TOGGLEON);
	textMenu.createPopupMenu(document.getElementById('propertiesmenu'), 'propertiesmenu', evt.top, evt.left);
	if (isTextTarget) {
		/**Convert html to text**/
		document.getElementById('textValue').value = convertHtmlToEdit(manipTarget.innerHTML);
		document.getElementById('textValue').focus();
	}
	return evt.stopPropagation();
}

function popupBackgroundMenu(el, evt, target) {
	clearAllMenus();
	manipTarget = target;
	toggleHighlightEl(manipTarget, TOGGLEON);
	backgroundMenu.createPopupMenu(document.getElementById('backgroundmenu'), 'backgroundmenu', evt.top, evt.left);
	return evt.stopPropagation();
}

function popupImageMenu(el, evt) {
	clearAllMenus();
	imageMenu.createPopupMenu(document.getElementById('imagemenu'), 'imagemenu', evt.top, evt.left);
	return evt.stopPropagation();
}

function popupImageWindow(imgType, defaultImage) {
	if (typeof(defaultImage)=="undefined") { defaultImage = ""; }
	window.open('imagemenu.php?bcCardsId='+bcCardsId+'&imgType='+imgType+'&defaultImage='+escape(defaultImage), 'designerAid', 'width=400,height=400,scrollbars=yes');
}

function insertImageButton(el, evt, defaultImage) {
	if (hasUploads) {
		popupImageMenu(el, geo(evt));
	}
	else {
		popupImageWindow('stdImage', defaultImage);
	}
}

function clearAllMenus() {
	if (manipTarget) {
		toggleHighlightEl(manipTarget, TOGGLEOFF);
		manipTarget = null;
	}
	textMenu.clearMenus();
	backgroundMenu.clearMenus();
	imageMenu.clearMenus();
	var els = getElementsByClass("popupMenu");
	for (var i in els) {
		if (els[i].style.display != "none") {
			els[i].style.display = "none";
		}
	}
}

/** Insert objects on canvas **/

function insertImageOnCard(target, imgSrc, width, height) {
	if (target==null) { target = document.getElementById("main"); }
	var img = document.createElement("img");
	img.onload = imgLoaded;
	img.target = target;
	img.origWidth = width;
	img.origHeight = height;
	if (width) {
		setCmWidth(img, width/pres);
		setCmHeight(img, height/pres);
	}
	img.style.cursor = 'hand';
	if (!document.all) { img.style.cursor = 'pointer'; }
	img.style.position = 'absolute';
	setCmXPos(img, 0);
	setCmYPos(img, 0);
	img.style.padding = '1px';
	pushElOnTopOfArrangement(target, img);
	img.src = imgSrc;
}

function imgLoaded() {
	this.onload = null;
	var imgWidth = this.width;
	var imgHeight = this.height;
	//setCmWidth(this, imgWidth/pres);
	//setCmHeight(this, imgHeight/pres);
	this.target.appendChild(this);
	this.target = null;
	//this.style.display = "block";
}

function insertImageOnCardFromUrl(target) {
	insertImageOnCard(target, prompt("Enter or paste the address of the image (must be .gif .jpg or .png): ", "http://"));
}

function createTextOnCard(target, evt) {
	anywhereClick();
	var divEl = document.createElement('div');
	var textNode = document.createTextNode('text');
	divEl.appendChild(textNode);
	target.appendChild(divEl);
	divEl.style.position = 'absolute';
	divEl.style.fontFamily = lastChange.fontFamily;
	divEl.style.textAlign = lastChange.textAlign;
	divEl.style.color = lastChange.colour;
	setCmFontSize(divEl, lastChange.fontSize*ptToCm);
	setCmXPos(divEl, 0);
	setCmYPos(divEl, 0);
	setCmWidth(divEl, cardWidth);
	divEl.style.padding = '1px';
	divEl.style.cursor = 'hand';
	pushElOnTopOfArrangement(target, divEl);
	setSelected(divEl);
	//popupProperties(divEl, evt);
}

/** Insertion book-keeping for user **/

function addUserSpecifiedImageToContainer(cont, imgSrc, clickevt) {
	var img;
	for (var i=0; i<cont.childNodes.length; i++) {
		if (cont.childNodes[i].tagName=="IMG") {
			if (cont.childNodes[i].src==imgSrc) {
				img = cont.childNodes[i];
			}
		}
	}
	if (!img) {
		img = document.createElement("img");
		img.src = imgSrc;
		img.width = 32;
		img.height = 32;
		img.onclick = clickevt;
	}
	cont.insertBefore(img, cont.firstChild);
}

function addUserSpecifiedImage(imgSrc) {
	hasUploads = true;
	addUserSpecifiedImageToContainer(
		document.getElementById("imagemenu_imagelist"),
		imgSrc,
		function(event) { insertImageOnCard(document.getElementById('main'), this.src); }
	);
	addUserSpecifiedImageToContainer(
		document.getElementById("side1backgroundimage_imagelist"),
		imgSrc,
		function(event) { changeBackgroundImage(this.src); geo(event).stopPropagation(); }
	);
	document.getElementById("side1backgroundimage_imagelist").style.display = "block";
}

function setHasUploads(hasthem) {
	hasUploads = hasthem;
}

/** Set positions & dimensions **/

/// In view pixels
function setViewXPos(el, x) {
	setElAttribute(el, "px", roundTo(x/res, 100000));
	el.style.left = Math.round(x)+"px";
}

function setViewYPos(el, y) {
	setElAttribute(el, "py", roundTo(y/res, 100000));
	el.style.top = Math.round(y)+"px";
}

function setViewWidth(el, w, min) {
	if (!min) { min = 1; }
	if (w<min) { w = min; }
	setElAttribute(el, "pw", roundTo(w/res, 100000));
	el.style.width = Math.round(w)+"px";
}

function setViewHeight(el, h, min) {
	if (!min) { min = 1; }
	if (h<min) { h=min; }
	setElAttribute(el, "ph", roundTo(h/res, 100000));
	el.style.height = Math.round(h)+"px";
}

function setViewFontSize(el, fs) {
	setElAttribute(el, "pfs", roundTo(fs/res, 100000));
	el.style.fontSize = fs+"px";
}

///In print cms
function setCmXPos(el, x) {
	setElAttribute(el, "px", x);
	el.style.left = Math.round(x*res)+"px";
}

function setCmYPos(el, y) {
	setElAttribute(el, "py", y);
	el.style.top = Math.round(y*res)+"px";
}

function setCmWidth(el, w) {
	setElAttribute(el, "pw", w);
	el.style.width = Math.round(w*res)+"px";
}

function setCmHeight(el, h) {
	setElAttribute(el, "ph", h);
	el.style.height = Math.round(h*res)+"px";
}

function setCmFontSize(el, fs) {
	setElAttribute(el, "pfs", fs);
	el.style.fontSize = (fs*res)+"px";
}

/** Object manipulation functions **/

function pushElOnTopOfArrangement(parent, el) {
	var maxzi = 500;
	for (var i=0; i<parent.childNodes.length; i++) {
		if (typeof(parent.childNodes[i].style)!="undefined" && parent.childNodes[i].style.zIndex > maxzi) {
			maxzi = parent.childNodes[i].style.zIndex;
		}
	}
	el.style.zIndex = parseInt(maxzi)+1;
}

function changeFaces(butn, el) {
	if (el.style.display=='none') {
		el.style.display = 'block';
		butn.value = 'One Sided';
	}
	else {
		el.style.display = 'none';
		butn.value = 'Two Sided';
	}
}

function clearBackground(type) {
	if (type!="image") {
		var img = document.getElementById("side1backgroundimage");
		if (img!=null) {
			img.style.display = "none";
		}
	}
	if (type!="generated") {
		var genImg = gbid("generatedBackground1");
		if (genImg) {
			var genScript = gbid("generatedBackgroundScript1");
			genImg.parentNode.removeChild(genImg);
			genScript.parentNode.removeChild(genScript);
		}
	}
}

function changeBackgroundColour(evt, col) {
	clearBackground("color");
	manipTarget.style.backgroundColor = col;
	return evt.stopPropagation();
}

function selectBackground() {
	manipTarget = document.getElementById("cardSide1");
}

function setScriptText(scriptElement, scriptText) {
	if (scriptElement.canHaveChildren===false) {
		scriptElement.text = scriptText;
	}
	else {
		while (scriptElement.hasChildNodes()) { scriptElement.removeChild(scriptElement.firstChild); }
		scriptElement.appendChild(document.createTextNode(scriptText));
	}
}

function createScriptElement(scriptText) {
	var scriptElement = document.createElement("script");
	setScriptText(scriptElement, scriptText);
	return scriptElement;
}

function generateGradientBackground(gradFrom, gradTo) {
	clearBackground("generated");
	var cnvs = gbid("generatedBackground1");
	var canvasScript = gbid("generatedBackgroundScript1");
	if (!cnvs) {
		cnvs = document.createElement("canvas");

		//cnvs.style.top = +"px";
		//cnvs.style.left = +"px";
		cnvs.zIndex = -20;
		cnvs.width = manipTarget.offsetWidth-2;
		cnvs.height = manipTarget.offsetHeight-2;
		cnvs.origWidth = cnvs.width;
		cnvs.origHeight = cnvs.height;
		setViewWidth(cnvs, cnvs.width);
		setViewHeight(cnvs, cnvs.height);
		setViewXPos(cnvs, getElTop(gbid("cardSide1"), gbid("main"))+1 );
		setViewYPos(cnvs, getElLeft(gbid("cardSide1"), gbid("main"))+1 );
		cnvs.id = "generatedBackground1";
		cnvs.style.position = "absolute";
		gbid("main").appendChild(cnvs);
		// we need to init this for IE
		if (typeof G_vmlCanvasManager != "undefined") {
		  cnvs = G_vmlCanvasManager.initElement(cnvs);
		}
	}
	else {
		if (typeof G_vmlCanvasManager != "undefined") {
			///I should remove all nodes in the g_vml_ namespace
			cnvsDiv = cnvs.firstChild;
			while (cnvsDiv.hasChildNodes()) { cnvsDiv.removeChild(cnvs.firstChild); }
		}
	}

	var scriptText = "function generatedBackgroundScript1() { \
		var cnvs = gbid('generatedBackground1'); \
		var ctxt = cnvs.getContext('2d'); \
		var lg = ctxt.createLinearGradient(0,0,0,cnvs.height); \
		lg.addColorStop(0, '"+gradFrom+"'); \
		lg.addColorStop(1, '"+gradTo+"'); \
		ctxt.fillStyle = lg; \
		ctxt.fillRect(0, 0, cnvs.width, cnvs.height); \
		} \
		if (typeof G_vmlCanvasManager != 'undefined' && document.readyState!='complete') { \
			onloads[onloads.length] = generatedBackgroundScript1; \
		} \
		else { \
			generatedBackgroundScript1(); \
		}";
	if (!canvasScript) {
		//eval(scriptText);
		canvasScript = createScriptElement(scriptText);
		canvasScript.id = "generatedBackgroundScript1";
		gbid("main").appendChild(canvasScript);
	}
	else {
		setScriptText(canvasScript, scriptText);
		eval(scriptText);
	}
}

function cleanDesignString(str, options) {
	if (typeof(options)=="undefined") { options = {}; }
	var str = str.replace(/(<canvas[\s\S]*?>)[\s\S]*?(<\/canvas>)/gi, '$1$2');
	if (options.removePreview) {
		str = str.replace(/<span class="?prev_.*?"?>(.*?)<\/span>/gi, '$1');
	}
	return str;
}

function changeBackgroundImage(imgSrc) {
	clearBackground("image");
	var background = document.getElementById("side1background");
	var cardSide1 = document.getElementById("cardSide1");
	if (background==null) {
		background = document.createElement("div");
		background.id = "side1background";
		background.style.position = "relative";
		setViewWidth(background, cardSide1.offsetWidth-2);
		setViewHeight(background, cardSide1.offsetHeight-2);
		background.style.overflow = "hidden";
		background.style.zIndex = 1;
		background.style.left = background.style.top = 0;
		cardSide1.appendChild(background);
	}
	else {
		var background = document.getElementById("side1background");
		background.removeChild(document.getElementById("side1backgroundimage"));
	}
	if (imgSrc=="none") {
		cardSide1.removeChild(background);
		manipTarget.style.background = "white";
		return;
	}
	img = document.createElement("img");
	img.id = "side1backgroundimage";
	img.target = background;
	img.cardWidth = cardSide1.offsetWidth-2;
	img.cardHeight = cardSide1.offsetHeight-2;
	img.onload = function() {
		this.onload = null;
		var imgWidth = this.width;
		var imgHeight = this.height;
		//setCmWidth(this, imgWidth/pres);
		//setCmHeight(this, imgHeight/pres);
		setViewWidth(this, this.cardWidth);
		setViewHeight(this, this.cardHeight);
		this.target.appendChild(this);
		this.target = null;
	};
	img.onerror = function() {
		this.onerror = null;
		this.onload = null;
		alert("Image location was not valid.");
		this.target.appendChild(this);
	}
	img.src = imgSrc.replace(/\/bg(std)?small([^\/]*)$/, "/bg$2");
	img.style.display = "block";
}

function changeFont(ff) {
	lastChange.fontFamily = ff;
	manipTarget.style.fontFamily = ff;
}

function specifyFont() {
	var ff = prompt("Specify the exact font name.\nIMPORTANT: We need to arrange to use the font if we do not have it.", lastChange.fontFamily);
	if (ff) {
		lastChange.fontFamily = ff;
		manipTarget.style.fontFamily = ff;
	}
}

function specifyFontSize() {
	var fs = prompt("Specify the font size.", lastChange.fontSize);
	if (fs) {
		changeSize(fs);
	}
}

function changeSize(sz) {
	lastChange.fontSize = sz;
	setCmFontSize(manipTarget, sz*ptToCm);
}

function changeAlignment(align) {
	lastChange.textAlign = align;
	manipTarget.style.textAlign = align;
}

function changeColour(evt, col) {
	lastChange.colour = col;
	manipTarget.style.color = col;
	return evt.stopPropagation();
}

function changeDecoration(dec) {
	switch (dec) {
		case 'italic':
			var newStyle = 'italic';
			if (manipTarget.style.fontStyle=='italic') {
				newStyle = '';
			}
			manipTarget.style.fontStyle = newStyle;
		break;
		case 'bold':
			var newStyle = 'bold';
			if (manipTarget.style.fontWeight=='bold') {
				newStyle = '';
			}
			manipTarget.style.fontWeight = newStyle;
		break;
		case 'small-caps':
			var newStyle = 'small-caps';
			if (manipTarget.style.fontVariant == newStyle) {
				newStyle = '';
			}
			manipTarget.style.fontVariant = newStyle;
		break;
	}
}

function changeOpacity(op) {
	manipTarget.style.opacity = op;
	manipTarget.style.filter = "alpha("+Math.round(op*100)+")";
}

function changePositioning(pos) {
	manipTarget.style.position = pos;
}

function changeLineHeight(lineHeight) {
	if (lineHeight=="auto") { manipTarget.style.lineHeight = ""; }
	else { manipTarget.style.lineHeight = lineHeight+"em"; }
}

function rearrange(rearrangement) {
	/** Randomly choose a time to fix indexes **/
	if (Math.random()<0.1) {
		//alert('redoing z-indexes');
		var zis = [];
		for (var i=0; i<parNode.childNodes.length; i++) {
			zis = parNode.childNodes[i].style.zIndex;
		}
		zis = zis.sort();
		backZis = [];
		for (var i=0; i<zis.length; i++) {
			backZis[zis[i]] = i - Math.floor(zis.length/2) + 500;
		}
		for (var i=0; i<parNode.childNodes.length; i++) {
			parNode.childNodes[i].style.zIndex = backZis[parNode.childNodes[i].style.zIndex];
		}
	}
	var parNode = manipTarget.parentNode;
	if (rearrangement=="bottom") {
		var minzi = 500;
		for (var i=0; i<parNode.childNodes.length; i++) {
			if (typeof(parNode.childNodes[i].style)!="undefined") {
				var zi = parseInt(parNode.childNodes[i].style.zIndex);
				minzi = zi < minzi ? zi : minzi;
			}
		}
		manipTarget.style.zIndex = minzi-1;
	}
	if (rearrangement=="down") {
		var nextzi = 0;
		for (var i=0; i<parNode.childNodes.length; i++) {
			if (typeof(parNode.childNodes[i].style)!="undefined") {
				var zi = parseInt(parNode.childNodes[i].style.zIndex);
				nextzi = (zi > nextzi && zi < parseInt(manipTarget.style.zIndex)) ? zi : nextzi;
			}
		}
		for (var i=0; i<parNode.childNodes.length; i++) {
			if (typeof(parNode.childNodes[i].style)!="undefined" && parNode.childNodes[i].style.zIndex==nextzi) {
				parNode.childNodes[i].style.zIndex = manipTarget.style.zIndex;
				break;
			}
		}
		manipTarget.style.zIndex = nextzi;

	}
	if (rearrangement=="up") {
		var nextzi = 1000;
		for (var i=0; i<parNode.childNodes.length; i++) {
			if (typeof(parNode.childNodes[i].style)!="undefined") {
				var zi = parNode.childNodes[i].style.zIndex;
				nextzi = (zi < nextzi && zi > parseInt(manipTarget.style.zIndex)) ? zi : nextzi;
			}
		}
		for (var i=0; i<parNode.childNodes.length; i++) {
			if (typeof(parNode.childNodes[i].style)!="undefined" && parNode.childNodes[i].style.zIndex==nextzi) {
				parNode.childNodes[i].style.zIndex = manipTarget.style.zIndex;
				break;
			}
		}
		manipTarget.style.zIndex = nextzi;
	}
	if (rearrangement=="top") {
		var maxzi = 500;
		for (var i=0; i<parNode.childNodes.length; i++) {
			if (typeof(parNode.childNodes[i].style)!="undefined") {
				var zi = parseInt(parNode.childNodes[i].style.zIndex);
				maxzi = zi > maxzi ? zi : maxzi;
			}
		}
		manipTarget.style.zIndex = maxzi+1;
	}
}

function deleteElement() {
	var parNode = manipTarget.parentNode;
	parNode.removeChild(manipTarget);
	clearAllMenus();
}

function duplicateElement() {
	clearSelected();
	var parNode = manipTarget.parentNode;
	var clonedNode = manipTarget.cloneNode(true);
	clonedNode.style.left = (parseInt(clonedNode.style.left)+6)+"px";
	clonedNode.style.top = (parseInt(clonedNode.style.top)+6)+"px";
	parNode.appendChild(clonedNode);
	setSelected(clonedNode);
	clearAllMenus();
	/*clonedNode.setAttribute('onclick2', 'return clickedElement(this, geo(event));');
	clonedNode.setAttribute('onmousedown2', 'return elMoveStart(geo(event), this);');
	clonedNode.onclick = function (event) { return clickedElement(this, geo(event)); };
	clonedNode.onmousedown = function (event) { return elMoveStart(geo(event), this); };*/
}

/** Business card/template manipulation **/

/**Doesn't work on user end (of course)**/
function updateTemplate(el) {
	changeZoomNum(document.getElementById('main'), 1);
	anywhereClick();
	var frm = document.forms["templateform"];

	///Fix, because setAttribute with event handlers, doesn't set new event
	///handlers, DOES mask existing event handlers, and setting event handlers
	///with functions don't get exported . . .
	frm.newTemplate.value = el.innerHTML.replace(/\b(on\w+)2\b/g, "$1");
	frm.submit();
}

function createTemplate(el) {
	document.forms.templateform.bcTemplatesId.value = -1;
	updateTemplate(el);
}

function saveBusinessCard(el) {
	anywhereClick();
	document.forms.cardform.bc_BusCard.value = el.innerHTML;
	document.forms.cardform.submit();
}

/** Input events: dragging, clicking, keying **/

var elMove = new Object();
elMove.el = null;
elMove.leftOnStart = null;
elMove.topOnStart = null;
elMove.origElLeft = null;
elMove.origElTop = null;
elMove.moved = false;
elMove.resizing = false;

function getControlParent(el) {
	var el = getContainerWithTagName(el, 'div|img|canvas');
	if (el.parentNode.tagName.toLowerCase()=="canvas") {
		el = el.parentNode;
	}
	return el;
}

function elMoveStart(event, el) {
	el = getControlParent(el);
	anywhereClick(event);
	if (event.ctrlKey || el.tagName.toLowerCase()=="canvas") return;
	if (el.style.position != "") {
		event = geo(event);
		elMove.el = el;
		elMove.el.ondragstart = function() { return false; }
		elMove.leftOnStart = event.clientX;
		elMove.topOnStart = event.clientY;
		toggleHighlightEl(el, TOGGLEON);
		var clickx = event.left - getElLeft(el);
		var clicky = event.top - getElTop(el);
		//alert(clickx +";"+ clicky);
		var minx = el.offsetWidth-boxsize;
		var maxx = el.offsetWidth+boxsize;
		var miny = el.offsetHeight-boxsize;
		var maxy = el.offsetHeight+boxsize;
		if (clickx>minx && clickx<maxx && clicky>miny && clicky<maxy) {
			elMove.resizing = true;
			/*highlighting = id;
			if (!prevColor) {
				prevColor = el.style.border;
				el.style.border = "solid 1pt lightgreen";
			}*/
		}
		elMove.origElLeft = parseInt(el.style.left);
		elMove.origElTop = parseInt(el.style.top);
		elMove.origElWidth = parseInt(el.offsetWidth);
		elMove.origElHeight = parseInt(el.offsetHeight);
		return false;
	}
	return false;
}

function elMoveMoving(event) {
	if (elMove.el) {
		if (elMove.el.style.position != "") {
			if (elMove.resizing) {
				event = geo(event);
				setViewWidth(elMove.el, elMove.origElWidth + (event.clientX - elMove.leftOnStart), 5);
				setViewHeight(elMove.el, elMove.origElHeight + (event.clientY - elMove.topOnStart), 5);
			}
			else {
				event = geo(event);
				setViewXPos(elMove.el, elMove.origElLeft + (event.clientX - elMove.leftOnStart));
				setViewYPos(elMove.el, elMove.origElTop + (event.clientY - elMove.topOnStart));
				elMove.moved = true;
			}
		}
		return false;
	}
}

function elMoveEnd(event) {
	if (elMove.el) {
		el = elMove.el;
		var moved = elMove.moved;
		elMove.el = null;
		elMove.moved = false;
		elMove.resizing = false;
		setSelected(el);
		/*if (moved) {
			toggleHighlightEl(el, TOGGLEOFF);
			event = geo(event);
			setSelected(el);
			return false;
		}
		else {
			setSelected(el);
			return false;
		}*/
	}
}

function anywhereClick(e) {
	if (event || e) {
		var event = geo(event || e);
		var elPar = event.target;
		while (elPar!=null && elPar.tagName!="BODY" && elPar.tagName!="HTML") {
			if (elPar.tagName=="textValue") { return true; } //Very specific at the moment
			elPar = elPar.parentNode;
		}
	}
	if (newSelected) { newSelected = false; }
	else {
		if (selectedEl) {
			clearSelected();
		}
	}
	clearAllMenus();
}

function docKeyPress(event) {
	event = geo(event);
	//If delete button pushed
	if (!manipTarget && selectedEl && event.keyCode==46) {
		manipTarget = selectedEl;
		deleteElement();
	}
}

function docDblClick(event) {
	event = geo(event);
	if (event.target) {
		popupProperties(getControlParent(event.target), event);
	}
}

function textValueKeyUp(el, evt) {
	manipTarget.innerHTML = convertEditToHtml(el.value);

	/*var lines = el.value.split(/[\n\r]+/);
	while (manipTarget.hasChildNodes()) {
		manipTarget.removeChild(manipTarget.firstChild);
	}
	if (el.value.search(/^[\n\r]+/)!=-1) {
		manipTarget.appendChild(document.createElement("br"));
	}
	for (var i=0; i<lines.length; i++) {
		if (i!=0) {
			manipTarget.appendChild(document.createElement("br"));
		}
		manipTarget.appendChild(document.createTextNode(lines[i]));
	}
	if (el.value.search(/[\n\r]+$/)!=-1) {
		manipTarget.appendChild(document.createElement("br"));
	}*/
}

function clickedElement(el, evt) {
	el = getControlParent(el);
	if (!evt.ctrlKey) return;
	return popupProperties(el, evt);
}

/** Utilities or shortcut functions **/

function elHasAttribute(el, attr) {
	if (ie) return typeof(el[attr])!="undefined";
	return el.hasAttribute(attr);
}

function getElAttribute(el, attr) {
	if (ie) return el[attr];
	return el.getAttribute(attr);
}

function setElAttribute(el, attr, value) {
	if (ie) { el[attr] = value; }
	else { el.setAttribute(attr, value); }
}

function dot(msg) {
	document.body.appendChild(document.createTextNode(msg));
}

function forPrint(el) {
	var curZoom = zoom;
	changeZoomNum(document.getElementById('main'), 1);
	var win = window.open('about:blank', 'printPreview');
	win.document.writeln("<html><body>");
	win.document.writeln(document.getElementById("saveThis").innerHTML);
	win.document.writeln("</body></html>");
	win.document.close();
	changeZoomNum(document.getElementById('main'), curZoom);
}

function reportAProblem() {
	window.location.href = "mailto:webmaster@theprintplace.com.au?subject="+escape("the print place design tool problem");
}
