var currenttabstep;
var currentpieceidx;
var dummyImage = new Image;

// these are here to define the location (top, left) of the icon/text area for each piecetype.
// they're here, rather than in the db, since there is no piecetype master table.
var icon_offsets = new Array();
icon_offsets['default'] = new Array(80, 75); // starting point
icon_offsets['square'] = new Array(0, 63);
icon_offsets['fold'] = new Array(95, 15);
icon_offsets['flat'] = new Array(60, 0);
icon_offsets['prog'] = new Array(30, 0);

// top, left for $('previewICONandTEXT') for square patterns
var square_text_offsets = new Array();
square_text_offsets['square'] = new Array(80, 45);
square_text_offsets['fold'] = new Array(-50, -50);

// width, height
var square_text_sizes = new Array();
square_text_sizes['default'] = new Array(216, 250);
square_text_sizes['square'] = new Array(291, 291);
square_text_sizes['fold'] = new Array(324, 236);

var CartObject;
var sdefs;

var fontMap = new Array();
fontMap['Text']   = 'T';
fontMap['Script'] = 'L';
fontMap['Note']   = 'N';
fontMap['Map']    = 'M';
fontMap['Photo']  = 'P';

var shippingBreaks = new Array(100, 200, 300, 400, 450, 500, 550, 650, 750, 850, 950, 1200, 1500, 1800, 2100, 2400);
var shippingValues = new Array( 12,  15,  25,  30,  35,  40,  45,  50,  55,  60,  65,   70,   80,   90,   95,  100);

function getAllCartValues() {
	var url = 'getAllCartValues.php';
	new Ajax.Request(url,
		{
			method: 'get',
			asynchronous: false,
			onSuccess: function(transport){
				var response = transport.responseText;
				if (response) {
					eval(response);
				}
				else {
					alert('getAllCartValues returned nothing!');
					return false;
				}
			},
			onFailure: function(){
				alert('getAllCartValues failed!');
				return false;
			}
		}
	);
}


function getCartValue(k) {
	// k key name
	if (!k) return '';
	var v = eval('CartObject.'+k);
	return v ? v : '';
}


// not used??
function createtab_over(t, tabclicked) {
	// t is a element representing a tab
	if (!t) return;
	
	var thistabstep = isIE ? t.step : t.getAttribute('step');

	if (thistabstep == currenttabstep) return;
	
	t.className = tabclicked ? 'createtabon' : 'createtabover';

	var tabs = t.parentNode.getElementsByTagName('TD');
	
	var firsttabstep = isIE ? tabs[0].step : tabs[0].getAttribute('step');
	
	if (thistabstep != firsttabstep) {
		for (var i=0; i<tabs.length; i++) {
			var tabstep = isIE ? tabs[i].step : tabs[i].getAttribute('step');
			if (tabstep == thistabstep) {
				tabs[i-1].style.borderRightColor = 'black';
			}
		}
	}
}

function tab_over(t) {
	// t is a element representing a tab
	if (!t) return;
	
	if (t.className != 'tabover') {
		t.className = 'tabhover';
		t.style.cursor = 'pointer';
	}
}


// not used??
function createtab_out(t, override) {
	// t is a element representing a tab
	if (!t) return;

	var thistabstep = isIE ? t.step : t.getAttribute('step');
	
	if ((thistabstep != currenttabstep) || override) {
		t.className = 'createtabout';
	}
	
	var tabs = t.parentNode.getElementsByTagName('TD');
	
	var firsttabstep = isIE ? tabs[0].step : tabs[0].getAttribute('step');
	
	if (thistabstep != firsttabstep) {
		for (var i=0; i<tabs.length; i++) {
			var tabstep = isIE ? tabs[i].step : tabs[i].getAttribute('step');
			var prvtabstep;
			if (i > 0) {
				prvtabstep = isIE ? tabs[i-1].step : tabs[i-1].getAttribute('step');
			}
			if (tabstep == thistabstep && (thistabstep != currenttabstep || override)) {
				tabs[i-1].style.borderRightColor = '';
			}
		}
	}
}

function tab_out(t) {
	// t is a element representing a tab
	if (!t) return;
	
	if (t.className == 'tabhover') {
		t.className = 'tabout';
		t.style.cursor = 'default';
	}
}

function tab_click(t) {
	// t is a element representing a tab
	if (!t) return;

	$("theForm").style.display="none";
	$("createform").style.display="block";

	//var thistabstep = isIE ? t.step : t.getAttribute('step');
	var thistabstep = t.id;

	if (thistabstep == currenttabstep) return;
	
	var tabs = t.parentNode.getElementsByTagName('div');
	for (var i=0; i<tabs.length; i++) {
			var tabstep = tabs[i].id;
			if (!tabstep) continue;
			
			var contentid = tabstep.replace('_tab', '');
			
			if (tabstep == thistabstep) {
				tabs[i].className = 'tabover';
				$(contentid).style.display = 'block';
				//$(contentid).className = 'tabcontentshow';
				if (contentid == 'patterns') {
					//CSBfleXcroll('patternslistmargin');
				}
				else if (contentid == 'pieces') {
					CSBfleXcroll('pieceslist');
				}
				else if (contentid == 'types') {
					//CSBfleXcroll('fontstyles');
					//CSBfleXcroll('piecestext');
				}
				else if (contentid == 'icons') {
					//CSBfleXcroll('iconlistmargin');
				}
				else if (contentid == 'borders') {
					//CSBfleXcroll('borderlistmargin');
				}
				else if (contentid == 'sashes') {
					CSBfleXcroll('beltlist');
					CSBfleXcroll('obilist');
					CSBfleXcroll('actualsashlist');
				}
			}
			else {
				tabs[i].className = 'tabout';
				$(contentid).style.display = 'none';
				//$(contentid).className = 'tabcontent';
			}
	}	
	
	currenttabstep = thistabstep;

	// set SESSION's CART_CURRENT_TAB_STEP value
	var url = 'setCartValues.php?CART_CURRENT_TAB_STEP=' + currenttabstep;
	new Ajax.Request(url,
		{
			method: 'get',
			asynchronous: false,
			onSuccess: function(transport){
				var response = transport.responseText;
				if (response) {
					eval(response);
				}
				else {
					alert('Something went wrong 1a...');
					return false;
				}
			},
			onFailure: function(){
				alert('Something went wrong 1b...');
				return false;
			}
		}
	);
debugIt();
}

function itemOver(el) {
	// el is the element 
	if (!el) return;
	
	if (!el.className.match(/^selected/)) {
		el.className='over';
		el.style.cursor = 'pointer';
	}
}

function itemOut(el) {
	// el is the element 
	if (!el) return;
	
	if (!el.className.match(/^selected/)) {
		el.className='notSelected';
		el.style.cursor = 'default';
	}
}

function init_tab(step) {
	// step is a string
	if (!step) return;

	var tabs = $('createmenu').getElementsByTagName('div');
	for (var i=0; i<tabs.length; i++) {
		if (tabs[i].className == 'tabout' || tabs[i].className == 'tabover') {
			//var tabstep = isIE ? tabs[i].step : tabs[i].getAttribute('step');
			var tabstep = tabs[i].id;
			if (tabstep == step) {
				//tab_click(tabs[i]);
				tabs[i].onclick();
				break;
			}
		}
	}	
}

function init_patterns(skipsetthumbnail) {
	//getAllCartValues();
	var PIECES = getCartValue('PIECES');
	var PATTERN = getCartValue('PATTERN');
//alert('got into init_patterns. PIECES: '+PIECES+', PATTERN: '+PATTERN);

	// note: currently, if PIECES, there must be PATTERN
	if (PIECES) {
		var Size = $('piecetop'+PIECES.split('|')[currentpieceidx]).getAttribute('piecesize'); 
//alert('Size: '+Size);
		$('previewPATTERNimg').src = 'patterns_display_image.php/'+PATTERN+'/1/'+Size;
		// we do it this way since init_borders() depends on the pattern being loaded
		$('previewPATTERNimg').onload = init_borders;
		if (!skipsetthumbnail) {
			hiliteImage($('pattern'+PATTERN), $('patternslistmargin'), 0, 1);
		}
	}
	else if (PATTERN) {
		if (!$("patternslistmargin").innerHTML) {
			getPatterns("patternslistmargin");
		}
		var Size = $('pattern'+PATTERN).getAttribute('defaultSize'); 
		$('previewPATTERNimg').src = 'patterns_display_image.php/'+PATTERN+'/1/'+Size;
		// we do it this way since init_borders() depends on the pattern being loaded
		$('previewPATTERNimg').onload = init_borders;
		if (!skipsetthumbnail) {
			hiliteImage($('pattern'+PATTERN), $('patternslistmargin'), 0, 1);
		}
	}
	else {
		$('previewPATTERNimg').src = 'images/1x1.gif';
		if (!skipsetthumbnail) {
			hiliteImage(dummyImage, $('patternslistmargin'), 0, 1);
		}
	}
//alert('got thru init_patterns');
}

function init_types(fontstyle, inkcolor, textaligns, texts) {
	var PIECES = getCartValue('PIECES');

	if (fontstyle) {
		if (!$("fontstyles").innerHTML) getFonts("fontstyles");
		hiliteImage($('fontstyle'+fontstyle), $('fontstyles'), 0, 1);
	}

	if (inkcolor) {
		hiliteInkColor($('inkcolor'+inkcolor), $('inkcolors'), 1);
	}

	if (textaligns) {
		var textalign = textaligns.split('|')[currentpieceidx];
		var imgs = $('taligns').getElementsByTagName('p');
		for (var x=0; x<imgs.length; x++) {
			if (imgs[x].getAttribute('cartval') == textalign) {
				imgs[x].className = imgs[x].id + '_on';
				$('previewICON').style.textAlign = textalign;
			}
			else {
				imgs[x].className = imgs[x].id;
			}
		}
	}

	if (texts) {
		var text = texts.split('|')[currentpieceidx];
		var textlines;
		var piece = PIECES.split('|')[currentpieceidx];
		var allow_map = 0;
		var allow_photo = 0;
		if (pt = $('piecetop'+piece)) {
			allow_map = pt.getAttribute('allow_map');
			allow_photo = pt.getAttribute('allow_photo');
		}
		if (text && text != '^') {
			textlines = text.split('^');
			for (var l=0; l<textlines.length; l++) {
				var line = textlines[l].split('~');
				line[0] = line[0].replace(/\&124;/g, '|');
				document.forms[2].elements['line'+(l+1)].setAttribute('value', line[0]);
				document.forms[2].elements['line'+(l+1)].value = line[0];
				thefont = line[1] ? line[1] : 'Text';
				document.forms[2].elements['line'+(l+1)].setAttribute('font', thefont);
				$('lineT'+(l+1)).className = 
					$('lineL'+(l+1)).className = 
					$('lineN'+(l+1)).className = 'TLNoff';
				$('lineM'+(l+1)).className = 
					$('lineP'+(l+1)).className = 'TLNoff';

				$('line'+fontMap[thefont]+(l+1)).className = 'TLNon';

				if (allow_map == 1) {
					$('lineMcontainer'+(l+1)).className = 'lineMcontainerOn';
				}
				else {
					$('lineMcontainer'+(l+1)).className = 'lineMcontainerOff';
				}
				if (allow_photo == 1) {
					$('linePcontainer'+(l+1)).className = 'linePcontainerOn';
				}
				else {
					$('linePcontainer'+(l+1)).className = 'linePcontainerOff';
				}
				// adjust input element width
				thisclass = '';
				if (allow_map == 1 && allow_photo == 1) {
					thisclass = 'allowboth';
				}
				else if (allow_map == 1 || allow_photo == 1) {
					thisclass = 'allowone';
				}
				document.forms[2].elements['line'+(l+1)].className = thisclass;

				document.forms[2].elements['line'+(l+1)].setAttribute('spaceafter', line[2] ? line[2] : 0);
				//document.forms[2].elements['line'+(l+1)].style.marginBottom = line[2] == 1 ? '10px' : '0px';
				//$('line'+(l+1)+'container').style.marginBottom = line[2] == 1 ? '10px' : '0px';
				document.forms[2].elements['line'+(l+1)].disabled = false;
				document.forms[2].elements['line'+(l+1)].removeAttribute('disabled'); // IE
				document.forms[2].elements['line'+(l+1)].style.backgroundColor = 'white';
			}
			if (textlines.length<20) {
				for (var l=textlines.length+1; l<=20; l++) {
					document.forms[2].elements['line'+l].setAttribute('value', '');
					document.forms[2].elements['line'+l].value = '';
					document.forms[2].elements['line'+l].setAttribute('font', 'Text');
					$('lineT'+l).className =      'TLNon';
					$('lineL'+l).className = 
						$('lineN'+l).className =
							$('lineM'+l).className = 
								$('lineP'+l).className = 'TLNoff';
					if (allow_map == 1) {
						$('lineMcontainer'+l).className = 'lineMcontainerOn';
					}
					else {
						$('lineMcontainer'+l).className = 'lineMcontainerOff';
					}
					if (allow_photo == 1) {
						$('linePcontainer'+l).className = 'linePcontainerOn';
					}
					else {
						$('linePcontainer'+l).className = 'linePcontainerOff';
					}
					// adjust input element width
					thisclass = '';
					if (allow_map == 1 && allow_photo == 1) {
						thisclass = 'allowboth';
					}
					else if (allow_map == 1 || allow_photo == 1) {
						thisclass = 'allowone';
					}
					document.forms[2].elements['line'+l].className = thisclass;
					//document.forms[2].elements['line'+l].removeAttribute('spaceafter');
					document.forms[2].elements['line'+l].setAttribute('spaceafter', 0);
					//document.forms[2].elements['line'+l].style.marginBottom = '0px';
					//$('line'+l+'container').style.marginBottom = '0px';
					//document.forms[2].elements['line'+l].disabled = true;
					//document.forms[2].elements['line'+l].setAttribute('disabled', 'disabled'); // IE
					//document.forms[2].elements['line'+l].style.backgroundColor = '#ccc';
				}
			}
		}
		else if (getCartValue('CURRENT_TAB_STEP') != 'types_tab') {
			// why was i doing this?
			//clearText();
		}
	}
}

function init_icons() {
var debug = false;

	var PIECES = getCartValue('PIECES');
	var icons = getCartValue('ICON');
	var theseicons = icons.split('|')[currentpieceidx];
	if (!theseicons) theseicons = '0';
	
	// this ensures a n^n format
	if (PIECES && $('piecetop'+PIECES.split('|')[currentpieceidx]).getAttribute('piecesquare') == 1 && (!theseicons || theseicons == '0')) theseicons = '0^0';
	
	var theseiconsa = theseicons.split('^');

	var PATTERN = getCartValue('PATTERN');

	// adjust ICON top and left offsets in preview
	var iconTop = parseInt(icon_offsets['default'][0]);
if (debug) alert('1 '+iconTop);
	var iconLeft = parseInt(icon_offsets['default'][1]);
	
	// use per-pattern/per-size offsets, if any
	if (PIECES) {
		var Size = $('piecetop'+PIECES.split('|')[currentpieceidx]).getAttribute('piecesize');
		if (!$("patternslistmargin").innerHTML) {
			getPatterns("patternslistmargin");
		}
		if (PATTERN && $('pattern'+PATTERN).getAttribute(Size+'IconOffsets')) {
			var iconOffsets = $('pattern'+PATTERN).getAttribute(Size+'IconOffsets').split('|');
var wasIconTop = iconTop;
			iconTop += parseInt(iconOffsets[0]);
if (debug) alert('2 '+wasIconTop+'+'+iconOffsets[0]+'='+iconTop);
			iconLeft += parseInt(iconOffsets[1]);
		}
		if (icon_offsets[Size]) {
var wasIconTop = iconTop;
			iconTop += parseInt(icon_offsets[Size][0]);
if (debug) alert('3 '+wasIconTop+'+'+icon_offsets[Size][0]+' ('+Size+')='+iconTop);
			iconLeft += parseInt(icon_offsets[Size][1]);
		}
		if ($('piecetop'+PIECES.split('|')[currentpieceidx]).getAttribute('piecesquare') == '1' && $('piecetop'+PIECES.split('|')[currentpieceidx]).getAttribute('piecesize') == 'fold') {
			iconLeft -= 73;
var wasIconTop = iconTop;
			iconTop  -= 30;
if (debug) alert('4 '+wasIconTop+'-30='+iconTop);
		}
			
	}
	
	var INKCOLOR = getCartValue('INKCOLOR');

	// handle first (or only) icon
	var icon = theseiconsa[0];
	if (!icon || icon == 0) {
		if (theseiconsa.length > 1) {
			$('previewICONimgsquare').src = 'images/1x1.gif';
			//$('previewICONimgsquare').width = 1;
			//$('previewICONimgsquare').height = 1;
			$('previewICONimgsquare').style.display = 'none';
		}
		else {
			$('previewICONimg').src = 'images/1x1.gif';
			//$('previewICONimg').width = 1;
			//$('previewICONimg').height = 1;
			$('previewICONimg').style.display = 'none';
		}
	}
	else {
		if (!$("iconlistmargin").innerHTML) getIcons("iconlistmargin");
		//var iconsrc = 'icons_display_image.php/'+icon+'/1';
		var iconsrc = 'images/icons/' + $('icon'+icon).getAttribute('previewname') + '-' + $('inkcolor'+INKCOLOR).getAttribute('previewcode') + '.png';
		if (theseiconsa.length > 1) {
			// TODO: get icon in inkcolor color
			$('previewICONimgsquare').src = iconsrc;
			//$('previewICONimgsquare').width = $('icon'+icon).getAttribute('Preview_Image_Width');
			//$('previewICONimgsquare').height = $('icon'+icon).getAttribute('Preview_Image_Height');
			$('previewICONimgsquare').style.display = '';
			$('previewICONsquare').style.top = iconTop + 'px';
			$('previewICONsquare').style.left = iconLeft + 'px';
		}
		else {
			// TODO: get icon in inkcolor color
			$('previewICONimg').src = iconsrc;
			//$('previewICONimg').width = $('icon'+icon).getAttribute('Preview_Image_Width');
			//$('previewICONimg').height = $('icon'+icon).getAttribute('Preview_Image_Height');
			$('previewICONimg').style.display = '';
		}
	}

	// handle second (if any) icon
	var icon = theseiconsa[1];
	if (!icon || icon == 0) {
		if (theseiconsa.length > 1) {
			$('previewICONimg').src = 'images/1x1.gif';
			//$('previewICONimg').width = 1;
			//$('previewICONimg').height = 1;
			$('previewICONimg').style.display = 'none';
		}
	}
	else {
		if (!$("iconlistmargin").innerHTML) getIcons("iconlistmargin");
		// TODO: get icon in inkcolor color
		//$('previewICONimg').src = 'icons_display_image.php/'+icon+'/1';
		$('previewICONimg').src = 'images/icons/' + $('icon'+icon).getAttribute('previewname') + '-' + $('inkcolor'+INKCOLOR).getAttribute('previewcode') + '.png';
		//$('previewICONimg').width = $('icon'+icon).getAttribute('Preview_Image_Width');
		//$('previewICONimg').height = $('icon'+icon).getAttribute('Preview_Image_Height');
		$('previewICONimg').style.display = '';
	}

	//if (PIECES && $('piecetop'+PIECES.split('|')[currentpieceidx]).getAttribute('piecesquare') == 1) {
	if (PIECES && $('piecetop'+PIECES.split('|')[currentpieceidx]).getAttribute('piecesize') == 'square') {
		$('previewTEXTinnerLink').style.display = 'block';
		$('previewICONsquare').style.display = 'block';
		$('previewICONandTEXT').className = 'Inner'+Size;
		// position
		$('previewICON').style.paddingTop = '30px';
		$('previewICONandTEXT').style.top = square_text_offsets[Size][0] + 'px';
		$('previewICONandTEXT').style.left = square_text_offsets[Size][1] + 'px';
		$('previewICONandTEXT').style.width = square_text_sizes[Size][0] + 'px';
		$('previewICONandTEXT').style.height = square_text_sizes[Size][1] + 'px';
		// if we're working on the inside, keep showing it; else show the outside
		if ($("showoutside").style.display != 'none') {
			$('previewICONandTEXT').style.display = 'block';
		}
		else {
			$('previewICONandTEXT').style.display = 'none';
		}
	}
	else {
		$('previewICON').style.paddingTop = '0px';
		$('previewTEXTinnerLink').style.display = 'none';
		//$("showinside").style.display = 'inline';
		//$("showoutside").style.display = 'none';
		$('previewICONsquare').style.display = 'none';
		$('previewICONandTEXT').style.display = 'block';
		$('previewICONandTEXT').className = 'notInner';
		// position 
		$('previewICONandTEXT').style.top = iconTop + 'px';
		$('previewICONandTEXT').style.left = iconLeft + 'px';
		$('previewICONandTEXT').style.width = square_text_sizes['default'][0] + 'px';
		$('previewICONandTEXT').style.height = square_text_sizes['default'][1] + 'px';
	}

	// hilite the right icon
	var index = ($("previewTEXTinnerLink").style.display != 'block' || $("showinside").style.display != 'none') ? 0 : 1;
	hiliteIcon(index);
}

function hiliteIcon(index) {
	var icons = getCartValue('ICON');
	var icontexts = getCartValue('ICON_TEXT');
	var theseicons = icons.split('|')[currentpieceidx];
	var theseicontexts = icontexts.split('|')[currentpieceidx];
	var theseiconsa = Array();
	var theseicontextsa = Array();
	if (theseicons) {
		theseiconsa = theseicons.split('^');
		theseicontextsa = theseicontexts.split('^');
		if (theseiconsa[index] && !$("iconlistmargin").innerHTML) getIcons("iconlistmargin");
	}

	var imgs = $('icons').getElementsByTagName('IMG');
	for (var x=0; x<imgs.length; x++) {
		var thisimg = imgs[x];
		var thisimgtxt = thisimg.parentNode.getElementsByTagName('INPUT');
		if (thisimg.getAttribute('cartval') == theseiconsa[index]) {
			thisimg.className = 'selected';
			thisimg.title = 'Click to de-select';
			// TODO: put any icon text below icon
			if (thisimgtxt.length) {
				if (thisimgtxt.length == 1) {
					thisimgtxt[0].value = theseicontextsa[index];
				}
				else {
					var letters = theseicontextsa[index].split("");
					for (var l=0; l<letters.length; l++) {
						thisimgtxt[l].value = letters[l];
					}
				}
			}
		}
		else {
			thisimg.className = 'notSelected';
			thisimg.title = 'Click to select';
			// TODO: clear icon text below icon
			for (var t=0; t<thisimgtxt.length; t++) {
				thisimgtxt[t].value = '';
			}
		}
	}
}

function init_borders() {
	if (!$("borderlistmargin").innerHTML) getBorders("borderlistmargin");

	var BORDER = getCartValue('BORDER');
	if ((PATTERN = getCartValue('PATTERN')) && $('pattern'+PATTERN).getAttribute('no_borders') == '1') {
			setCart('BORDER', '', 1, 0, 0);
			BORDER = '';
	}

	var PIECES = getCartValue('PIECES');
	var INKCOLOR = getCartValue('INKCOLOR');
	
	if (BORDER && PIECES && INKCOLOR) {
		var size = $('piecetop'+PIECES.split('|')[currentpieceidx]).getAttribute('piecesize');
		var topoffset = (size == 'prog') ? 29 : 0;
		var leftoffset = (size == 'fold') ? 29 : 0;
		var ppi = $('previewPATTERNimg');
		// this is for safari's know bug of incorrect offsetTop for absolutely positioned elements
		var ppiOffsetTop = ppi.offsetTop ? ppi.offsetTop : ppi.parentNode.offsetTop;
		$('previewBORDER').style.top    = parseInt(ppiOffsetTop + 1 + topoffset)+'px';
		$('previewBORDER').style.left   = parseInt(ppi.offsetLeft + 1 + leftoffset)+'px';
		$('previewBORDER').style.height = parseInt(ppi.offsetHeight - topoffset - 18)+'px';
		$('previewBORDER').style.width  = parseInt(ppi.offsetWidth - leftoffset - 18)+'px';
		var inkpreviewcode = $('inkcolor'+INKCOLOR).getAttribute('previewcode');
		var borderpreviewcode = $('border'+BORDER).getAttribute('previewcode'); 
		if (borderpreviewcode == 'bouquet') {
			if (size == 'flat') size = '4BFLAT';
			if (size == 'fold') size = '4BFOLD';
		}
		if (size == 'flat' || size == 'fold') size = '4B';
		if (size == 'prog') size = 'PR';
		$('previewBORDER').style.background='url(images/borders/'+borderpreviewcode+'-'+size+inkpreviewcode+'.png) no-repeat';
	}
	else {
		$('previewBORDER').style.background='url(images/1x1.gif) no-repeat';
	}

	var imgs = $('borders').getElementsByTagName('IMG');
	for (var x=0; x<imgs.length; x++) {
		if (imgs[x].getAttribute('cartval') == BORDER) {
			imgs[x].className = 'selected';
			imgs[x].title = 'Click to de-select';
		}
		else {
			imgs[x].className = 'notSelected';
			imgs[x].title = 'Click to select';
		}
	}
}

function init_sashes(sash, backings, embellishment) {
	var backingsa = backings.split('|');
	
	if ((PATTERN = getCartValue('PATTERN')) && $('pattern'+PATTERN) && $('pattern'+PATTERN).getAttribute('no_backings') == '1') {
			for (b=0; b<backingsa.length; b++) {
				backingsa[b] = '';
			}
			setCart('BACKING', backingsa.join('|'), 1, 0, 0);
	}

	// true so no alert shows
	var noA6 = noA6Selected(true);
	var noFlat = noFlatSelected(true);
	
	if (!sash || noA6) {
		$('previewSASH').style.display = 'none';
		$('hidesash').style.display = 'none';
		hiliteImage(dummyImage, $('sashes'), 1, 1);
	}
	else {
		$('previewSASH').style.background = 'url(sashs_display_image.php/'+sash+'/1) no-repeat';
		$('previewSASH').style.display = $('hidesashshow').style.display == 'none' ? 'block' : 'none';
		$('hidesash').style.display = 'block';
		if (!$("sashlist").innerHTML) getSashs("sashlist");
		hiliteImage($('sash'+sash), $('sashes'), 1, 1);
	}

	var backing = backingsa[currentpieceidx];

	var imgs = $('backings').getElementsByTagName('IMG');
	if (backing == 0 || noFlat) {
		$('previewBACKING').style.display = 'none';
		hiliteImage(dummyImage, $('backings'), 1, 1);
	}
	else {
		//$('previewBACKING').style.background = 'url(backings_display_image.php/'+backing+') no-repeat';
		var PIECES = getCartValue('PIECES');
		var size = $('piecetop'+PIECES.split('|')[currentpieceidx]).getAttribute('piecesize');
		if (size == 'flat') size = '4bFLAT';
		if (!$("backingscontainer").innerHTML) getBackings("backingscontainer");
		$('previewBACKINGimg').src = 'images/backings/backing-'+size+$('backing'+backing).getAttribute('previewcode')+'.png';
		$('previewBACKING').style.display = 'block';
		hiliteImage($('backing'+backing), $('backings'), 1, 1);
	}

	var embsa = new Array();
	if (embellishment) {
		var embs = embellishment.split('|');
		for (var x=0; x<embs.length; x++) {
			embsa[embs[x]] = 1;
		}
	}
	
	var echks = $('embellishmentchkboxes').getElementsByTagName('input');
	for (var x=0; x<echks.length; x++) {
		echks[x].checked = embsa[echks[x].getAttribute('cartval')] ? true : false;
	}
}

function init_envelopes(envelope, squareenvelope) {
	if (!envelope && !squareenvelope) return;

	var opts;
	
	if (envelope && $('envelopeSelect')) {
		opts = $('envelopeSelect').options;
		for (o=0; o<opts.length; o++) {
			opts[o].selected = (opts[o].value == envelope);
		}
	}

	if (squareenvelope && $('squareenvelopeSelect')) {
		opts = $('squareenvelopeSelect').options;
		for (o=0; o<opts.length; o++) {
			opts[o].selected = (opts[o].value == envelope);
		}
	}
}

function setCart(k, v, c, m, q, t) {
	// handle the fact that square designs can have one icon on the outside (and no text), 
	// and another icon on the inside (with text).
	//
	// inside icon is possible.
	if (k == 'ICON') {
		if ($("previewTEXTinnerLink").style.display == 'block') {
			var icons = getCartValue('ICON').split('|')[currentpieceidx];
			var theseicons = icons.split('^');
			var icontexts = getCartValue('ICON_TEXT').split('|')[currentpieceidx];
			var theseicontexts = icontexts.split('^');
			// inside icon
			if ($("showinside").style.display == 'none') {
				theseicons[1] = (c == 0) ? 0 : v;
				theseicontexts[1] = (c == 0) ? 0 : t;
			}
			// outside icon
			else {
				theseicons[0] = (c == 0) ? 0 : v;
				theseicontexts[0] = (c == 0) ? 0 : t;
				// this ensures a n^n format
				theseicons[1] = (theseicons[1]) ? theseicons[1] : 0;
				theseicontexts[1] = (theseicontexts[1]) ? theseicontexts[1] : 0;
			}
			v = theseicons.join('^');
			t = theseicontexts.join('^');
		}
		else {
			if (c == 0) {
				v = 0;
				t = 0;
			}
		}
	}
	
	
	var url = 'setCart.php?k='+k+'&v='+escape(v)+'&m='+m+'&q='+q+'&r='+Math.random();
	if (typeof(c) != undefined) {
		url += '&c='+c;
	}
	
	if (typeof(c) == undefined || c == 1) {
		if (v == getCartValue(k) && q == getCartValue(k+'_QTY')) {
			return;
		}
	}

//alert(url);
	new Ajax.Request(url,
		{
			method: 'get',
			asynchronous: false,
			onSuccess: function(transport){
				var response = transport.responseText;
				if (response) {
					eval(response);
				}
				else {
					alert('Something went wrong 2a...');
					return false;
				}
			},
			onFailure: function(){
				//alert('Something went wrong 2b...');
				//return false;
			}
		}
	);
	
	if (k == 'ICON') {
		var url = 'setCart.php?k='+k+'_TEXT&v='+escape(t)+'&m='+m+'&q='+q+'&r='+Math.random();
		if (typeof(c) != undefined) {
			url += '&c='+c;
		}
	
//alert(url);
		new Ajax.Request(url,
			{
				method: 'get',
				asynchronous: false,
				onSuccess: function(transport){
					var response = transport.responseText;
					if (response) {
						eval(response);
					}
					else {
						alert('Something went wrong 3a...');
						return false;
					}
				},
				onFailure: function(){
					alert('Something went wrong 3b...');
					return false;
				}
			}
		);
	}
	
debugIt();
}

function setCartText(setonly, nowarn) {
	var v  = '';
	var l = 1;
	while (l<=20 && document.forms[2].elements['line'+l].getAttribute('font')) {
		if (v) v += '^';
		var el = document.forms[2].elements['line'+l];
		var elvalue = el.value.replace(/\|/g, '&124;');
		v += elvalue;
//alert(elvalue);
		//if (elvalue)
			v += '~' + el.getAttribute('font') + '~' + (el.getAttribute('spaceafter') ? el.getAttribute('spaceafter') : 0);
		l++;
	}

	// save text for the selected piece in cart
	setCart('TEXT', v, 1, 0, 0);
	
	if (!setonly) {
		if (!nowarn && (!getCartValue('FONTSTYLE') || !getCartValue('INKCOLOR'))) {
			showAlphaMsgText('Please choose both a font and an inkcolor from the Type & Ink tab');
		}
		else {
			// create text image
			createPreviewTextImage();
			// force 'show inside' if necessary
			if ($('previewTEXTinnerLink').style.display == 'block' && $('showinside').style.display == 'none') {
				$('showinside').onclick();
			}
		}
	}
}

function getPieces(c) {
	// c is the name of a container to update
	if (!c) return;
	
	new Ajax.Updater(c, 'getPieces.php', { asynchronous: false, evalScripts: true } );

	// handle situation where a previously selected SET or ALACART is no longer available
	var SET = getCartValue('SET');
	var SET_QTY = getCartValue('SET_QTY');
	var ALACARTE = getCartValue('ALACARTE');
	var ALACARTE_QTY = getCartValue('ALACARTE_QTY');

	var setsmissing = false;
	var alasmissing = false;
	var new_sets = new Array();
	var new_sets_qty = new Array();
	var new_alacartes = new Array();
	var new_alacartes_qty = new Array();

	if (SET) {
		var sets = SET.split('|');
		var sets_qty = SET_QTY.split('|');
		for (var i=0; i<sets.length; i++) {
			if (!$('SET'+sets[i]+'select')) {
				setsmissing = true;
			}
			else {
				new_sets.push(sets[i]);
				new_sets_qty.push(sets_qty[i]);
			}
		}
	}
	
	if (ALACARTE) {
		var alacartes = ALACARTE.split('|');
		var alacartes_qty = ALACARTE_QTY.split('|');
		for (var i=0; i<alacartes.length; i++) {
			if (!$('ALACARTE'+alacartes[i]+'select')) {
				alasmissing = true;
			}
			else {
				new_alacartes.push(alacartes[i]);
				new_alacartes_qty.push(alacartes_qty[i]);
			}
		}
	}

	if (setsmissing || alasmissing) {
		var msg = "WARNING:\n\n";
		msg += "One or more of your previous Set or A La Carte selections are not available in this pattern.\n";
		msg += "Please re-select your pieces in the Pieces tab.\n";
		if (setsmissing) {
			SET = new_sets.join('|');
			SET_QTY = new_sets_qty.join('|');
		}
		if (alasmissing) {
			ALACARTE = new_alacartes.join('|');
			ALACARTE_QTY = new_alacartes_qty.join('|');
		}
		
		// e&m don't want this message to show
		//showAlphaMsgText(msg);
		
		clearText();
		// set SESSION's CART_SET and CART_ALACARTE values
		var url = 'setCartValues.php?CART_SET=' + SET + '&CART_SET_QTY=' + SET_QTY + 
									'&CART_ALACARTE=' + ALACARTE + '&CART_ALACARTE_QTY=' + ALACARTE_QTY + 
									'&CART_PIECES=&CART_BORDER=&CART_TEXT=&CART_TEXTALIGN=&CART_ICON=';
		new Ajax.Request(url,
			{
				method: 'get',
				asynchronous: false,
				onSuccess: function(transport){
					var response = transport.responseText;
					if (response) {
						eval(response);
					}
					else {
						alert('Something went wrong 4a...');
						return false;
					}
				},
				onFailure: function(){
					alert('Something went wrong 4b...');
					return false;
				}
			}
		);
		tab_click($('pieces_tab'));
		// hide pattern popup
		$('patternpopup').style.top = '-1000px';
		$('previewICONandTEXT').style.display = 'block';
		createPreviewTextImage();
	}
	
	//doSubtotal('');
}

function getPatterns(c) {
	// c is the name of a container to update

	new Ajax.Updater(c, 'getPatterns.php', { asynchronous: false, evalScripts: true } );
	
	$('patternsblock').style.display = getCartValue('OCCASION') ? 'block' : 'none';
	//$('patternsblock').className = getCartValue('OCCASION') ? 'tabcontentshow' : 'tabcontent';

	// handle situation where a previously selected PATTERN is no longer available
	var PATTERN = getCartValue('PATTERN');
	if (PATTERN && !('pattern'+PATTERN)) showAlphaMsgText('Your previously selected pattern is no longer available');
	$("patternsblock").style.display = "block";
	//$("patternsblock").className="tabcontentshow";
	//CSBfleXcroll(c);

	if ($("patternsblock").style.display == 'block') {
		var popups = '';
		var imgs = $(c).getElementsByTagName('IMG');
		for (var x=0; x<imgs.length; x++) {
			var code = imgs[x].getAttribute('code');
			popups += "<img class='patternpopupimg' id='" + code + "patternpopup' src='/images/patternpopups/" + code + "_over.png' style='display:none;' />\n";
		}
		$('patternpopup').innerHTML = popups;
	}
}

function getIcons(c) {
	// c is the name of a container to update

	new Ajax.Updater(c, 'getIcons.php', { asynchronous: false } );
	//CSBfleXcroll(c);
}

function getBorders(c) {
	// c is the name of a container to update

	new Ajax.Updater(c, 'getBorders.php', { asynchronous: false } );
	//CSBfleXcroll(c);
}

function getBackings(c) {
	// c is the name of a container to update

	new Ajax.Updater(c, 'getBackings.php', { asynchronous: false } );
}

function getFonts(c) {
	// c is the name of a container to update

	new Ajax.Updater(c, 'getFonts.php', { asynchronous: false, evalScripts: true } );

	var popups = '';
	var imgs = $(c).getElementsByTagName('IMG');
	for (var x=0; x<imgs.length; x++) {
		var code = imgs[x].getAttribute('code');
		popups += "<img class='fontpopupimg' id='" + code + "fontpopup' src='/images/fontpopups/" + code + "_over.png' style='display:none;' />\n";
	}
	$('fontpopup').innerHTML = popups;

	//CSBfleXcroll(c);
}

function getSashs(c) {
	// c is the name of a container to update

	new Ajax.Updater(c, 'getSashs.php', { asynchronous: false } );
}

function hiliteImage(i, c, t, f) {
	// i is an image element
	// c is a container of such elements
	// t is optional 'toggle' flag
	// f is optional 'force' flag
	if (!i || !c) return;

	var imgs = c.getElementsByTagName('IMG');
	for (var x=0; x<imgs.length; x++) {
		if (imgs[x] == i) {
			imgs[x].className = (imgs[x].className == 'over' || f) ? 'selected' : (t ? 'over' : imgs[x].className);
		}
		else {
			imgs[x].className = 'notSelected';
		}
		imgs[x].title = (imgs[x].className == 'selected') ? (t ? 'Click to de-select' : '') : 'Click to select';
	}
}

function hiliteAlign(p, c) {
	// p is a p element
	// c is a container of such elements
	if (!p || !c) return;
	
	var ps = c.getElementsByTagName('P');
	for (var x=0; x<ps.length; x++) {
		if (ps[x] == p) {
			ps[x].className = ps[x].id+'_on';
		}
		else {
			ps[x].className = ps[x].id;
		}
	}
}

function hiliteInkColor(td, c, f) {
	// td is a td element
	// c is a container of such elements
	// f is optional 'force' flag
	if (!td || !c) return;
	
	var tds = c.getElementsByTagName('TD');
	for (var x=0; x<tds.length; x++) {
		if (tds[x].getAttribute('cartval')) {
			if (tds[x] == td) {
				//tds[x].className = (tds[x].className == 'over' || f) ? 'selected' : tds[x].className;
				tds[x].className = 'selected';
			}
			else {
				tds[x].className = 'notSelected';
			}
		}
	}
}

// not used??
function hilitePieceSelect(td, c) {
	// td is a td element
	// c is a container of such elements
	if (!td || !c) return;
	
	var ps = c.getElementsByTagName('');
	for (var x=0; x<ps.length; x++) {
		if (ps[x] == p) {
			ps[x].className = ps[x].id+'_on';
		}
		else {
			ps[x].className = ps[x].id;
		}
	}
}

function getEnvelopes(c) {
	// c is a container to update
	if (!c) return;
	
	new Ajax.Updater(c, 'getEnvelopes.php', { asynchronous: false });

	// handle situation where a previously selected ENVELOPE is no longer available
	var ENVELOPE = getCartValue('ENVELOPE');
	var SQUARE_ENVELOPE = getCartValue('SQUARE_ENVELOPE');
	init_envelopes(ENVELOPE, SQUARE_ENVELOPE);
}

function getEnvelopeDropdown(c) {
	// c is a container to update
	if (!c) return;
	
	new Ajax.Updater(c, 'getEnvelopeDropdown.php', { asynchronous: false });
}

function getA7orSquare() {

	new Ajax.Request("getA7orSquare.php?wid="+wedding_occasion_id,
		{
			asynchronous: false,
			onSuccess: function(transport){
				var response = transport.responseText;
				if (response) {
					var resp = response.split('<SCRIPT>');
					$('a7orSquare').innerHTML = resp[0];
					eval(resp[1]);
				}
				else {
					alert('Something went wrong 5a...');
					return false;
				}
			},
			onFailure: function(){
				alert('Something went wrong 5b...');
				return false;
			}
		}
	);
}

extension = function(c, skipSetCart, suffix, handleDiscount) {
	// c is the name of a container to update with an extension
	// skipSetCart is an option boolean
	// suffix is an optional field name suffix
	if (!c) return;

	var s = $(c+'select'+suffix);
	if (!s) return;
	
	var v = s.options[s.selectedIndex].value;
	var parr;
	var darr;
	try {
		parr = eval(s.getAttribute('cartkey')+'prices'+s.getAttribute('cartval'));
		aarr = eval(s.getAttribute('cartkey')+'prices'+s.getAttribute('cartval')+'addtl');
		darr = eval(s.getAttribute('cartkey')+'prices'+s.getAttribute('cartval')+'deduct');
	}
	catch (err) {
		//alert('setprices'+s.getAttribute('cartval')+' no good');
	}

	if (!parr) return;

	var e = parseFloat(parr[v]) + parseFloat(aarr[v]);
	var e2;
	if (e != parseInt(e)) {
		var f = ((e - parseInt(e)) + '').split('.')[1];
		if (f.length < 2) f += '0';
		e2 = '' + parseInt(e) + '.' + f;
	}
	else {
		e2 = e + '.00';
	} 
	$(c+suffix).innerHTML = e2;
	if (darr) $(c+suffix).setAttribute('deduct', parseFloat(darr[v]));
	
	if (!skipSetCart) {
		var SETB4 = getCartValue('SET');
		var ALACARTEB4 = getCartValue('ALACARTE');

		setCart(s.getAttribute('cartkey'), s.getAttribute('cartval'), 1, 1, v);
		
		// if something about selected pieces has changed...
		if (SETB4 != getCartValue('SET') || ALACARTEB4 != getCartValue('ALACARTE')) {
			updatePieceSelect();
		
			var PIECES = getCartValue('PIECES');
			var PATTERN = getCartValue('PATTERN');
	
			if (PIECES && PATTERN) {
				var currentID = PIECES.split('|')[currentpieceidx];
				selectPiece($('piecetop'+currentID), $('piecebottom'+currentID), currentpieceidx); 
			}
			
			if (!PIECES) {
				clearPreview();
				patternClicked($('pattern'+getCartValue('PATTERN')), getCartValue('PATTERN'));
			}
		}
	}
	
	doSubtotal(suffix, handleDiscount);
	
	// changed this to try to prevent "0.00" orders
	//if (suffix == 'Checkout') {
	if ($('piecestabletotalCheckout')) {
		var url = 'setCartValues.php?CART_TOTAL=' + $('piecestabletotalCheckout').innerHTML;
		new Ajax.Request(url,
			{
				method: 'get',
				asynchronous: false,
				onSuccess: function(transport){
					var response = transport.responseText || "no response text";
					if (response) {
						//eval(response);
					}
					else {
						alert('Something went wrong 6a...');
						return false;
					}
				},
				onFailure: function(){
					alert('Something went wrong 6b...');
					return false;
				}
			}
		);
	
		saveOrder();
	}
		
debugIt();
}


function saveOrder() {
		url = 'saveOrder.php';
		new Ajax.Request(url,
			{
				method: 'get',
				asynchronous: false,
				onSuccess: function(transport){
					var response = transport.responseText || "no response text";
					if (response) {
						//eval(response);
					}
					else {
						alert('Something went wrong onSuccess saveOrder...');
						return false;
					}
				},
				onFailure: function(){
					alert('Something went wrong onFailure saveOrder...');
					return false;
				}
			}
		);
}


function doSubtotal(suffix, handleDiscount) {
	// suffix is an optional field name suffix
	
	if (suffix == undefined) suffix = '';

	if (!$('pieceslist'+suffix)) return;

	var sub = 0;
	var deductforshipping = 0;
	var qtys = $('pieceslist'+suffix).getElementsByTagName('select');
	for (var i=0; i<qtys.length; i++) {
		var q = qtys[i];
		if (q.className == 'qtyelement') {
			//sub += q.options[q.selectedIndex].value * q.getAttribute('priceper');
			var extid = q.id.replace(/select.*$/, '');
			//if ($(extid+suffix)) sub += parseInt($(extid+suffix).innerHTML);
			if ($(extid+suffix)) {
				sub += parseFloat($(extid+suffix).innerHTML);
				deductforshipping += parseFloat($(extid+suffix).getAttribute('deduct'));
			}
		}
	}
	var sub2;
	var subtotal = sub;
	if (sub != parseInt(sub)) {
		var f = ((sub - parseInt(sub)) + '').split('.')[1];
		if (f.length < 2) f += '0';
		sub2 = '' + parseInt(sub) + '.' + f;
	}
	else {
		sub2 = sub + '.00';
	}
	$('piecestablesubamt'+suffix).innerHTML = sub2;

	var discount = 0;
	if ($('Discount_Code')) {
		if (handleDiscount && $('Discount_Code').value) {
			var url = 'validateDiscount.php?Discount_Code=' + escape($('Discount_Code').value) + '&Order_Subtotal=' + sub2;
			new Ajax.Request(url,
				{
					method: 'get',
					asynchronous: false,
					onSuccess: function(transport){
						var response = transport.responseText;
						if (response && response.match(/ERROR\^/)) {
							response = response.replace('ERROR\^', '');
							alert(response);
							$('Discount_Code').value = '';
							$('discountlabel').style.display = 'none';
							$('discountcontainer').style.display = 'none';
						}
						else {
							//alert('validateDiscount returned nothing!');
							discount = $('discount').innerHTML = response;
							$('discountlabel').style.display = 'block';
							$('discountcontainer').style.display = 'block';
							return false;
						}
					},
					onFailure: function(){
						alert('validateDiscount failed!');
						$('Discount_Code').value = '';
						$('discountlabel').style.display = 'none';
						$('discountcontainer').style.display = 'none';
						return false;
					}
				}
			);
		}
		else {
			$('Discount_Code').value = '';
			$('discountlabel').style.display = 'none';
			$('discountcontainer').style.display = 'none';
		}
	}

//alert(sub + ',' + deductforshipping);
	var savesub = sub;
	var subforshipping = sub - deductforshipping;
	var shipping = 0;
	if (subforshipping) {
		for (i=0; i<shippingBreaks.length; i++) {
			if (subforshipping <= shippingBreaks[i]) {
				shipping = shippingValues[i];
				break;
			}
		}
	}
	
	sub = shipping;
	if (sub != parseInt(sub)) {
		var f = ((sub - parseInt(sub)) + '').split('.')[1];
		if (f.length < 2) f += '0';
		sub2 = '' + parseInt(sub) + '.' + f;
	}
	else {
		sub2 = sub + '.00';
	}
	if ($('piecestableshipsubamt'+suffix)) {
		$('piecestableshipsubamt'+suffix).innerHTML = sub2;
		// debug only
		//$('piecestableshipsubhdr'+suffix).innerHTML = "(based on " + savesub + "-" + deductforshipping + "=" + subforshipping + ")";
	}
	
	sub = discount;
	if (sub != parseInt(sub)) {
		var f = ((sub - parseInt(sub)) + '').split('.')[1].substr(0,2);
		if (f.length < 2) f += '0';
		sub2 = '' + parseInt(sub) + '.' + f;
	}
	else {
		sub2 = sub + '.00';
	}
	discount = sub2;

	sub = parseFloat(subtotal) - discount + parseFloat(shipping);
	if (sub != parseInt(sub)) {
		var f = ((sub - parseInt(sub)) + '').split('.')[1].substr(0,2);
		if (f.length < 2) f += '0';
		sub2 = '' + parseInt(sub) + '.' + f;
	}
	else {
		sub2 = sub + '.00';
	}
	if ($('piecestableshipsubamt'+suffix)) $('piecestabletotal'+suffix).innerHTML = sub2;

	if (handleDiscount && $('Discount_Code')) {
		var url = 'setCartValues.php?CART_TOTAL=' + $('piecestabletotalCheckout').innerHTML + '&CART_DISCOUNT_CODE=' + $('Discount_Code').value;
		new Ajax.Request(url,
			{
				method: 'get',
				asynchronous: false,
				onSuccess: function(transport){
					var response = transport.responseText || "no response text";
					if (response) {
						//eval(response);
					}
					else {
						alert('Something went wrong 12a...');
						return false;
					}
				},
				onFailure: function(){
					alert('Something went wrong 12b...');
					return false;
				}
			}
		);
	}

debugIt();
}

function clearText() {
	for (var l=1; l<=20; l++) {
		document.forms[2].elements['line'+l].setAttribute('value', '');
		document.forms[2].elements['line'+l].value = '';
		document.forms[2].elements['line'+l].removeAttribute('font');
		document.forms[2].elements['line'+l].removeAttribute('spaceafter');
		//document.forms[2].elements['line'+l].style.marginBottom = '0px';
		$('line'+l+'container').style.marginBottom = '0px';
		document.forms[2].elements['line'+l].disabled = false;
		document.forms[2].elements['line'+l].removeAttribute('disabled'); // IE
		document.forms[2].elements['line'+l].style.backgroundColor = 'white';
	}
}

function setPlainText() {
	for (var l=1; l<=20; l++) {
		document.forms[2].elements['line'+l].setAttribute('value', '');
		document.forms[2].elements['line'+l].value = '';
		document.forms[2].elements['line'+l].setAttribute('font', 'Text');
		document.forms[2].elements['line'+l].setAttribute('spaceafter', 0);
		//document.forms[2].elements['line'+l].style.marginBottom = '0px';
		$('line'+l+'container').style.marginBottom = '0px';
		document.forms[2].elements['line'+l].disabled = false;
		document.forms[2].elements['line'+l].removeAttribute('disabled'); // IE
		document.forms[2].elements['line'+l].style.backgroundColor = 'white';
	}
}

function clearPreview() {
	clearText();
	
	if ($('previewTEXTinnerLink'))	$('previewTEXTinnerLink').style.display = 'none';
	if ($('previewBACKING'))		$('previewBACKING').style.display = 'none';
	if ($('previewICONsquare'))		$('previewICONsquare').style.display = 'none';
	if ($('previewSASH'))			$('previewSASH').style.display = 'none';
	if ($('hidesash'))				$('hidesash').style.display = 'none';
	
	var PATTERN = getCartValue('PATTERN');
	if (PATTERN) {
		var Size = $('pattern'+PATTERN).getAttribute('defaultSize'); 
		$('previewPATTERNimg').src = 'patterns_display_image.php/'+PATTERN+'/1/'+Size;
	}
	else {
		$('previewPATTERNimg').src = 'images/1x1.gif';
		$("patternsblock").style.display = 'none';
		//$("patternsblock").className="tabcontent";
	}
	// we do it this way since init_borders() depends on the pattern being loaded
	$('previewPATTERNimg').onload = init_borders;

	if ($('previewICONimg')) {
		$('previewICONimg').src = 'images/1x1.gif';
		//$('previewICONimg').width = 1;
		//$('previewICONimg').height = 1;
		$('previewICONimg').style.display = 'none';
	}
	if ($('previewBORDER'))			$('previewBORDER').style.background = 'url(images/1x1.gif) no-repeat';
	
	clearElement('previewTEXT');
	
	setCart('TEXT', '', 1, 0, 0);
	setCart('ICON', '', 1, 0, 0);
	setCart('BORDER', '', 1, 0, 0);
	setCart('BACKING', '', 1, 0, 0);
	updatePieceSelect();
	currentpieceindex = 0;
}

function selectEnvelope(s) {
	// s is a select element representing an envelope color
	if (!s) return;

	setCart('ENVELOPE', s.options[s.selectedIndex].value, 1, 0);
}

function selectSquareEnvelope(s) {
	// s is a select element representing a square envelope color
	if (!s) return;

	setCart('SQUARE_ENVELOPE', s.options[s.selectedIndex].value, 1, 0);
}

function updatePieceSelect() {
	new Ajax.Request('updatePieceSelect.php',
		{
			asynchronous: false,
			onSuccess: function(transport){
				var response = transport.responseText;
				if (response) {
					var resp = response.split('<SCRIPT>');
					$('piecesinnercontent').innerHTML = resp[0];
					eval(resp[1]);
				}
				else {
					alert('Something went wrong 7a...');
					return false;
				}
			},
			onFailure: function(){
				alert('Something went wrong 7b...');
				return false;
			}
		}
	);
debugIt();
}

function showIcons(s) {
	if (!s) return;
	
	var which = s.options[s.selectedIndex].value;
	
	var icons = $('iconlistmargin').getElementsByTagName('div');
	
	for (var i=0; i<icons.length; i++) {
		if (!which) {
			icons[i].style.display = 'block';
		}
		else {
			var itypes = icons[i].getAttribute('Icon_Type').split(',');
			var d = 'none';
			for (var t=0; t<itypes.length; t++) {
				if (itypes[t] == which) {
					d = 'block';
					break;
				}
			}
			icons[i].style.display = d;
		}
	}
}

function limitPiecesHeight(p, m) {
	if (p) p.style.height = p.offsetHeight > m ? m + 'px' : p.offsetHeight + 'px';
}

function removeElement(id)	{
	var Node = document.getElementById(id);
	Node.parentNode.removeChild(Node);
}

function clearElement(id) {
	var el = document.getElementById(id);
	while (el.firstChild) {
		el.removeChild(el.firstChild);
	}
}

function changePreview(i, k, v) {
	// i is the image clicked
	// k is the cart key
	// v is the cart value

	if (i.className == 'selected') {
		var PIECES = getCartValue('PIECES');
		if (k == 'ICON') {
			//var iconsrc ='icons_display_image.php/'+v+'/1' ;
			var iconsrc = 'images/icons/' + $('icon'+getCartValue('ICON')).getAttribute('previewname') + '-' + $('inkcolor'+v).getAttribute('previewcode') + '.png';
			// only or working on inside icon
			if ($("previewTEXTinnerLink").style.display != 'block' || $("showinside").style.display == 'none') {
				$('previewICONimg').style.display = 'none';
				//$('previewICONimg').width = i.getAttribute('Preview_Image_Width');
				//$('previewICONimg').height = i.getAttribute('Preview_Image_Height');
				$('previewICONimg').src = iconsrc;
				$('previewICONimg').style.display = 'inline';
			}
			// outside icon
			else {
				$('previewICONimgsquare').style.display = 'none';
				//$('previewICONimgsquare').width = i.getAttribute('Preview_Image_Width');
				//$('previewICONimgsquare').height = i.getAttribute('Preview_Image_Height');
				$('previewICONimgsquare').src = iconsrc;
				$('previewICONimgsquare').style.display = 'inline';
			}
		}
		else if (k == 'PATTERN') {
			var Size = PIECES ? $('piecetop'+PIECES.split('|')[currentpieceidx]).getAttribute('piecesize') : i.getAttribute('defaultSize'); 
			$('previewPATTERNimg').src = 'patterns_display_image.php/'+v+'/1/'+Size;
		}
		else if (k == 'BACKING') {
			var size = $('piecetop'+PIECES.split('|')[currentpieceidx]).getAttribute('piecesize');
			if (size == 'flat') size = '4bFLAT';
			if (!$("backingscontainer").innerHTML) getBackings("backingscontainer");
			$('previewBACKINGimg').src = 'images/backings/backing-'+size+$('backing'+v).getAttribute('previewcode')+'.png';
			$('previewBACKING').style.display = 'block';
		}
		else {
			$('preview'+k).style.background = 'url(' + k.toLowerCase() + 's_display_image.php/'+v+'/1) no-repeat';
		}
		$('preview'+k).style.display = 'block';
	}
	else {
		if (k == 'ICON') {
			// only or inside icon
			if ($("previewTEXTinnerLink").style.display != 'block' || $("showinside").style.display == 'none') {
				$('previewICONimg').src = 'images/1x1.gif';
				$('previewICONimg').style.display = 'none';
			}
			// outside icon
			else {
				$('previewICONimgsquare').src = 'images/1x1.gif';
				//$('previewICONimgsquare').width = 1;
				//$('previewICONimgsquare').height = 1;
				$('previewICONimgsquare').style.display = 'none';
			}
		}
		else if (k == 'PATTERN') {
			$('preview'+k).style.background = 'url(images/preview/nopattern.gif) no-repeat';
		}
		else {
			$('preview'+k).style.display = 'none';
		}
	}
}

function selectPiece(ttd, btd, pidx) {
	// ttd is the top td
	// btd is the bottom td
	// pidx is the index into the PIECES list (may be 0)
	if (!ttd || !btd) return;

	// set cart text for previous piece before moving to next piece
	setCartText(true, true);
	
	currentpieceidx = pidx;
	
	// set SESSION's CART_CURRENT_PIECE_INDEX value
	var url = 'setCartValues.php?CART_CURRENT_PIECE_INDEX=' + currentpieceidx;
	new Ajax.Request(url,
		{
			method: 'get',
			asynchronous: false,
			onSuccess: function(transport){
				var response = transport.responseText || "no response text";
				if (response) {
					eval(response);
				}
				else {
					alert('Something went wrong 8a...');
					return false;
				}
			},
			onFailure: function(){
				alert('Something went wrong 8b...');
				return false;
			}
		}
	);

	var textaligns = getCartValue('TEXTALIGN');
	var texts = getCartValue('TEXT');
	var PATTERN = getCartValue('PATTERN');
	var SASH = getCartValue('SASH');
	var BACKING = getCartValue('BACKING');
	var EMBELLISHMENT = getCartValue('EMBELLISHMENT');
	var PIECES = getCartValue('PIECES');
	var currenttabstep = getCartValue('CURRENT_TAB_STEP');

	//if (currenttabstep == 'types_tab') {
		getSuggestions();
	//}
	
	var ttds = ttd.parentNode.getElementsByTagName('td');
	var btds = btd.parentNode.getElementsByTagName('td');
	
	for (var i=0; i<ttds.length; i++) {
		ttds[i].className = ttds[i] == ttd ? "piecetoselectOnTop" : "piecetoselectOutTop";
		btds[i].className = btds[i] == btd ? "piecetoselectOnBottom" : "piecetoselectOutBottom";
	}
	
	init_types(0, 0, textaligns, texts);
	init_sashes(SASH,BACKING,EMBELLISHMENT);

	if (!PATTERN) {
		showAlphaMsgText('Please select a Pattern from the Patterns tab at left');
	}
	else {
		// show image for selected piece background
		skipsetthumbnail = false;
		init_patterns(skipsetthumbnail);
		var text = texts.split('|')[currentpieceidx];
		if (!text || text == '^') {
			var pieceimg = $('piecetop'+getCartValue('PIECES').split('|')[currentpieceidx]);
			if ($('previewTEXTimg') && pieceimg && pieceimg.getAttribute('piecesquare') == '1' && pieceimg.getAttribute('piecesize') == 'fold') {
				$('previewTEXTimg').src = 'images/1x1.gif';
				$('previewTEXTimg').style.width = 1;
				$('previewICONandTEXT').style.width = 100;
			}
		}
		else {
			createPreviewTextImage();
		}
	}
	init_icons();
	
	// if piece has 'show inside/outside' links, and we're on the 'types' tab, pretend they clicked 'show inside'
	if ($('previewTEXTinnerLink').style.display != 'none' && currenttabstep == 'types_tab') {
		$('showinside').onclick();
	}

debugIt();
}

function createPreviewTextImage() {
	// create text image for selected piece

	var PIECES = getCartValue('PIECES');
	var imw;
	if (PIECES && $('piecetop'+PIECES.split('|')[currentpieceidx]).getAttribute('piecesquare') == 1) {
		var Size = $('piecetop'+PIECES.split('|')[currentpieceidx]).getAttribute('piecesize'); 
		imw = square_text_sizes[Size][0] - 20;
		$('previewTEXT').style.left = '10px';
		if ($('previewTEXT').style.offsetWidth) $('previewICON').style.width = ($('previewTEXT').style.offsetWidth + 5) + 'px';
	}
	else {
		imw = square_text_sizes['default'][0];
		$('previewTEXT').style.left = '0px';
		$('previewICON').style.width = 'auto';
	}

	var url = 'createPreviewTextImage.php?imw='+imw;
	showBuildingPreview();
	
	new Ajax.Request(url,
		{
			method: 'get',
			asynchronous: false,
			onSuccess: function(transport){
				var response = transport.responseText || "no response text";
				if (response) {
					//alert(response);
					
					// remove it
					//if ($('previewTEXTimg')) removeElement('previewTEXTimg');
					// recreate it
					var i = document.createElement('IMG');
					i.id = 'previewTEXTimg';
					var now = new Date();
					i.src = "previewtxt/" + session + ".png?" + now.getTime();
					i.onload = function () {
						clearElement('previewTEXT');
						$('previewTEXT').appendChild(i);
						//hideAlpha($('buildingpreview'));
						$('buildingpreview').style.visibility = 'hidden';
					}
				}
				else {
					alert('Something went wrong 9a...');
					return false;
				}
			},
			onFailure: function(){
				alert('Something went wrong 9b...');
				return false;
			}
		}
	);
}

function iconClicked(i, id) {
	// i is an icon image
	if (!i || !id) return;

	var PIECES = getCartValue('PIECES');

	if (!PIECES) {
		showAlphaMsgText('Please select pieces first');
		return;
	}
	
	var icontext = '';
	if (i.className != 'selected' && i.parentNode.getAttribute('Icon_Type') == 'Monograms') {
		var missing = false;
		var letters = i.parentNode.getElementsByTagName('INPUT');
		var msg = 'Note that the preview will not show your letter(s) but that your proof will.';
		for (var l=0; l<letters.length; l++) {
			if (!letters[l].value.match(/\S/)) {
				missing = true;
				break;
			}
			icontext += letters[l].value;
		}
		if (missing) {
			msg = "Please enter letter(s) for this icon.\n" + msg;
		}
		showAlphaMsgText(msg);
		if (missing) {
			return;
		}
	}

	setCart('ICON', i.getAttribute('cartval'), (/^selected/.test(i.className) ? 0 : 1), 0, 0, icontext);
	init_icons();
}

function noA6Selected(noalert) {
	// noalert is a boolean

	var noA6 = true;
	
	var tds = Array();
	if ($('piecetoselecttable')) tds = $('piecetoselecttable').getElementsByTagName('td');
	
	if (!tds.length) {
		if (!noalert) showAlphaMsgText('Please select pieces first');
		return noA6;
	}
	
	for (var i=0; i<tds.length; i++) {
		if (tds[i].getAttribute('piecesize') == 'A6' && currentpieceidx == i) {
			noA6 = false;
			break;
		}
	}
	
	if (noA6 && !noalert) showAlphaMsgText("Sorry! Skinny Belts, Obis, and Sashes are only available for large flat cards.");
	
	return noA6;
}

function noFlatSelected(noalert) {
	// noalert is a boolean

	var noFlat = true;
	
	var tds = Array();
	if ($('piecetoselecttable')) tds = $('piecetoselecttable').getElementsByTagName('td');
	
	for (var i=0; i<tds.length; i++) {
		var piecesize = tds[i].getAttribute('piecesize');
		if ((piecesize == 'A6' || piecesize == 'flat') && currentpieceidx == i) {
			noFlat = false;
			break;
		}
	}
	
	if (noFlat && !noalert) showAlphaMsgText("Sorry! Backings are only available on flat, unfolded pieces.");

	return noFlat;
}

function borderAllowed(noalert) {
	// noalert is a boolean

	if (!patternChosen()) {
		return false;
	}
	else {
		if ($('pattern'+getCartValue('PATTERN')).getAttribute('No_Borders') == 1) {
			if (!noalert) showAlphaMsgText("Sorry! Borders just don't work on this pattern. Please select another pattern if you'd like to use a border.");
			return false;
		}
		else {
			return true;
		}
	}
}

function backingAllowed(noalert) {
	// noalert is a boolean

	if (!patternChosen()) {
		return false;
	}
	else {
		if ($('pattern'+getCartValue('PATTERN')).getAttribute('No_Backings') == 1) {
			if (!noalert) showAlphaMsgText("Sorry! Backings just don't work on this pattern. Please select another pattern if you'd like to use a backing.");
			return false;
		}
		else {
			return true;
		}
	}
}

function occasionChosen() {

	if (!getCartValue('OCCASION')) {
		showAlphaMsgText('Please select an Occasion from the Patterns tab at left');
		return false;
	}
	
	return true;
}

function patternChosen() {

	if (!occasionChosen()) {
		return false;
	}
		
	if (!getCartValue('PATTERN')) {
		showAlphaMsgText('Please select a Pattern from the Patterns tab at left');
		return false;
	}
	
	return true;
}

function piecesChosen() {

	if (!patternChosen()) {
		return false;
	}
		
	if (!getCartValue('PIECES')) {
		showAlphaMsgText('Please select Pieces from the Pieces tab at left');
		return false;
	}
	
	return true;
}

function handleTextarea(w, op, t) {
	// w is which textarea type (idea, address, etc)
	// op is the event (focus, blur)
	// t is a textarea element
	if (!w || !op || !t) return;
	
	var default_text = eval('default_'+w+'_text');
	
	if (!default_text) return;
	
	if (op == 'focus') {
		if (t.value == default_text) {
			t.value = '';
		}
	}
	
	if (op == 'blur') {
		if (t.value != default_text) {
			if (!t.value.match(/\S/)) t.value = '';
			setCart(t.name, t.value, 1, 0);
		}
		if (t.value == '') {
			t.value = default_text;
		}
	}
}

function occasionSelected() {	
	showLoading();
	window.setTimeout(occasionSelected2, 500);
}

function occasionSelected2() {
	var s = $('occasion');
	
	setCart('OCCASION', s.options[s.selectedIndex].value, 1, 0);
	
	clearPreview();
	
	if (s.selectedIndex > 0) {
		//getAllCartValues();
		getPatterns("patternslistmargin");
		// select the first pattern
		var pis = $('patternslistmargin').getElementsByTagName('img');
		patternClicked(pis[0], pis[0].getAttribute('cartval'));
		createPreviewTextImage();
	}

	hideAlpha($('loading'));
}

function borderClicked(i) {
	// i is this border thumbnail
	if (!i) return;
	
	var PIECES = getCartValue('PIECES');
	
	var c = /^selected/.test(i.className) ? 0 : 1;
	
	if (PIECES && inkSelected() && borderAllowed()) {
		setCart('BORDER', i.getAttribute('cartval'), c, 0);
		init_borders();
	}
}

function inkSelected() {
	if (!getCartValue('INKCOLOR')) {
		showAlphaMsgText ('Please select an Ink Color from the Type & Ink tab');
		return false;
	}
	
	return true;
}

function inkcolorClicked(i) {
	// i is the inkcolor image
	if (!i) return;
	
	//setCart('INKCOLOR', i.getAttribute('cartval'), (/^selected/.test(i.className) ? 0 : 1), 0);
	setCart('INKCOLOR', i.getAttribute('cartval'), null, 0);
	hiliteInkColor(i, $('inkcolors'));
	init_borders();
	setCartText(null, true);
	init_icons();
}

function sashClicked(s, sID) {
	// s is the sash icon clicked
	// sID is the sash db rcd ID
	if (!s || !sID) return;
	
	if (noA6Selected(false)) {
		return;
	}
	
	//getAllCartValues();
	hiliteImage(s, $('sashlist'), 1);
	setCart('SASH', s.getAttribute('cartval'), (/^selected/.test(s.className) ? 1 : 0), 0);
	$('hidesashhide').style.display = '';
	$('hidesashshow').style.display = 'none';
	$('hidesash').style.display = (s.className == 'selected') ? 'block' : 'none';
	changePreview(s, 'SASH', sID);
}

function getSuggestions(dontrender) {
	new Ajax.Request('getSuggestions.php',
		{
			asynchronous: false,
			onSuccess: function(transport){
				var response = transport.responseText;
				if (response) {
					var resp = response.split('<SCRIPT>');
					$('suggestiondropdown').innerHTML = resp[0];
					eval(resp[1]);
					//$('inspirationcontainer').style.display = (sdefs.length == 0 ? 'none' : 'block');
					$('inspirationcontainer').style.visibility = (sdefs.length == 0 ? 'hidden' : 'visible');
				}
				else {
					alert('Something went wrong 10a...');
					return false;
				}
			},
			onFailure: function(){
				alert('Something went wrong 10b...');
				return false;
			}
		}
	);

	var text = getCartValue('TEXT').split('|')[currentpieceidx];
	//if ((!text || text == '^')) {
	var pieceimg = $('piecetop'+getCartValue('PIECES').split('|')[currentpieceidx]);
	$('wording').style.display = 'block';
	$('nowording').style.display = 'none';
	if (!text || text == '^') {
		if (pieceimg.getAttribute('piecesquare') == '1' && pieceimg.getAttribute('piecesize') == 'fold') {
			clearText();
			//disableText(1);
			// don't show text stuff at all
			$('wording').style.display = 'none';
			$('nowording').style.display = 'block';
		}
		else {
			showSuggestionText($('suggestion'), true, dontrender);
		}
	}
		
	// if piece has 'show inside/outside' links, and we're on the 'types' tab, pretend they clicked 'show inside'
	//if ($('previewTEXTinnerLink').style.display == 'block' && getCartValue('CURRENT_TAB_STEP') == 'types_tab') {
	var PIECES = getCartValue('PIECES');
	if (PIECES && $('piecetop'+PIECES.split('|')[currentpieceidx]).getAttribute('piecesize') == 'square' && getCartValue('CURRENT_TAB_STEP') == 'types_tab') {
		$('showinside').onclick();
	}
}

function showSuggestionText(s, showfirst, dontrender) {
	// s is a select element
	// showfirst is optional
	// dontrender is optional
	if (!s || (s.selectedIndex < 1 && !showfirst)) return;
	
	var si = showfirst ? 1 : s.selectedIndex;
	try {
		s.selectedIndex = si;
	}
	catch (err) {
		//alert(err);
	}

	if (s.options[si]) {
		clearText();
	
		var sarr = sdefs[s.options[si].value];
		for (var sa=0; sa<sarr.length; sa++) {
			document.forms[2].elements['line'+(sa+1)].setAttribute('value', sarr[sa][0]);
			document.forms[2].elements['line'+(sa+1)].value = sarr[sa][0];
			document.forms[2].elements['line'+(sa+1)].setAttribute('font', sarr[sa][1]);
			$('lineT'+(sa+1)).className = 
				$('lineL'+(sa+1)).className = 
					$('lineN'+(sa+1)).className =
						$('lineM'+(sa+1)).className = 
							$('lineP'+(sa+1)).className = 'TLNoff';
			$('line'+fontMap[sarr[sa][1]]+(sa+1)).className = 'TLNon';
			document.forms[2].elements['line'+(sa+1)].setAttribute('spaceafter', sarr[sa][2]);
			//document.forms[2].elements['line'+(sa+1)].style.marginBottom = sarr[sa][2] == 0 ? '0px' : '10px';
			$('line'+(sa+1)+'container').style.marginBottom = sarr[sa][2] == 0 ? '0px' : '10px';
			document.forms[2].elements['line'+(sa+1)].disabled = false;
			document.forms[2].elements['line'+(sa+1)].removeAttribute('disabled'); // IE
			document.forms[2].elements['line'+(sa+1)].style.backgroundColor = 'white';
		}
		if (sarr.length<20) {
			disableText(sarr.length+1);
		}
		
		// reset dropdown
		//s.selectedIndex = 0;
	}
	else {
		setPlainText();
	}
	
	if (!dontrender) setCartText();
}

function disableText(from) {
	for (var sa=from; sa<=20; sa++) {
		document.forms[2].elements['line'+sa].setAttribute('value', '');
		document.forms[2].elements['line'+sa].value = '';
		document.forms[2].elements['line'+sa].setAttribute('font', 'Text');
		$('lineT'+sa).className = 'TLNon';
		$('lineL'+sa).className = 
			$('lineN'+sa).className = 
				$('lineM'+sa).className = 
					$('lineP'+sa).className = 'TLNoff';
		//document.forms[2].elements['line'+sa].removeAttribute('spaceafter');
		document.forms[2].elements['line'+sa].setAttribute('spaceafter', 0);
		//document.forms[2].elements['line'+sa].style.marginBottom = '0px';
		$('line'+sa+'container').style.marginBottom = '0px';
		//document.forms[2].elements['line'+sa].disabled = true;
		//document.forms[2].elements['line'+sa].setAttribute('disabled', 'disabled'); // IE
		//document.forms[2].elements['line'+sa].style.backgroundColor = '#ccc';
	}
}

function showItemDetails(pid, idx, a) {
	// pid is a product ID
	// idx is an index into the PIECES list
	// a is the a tag clicked to get here
	if (!pid) return;
	
	if ($("details"+pid).style.display == "none") {
		a.innerHTML = 'hide details';
		$("details"+pid).style.display = isIE ? 'block' : 'table-row';
		// show the piece in the preview area to the lower right
		selectPiece($("piecetop"+pid), $("piecebottom"+pid), idx);
	}
	else {
		a.innerHTML = 'show details';
		$("details"+pid).style.display = "none";
	}
}

function patternOver(i) {
	// i is the pattern image
	if (!i) return;

	var ileft = itop = 0;
	var el = i;
	if (el.offsetParent) {
		do {
			ileft += el.offsetLeft;
			itop  += el.offsetTop;
			if (el.offsetParent && el.offsetParent.offsetParent) itop  -= el.offsetParent.scrollTop; // account for container scroll
		} while (el = el.offsetParent);
	}

	var p  = $('patternpopup');
	//ps.background = 'url(images/patternpopups/' + i.getAttribute('code') + '_over.png) no-repeat';
	//pi.src = '/images/patternpopups/' + i.getAttribute('code') + '_over.png';
	var imgs = p.getElementsByTagName('IMG');
	for (var x=0; x<imgs.length; x++) {
		imgs[x].style.display = 'none';
	}
	$(i.getAttribute('code')+'patternpopup').style.display = '';
	var ps = p.style;
	p.onclick = function () { patternClicked(i, i.getAttribute('cartval')); }
	ps.left = (ileft - (p.offsetWidth - i.offsetWidth)/2) + 'px';
	ps.top  = (itop - p.offsetHeight + i.offsetHeight + 40) + 'px';
}

function patternClicked(i, ID) {
	// i is the pattern image clicked
	if (!i) return;
	
	setCart('PATTERN', ID, 1, 0);
//alert(i);
	init_patterns();
	getPieces('piecestable');
	updatePieceSelect();
	changePreview(i, 'PATTERN', ID);
	init_icons();
	getEnvelopeDropdown("envelopeDropdown");
	var SASH = getCartValue('SASH');
	var BACKING = getCartValue('BACKING');
	var EMBELLISHMENT = getCartValue('EMBELLISHMENT');
	init_sashes(SASH, BACKING, EMBELLISHMENT);
}

/* these not used since popups introduced
function fontOver(i) {
	// i is the font image 
	if (!i || i.className == 'selected') return;
	
	i.src = 'fonts_display_image.php/' + i.getAttribute('cartval') + '/0/selected';
}

function fontOut(i) {
	// i is the font image 
	if (!i || i.className == 'selected') return;
	
	i.src = 'fonts_display_image.php/' + i.getAttribute('cartval') + '/0/notSelected';
}

function fontClicked(i) {
	// i is this font thumbnail
	if (!i) return;
	
	if (!i.className.match(/^selected/)) {
		getAllCartValues();
		var curfont = getCartValue('FONTSTYLE');
		if (curfont) {
			$('fontstyle'+curfont).src = 'fonts_display_image.php/' + curfont + '/0/notSelected';
		}
		setCart('FONTSTYLE', i.getAttribute('cartval'), (/^selected/.test(i.className) ? 0 : 1), 0);
		//$('fontstyle'+i.getAttribute('cartval')).src = 'fonts_display_image.php/' + i.getAttribute('cartval') + '/0/selected';
		i.src = 'fonts_display_image.php/' + i.getAttribute('cartval') + '/0/selected';
		hiliteImage(i, i.parentNode, null, true);
		setCartText(null, true);
	}
}
*/

function fontOver(i) {
	// i is the font image
	if (!i) return;

	var ileft = itop = 0;
	var el = i;
	if (el.offsetParent) {
		do {
			ileft += el.offsetLeft;
			itop  += el.offsetTop;
			if (el.offsetParent && el.offsetParent.offsetParent) itop  -= el.offsetParent.scrollTop; // account for container scroll
		} while (el = el.offsetParent);
	}

	var p  = $('fontpopup');
	//ps.background = 'url(images/patternpopups/' + i.getAttribute('code') + '_over.png) no-repeat';
	//pi.src = '/images/patternpopups/' + i.getAttribute('code') + '_over.png';
	var imgs = p.getElementsByTagName('IMG');
	for (var x=0; x<imgs.length; x++) {
		imgs[x].style.display = 'none';
	}
	$(i.getAttribute('code')+'fontpopup').style.display = '';
	var ps = p.style;
	p.onclick = function () { fontClicked(i, i.getAttribute('cartval')); }
	ps.left = (ileft - (p.offsetWidth - i.offsetWidth)/2) + 10 + 'px';
	ps.top  = (itop - p.offsetHeight + i.offsetHeight) + 'px';
}

function fontClicked(i, ID) {
	// i is the pattern image clicked
	if (!i) return;
	
	// un-hilite exiting font (if any)
	f = getCartValue('FONTSTYLE');
	if (f) $('fontstyle'+f).src = 'fonts_display_image.php/' + f + '/0/notSelected';
	
	// set and hilite this font
	setCart('FONTSTYLE', ID, 1, 0);
	i.src = 'fonts_display_image.php/' + ID + '/0/selected';
	
	createPreviewTextImage();
}

function showInsideClicked(a) {
	// a is the link element
	if (!a) return;

	$("previewICONandTEXT").style.display="block";
	a.style.display="none";
	$("showoutside").style.display="inline";
	hiliteIcon(1);
	$('wording').style.display = 'block';
	$('nowording').style.display = 'none';
}

function showOutsideClicked(a) {
	// a is the link element
	if (!a) return;
	
	$("previewICONandTEXT").style.display="none";
	a.style.display="none";
	$("showinside").style.display="inline";
	hiliteIcon(0);
	$('nowording').style.display = 'block';
	$('wording').style.display = 'none';
}

function hideShowSashClicked() {
	// they clicked Hide
	if ($('hidesashshow').style.display == 'none') {
		$('previewSASH').style.display = 'none';
		$('hidesashshow').style.display =  'inline';
		$('hidesashhide').style.display =  'none';
	}
	// they clicked Show
	else {
		$('previewSASH').style.display = 'block';
		$('hidesashshow').style.display =  'none';
		$('hidesashhide').style.display =  'inline';
	}
}

function showAlphaLayer() {
	$('alphaLayer').style.width = document.body.scrollWidth + 'px';
	$('alphaLayer').style.height = document.body.scrollHeight + 'px';
	$('alphaLayer').style.display = 'block';
}

function hideAlpha(el) {
	if (el) el.style.top='-1000px';
	$('alphaLayer').style.display = 'none';
}

function centerElement(el) {
	if (!el) return;
	
	//el.style.left = document.body.scrollLeft + ((document.body.clientWidth - parseInt(el.offsetWidth))/2) + 'px';
	//el.style.top = (document.body.scrollTop + (document.body.clientHeight - parseInt(el.offsetHeight))/2) + 'px';
	el.style.left = (document.body.scrollLeft + (document.body.clientWidth  - parseInt(el.offsetWidth) )/2) + 'px';
	el.style.top  = (document.body.scrollTop  + (document.body.clientHeight - parseInt(el.offsetHeight))/2) + 'px';
}

function showLoading() {
	showAlphaLayer();
	centerElement($('loading'));
}

function showBuildingPreview() {
//return;
	//showAlphaLayer();
	//$('buildingpreview').style.top = '175px';
	$('buildingpreview').style.visibility = 'visible';
}

function showAlphaMsgText(m) {
	if (!m) m = '';
	
	showAlphaLayer();
	$('alphaMsgText').innerHTML = m;
	centerElement($('alphaMsg'));
}

function showToAFriend() {
	showAlphaLayer();
	
	// clear form, but keep yourname and youremail
	var urname  = $('toafriendform').yourname.value;
	var uremail = $('toafriendform').youremail.value;
	clearFormFields($('toafriendform'));
	$('toafriendform').yourname.value  = urname;
	$('toafriendform').youremail.value = uremail;
	
	$('toafriendformcontainer').style.display = 'block';
	$('toafriendthanks').style.display = 'none';
	
	//$('toafriend').style.left = document.body.scrollLeft + ((document.body.clientWidth - parseInt($('toafriend').offsetWidth))/2) + 'px';
	//$('toafriend').style.top = (document.body.scrollTop + (document.body.clientHeight - parseInt($('toafriend').offsetHeight))/2) + 'px';
	centerElement($('toafriend'));
}

function handleToAFriend(f) {
	// edit form and build params along the way
	var params = '';
	if (!f.yourname.value || !f.youremail.value) {
		alert('We need your name and email address');
		return;
	}
	if (!validEmail(f.youremail)) {
		alert("Your email address is not valid");
		return;
	}
	params += 'yourname='+encodeURI(f.yourname.value)+'&';
	params += 'youremail='+encodeURI(f.youremail.value)+'&';
	var onerecip = false;
	for (var i=1; i<=5; i++) {
		if (f.elements['recipname'+i].value || f.elements['recipemail'+i].value) {
			onerecip = true;
		}
	}
	if (!onerecip) {
		alert('We need at least one recipient name and email address');
		return;
	}
	else {
		for (var i=1; i<=5; i++) {
			if (f.elements['recipname'+i].value || f.elements['recipemail'+i].value) {
				if (!f.elements['recipname'+i].value || !f.elements['recipemail'+i].value) {
					alert('We need a name and an email address for each recipient');
					return;
				}
				else {
					if (!validEmail(f.elements['recipemail'+i])) {
						alert("Recipient #"+i+"'s email address is not valid"+" ("+f.elements['recipname'+i].value+")");
						return;
					}
					else {
						params += 'recipname'+i+'='+encodeURI(f.elements['recipname'+i].value)+'&';
						params += 'recipemail'+i+'='+encodeURI(f.elements['recipemail'+i].value)+'&';
					}
				}
			}
		}
	}
	params += 'comments='+encodeURI(f.elements['comments'].value);
	$('toafriendsubmit').style.display = 'none';
	$('toafriendpleasewait').style.display = 'block';
	new Ajax.Request('toafriend.php?'+params,
		{
			method: 'get',
			asynchronous: false,
			onSuccess: function(transport){
				var response = transport.responseText;
				if (response) {
				}
				else {
					alert('Something went wrong 11a... ('+response+')');
					return false;
				}
			},
			onFailure: function(){
				alert('Something went wrong 11b...');
				return false;
			}
		}
	);
	$('toafriendformcontainer').style.display = 'none';
	$('toafriendsubmit').style.display = 'block';
	$('toafriendpleasewait').style.display = 'none';
	$('toafriendthanks').style.display = 'block';
}

function setLineFont(l, f) {
	// do nothing if already selected
	if ($('line'+fontMap[f]+l).className == 'TLNon') return;
	
	wasf = document.forms[2].elements['line'+l].getAttribute('font');
	
	document.forms[2].elements['line'+l].setAttribute('font', f);
	$('lineT'+l).className = $('lineL'+l).className = $('lineN'+l).className = 'TLNoff';
	$('lineM'+l).className = $('lineP'+l).className = 'TLNoff';
	$('line'+fontMap[f]+l).className = 'TLNon';
	if (fontMap[f] == 'M') {
		// no, leave the line alone - the text doesn't matter now, but user may want to resurrect what was there
		//document.forms[2].elements['line'+l].value = '[[map]]';
	}
	else if (fontMap[f] == 'P') {
		// no, leave the line alone - the text doesn't matter now, but user may want to resurrect what was there
		//document.forms[2].elements['line'+l].value = '[[photo]]';
	}
	else if (wasf == 'Map' || wasf == 'Photo') {
		// no, leave the line alone - the text doesn't matter now, but user may want to resurrect what was there
		//document.forms[2].elements['line'+l].value = '';
	}
	setCartText();
}

function debugIt() {
return;
	new Ajax.Updater('debug', 'getDebug.php', { asynchronous: false, evalScripts: true } );
}
