function flash_write(file, width, height, name) { 
	document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="'+width+'" height="'+height+'" id="'+name+'" ><param name="movie" value="'+file+'" /><param name="allowScriptAccess" value="sameDomain" /><param name="wmode" value="transparent" /><param name="menu" value="false" /><!--[if !IE]> <--> <object type="application/x-shockwave-flash" name="'+name+'" data="'+file+'"  width="'+width+'" height="'+height+'" allowScriptAccess="sameDomain" wmode="transparent"></object><!--> <![endif]--></object>');
}



function fontChange(fontval)
{
	//document.getElementById(currentFont).className = '';
	//document.getElementById(fontval).className = 'on';
	currentFont = fontval;
	canvas.setFont(fontval);	
}
function colorChange(color) {
	canvas.utils.colorText(color);
}
function bg_insert(file, pedestal) {
	canvas.loadBackground(file, pedestal);
}

function pedestalColor(color) {
	switch(color) {
		case 0xFFFFFF:
			return 0x000000;
		case 0xFFFF20:
			return 0x048f04;
		default:
			return 0xFFFFFF;
	}
}

function bgswitch() {
	var id = document.getElementById('background').value;
	for ( var x = 0; x < document.getElementById('background').options.length; x++ ) {
		var oldId = document.getElementById('background').options[x].value;
		document.getElementById('bg_'+oldId).style.display = 'none';
	}
	document.getElementById('bg_'+id).style.display = '';
}

function NewWindow2(mypage, myname, w, h, scroll) {
var winl = (screen.width - w) / 2;
var wint = (screen.height - h) / 2;
winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable=yes'
win = window.open(mypage, myname, winprops)
if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
return win;
}

var currentFont = 'Times New Roman';

function setFont(font) {
	document.getElementById(currentFont).className = '';
	document.getElementById(font).className = 'on';
	currentFont = font;
}

function getFont() {
	return currentFont;
}

function NewWindow(mypage, myname, w, h, scroll) {
var winl = (screen.width - w) / 2;
var wint = (screen.height - h) / 2;
winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable=yes,,toolbar=no,menubar=no'
win = window.open(mypage, myname, winprops)
if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}



var color_width = 255;
var color_height = 100;

function colorPick(e, set) {
	var x = e.clientX - $('picker').offsetLeft - $('picker').offsetParent.offsetLeft - $('picker').offsetParent.offsetParent.offsetLeft;
	var y = e.clientY - $('picker').offsetTop - $('picker').offsetParent.offsetTop - $('picker').offsetParent.offsetParent.offsetTop;
	var r = getXColor(x, 0.13 * color_width);
	r = getYColor(r, y);

	var g = getXColor(x, 0.38 * color_width);
	g = getYColor(g, y);
	var b = getXColor(x, 0.88 * color_width);
	b = getYColor(b, y);
	document.getElementById('color_prev').style.backgroundColor = 'rgb('+Math.round(r)+','+Math.round(g)+','+Math.round(b)+')';
	if ( set ) {
		colorChange(d2h(Math.round(r))+d2h(Math.round(g))+d2h(Math.round(b)));
	}
	
}

function getXColor(x_position, x_base) {
	var direct_diff = Math.abs(x_base - x_position);
	var round_diff = color_width - direct_diff;
	var x_diff = Math.min(direct_diff, round_diff);
	x_diff *= 3;
	x_diff = Math.min(color_width, x_diff);
	var color = 255 - (255 * x_diff / color_width);
	return color;
}

function getYColor(x_color, y_position) {
	var color_diff = Math.abs(255 - x_color);
	var color = x_color + (color_diff * y_position / color_height);
	color = Math.min(color, 255);
	return color;
}

var hD="0123456789ABCDEF";
function d2h(d) {
var h = hD.substr(d&15,1);
while(d>15) {d>>=4;h=hD.substr(d&15,1)+h;}
return h;
}

var currentColor = '000000';

function setColor(clr) {
	clr = d2h(clr);
	while ( clr.length < 6 ) {
		clr = '0'+clr;
	}
	if ( document.getElementById('color_'+clr) ) {
		document.getElementById('color_'+currentColor).className = '';
		document.getElementById('color_'+clr).className = 'on';
		currentColor = clr;
	}
	

}

function getShockwaveVersion()
{
  // Set local variables to avoid crashing bug
  var thearray = navigator.plugins;
  var arraylength = thearray.length;
  for (i=0; i<arraylength; i++)
  {
    theplugin = thearray[i];
    // Retrieve the plugin
    thename   = theplugin.name;
    // Get the plugin name
    thedesc   = theplugin.description;
    // Get the plugin description
      // If the plugin is the Shockwave Player...
      if (thedesc.indexOf("Shockwave")
        != -1 && thedesc.indexOf("Director") != -1)
        { 
        // ...parse out the version...
        versionString = thedesc.substring(thedesc.indexOf("version ") + 8);
        // ...pet the major version...
        majorVersion = parseInt(versionString);
        // ...and return it.
        return majorVersion;
        } 
   }
   // If we've went through the whole list of plugins without
   // finding Shockwave, we return zero.
   return 0;
}

var prevpop;
var rootbase = '';

function pop3d() {
	//prevpop = NewWindow2(rootbase+'wait', 'preview', 640, 657); 
}
function preview3d(base) {
    prevpop = NewWindow2(base+'wait', 'preview', 657, 620, 'yes');
    canvas.save('preview');
}

function noshock(base) {
	prevpop = NewWindow2(base+'waitnoshock', 'preview', 500, 580, 'yes');
	canvas.save('noshock');
}

function cancelpreview() {
	if ( prevpop ) { prevpop.close(); }
}


function clearpopup() {
	if ( typeof(prevpop) != 'undefined' ) {
		prevpop.close();
	}
}

function watchfocus() {
	window.onactivate = clearpopup;
	window.onfocus = clearpopup;
	window.document.onfocus = clearpopup;
	window.document.onactive = clearpopup;
	window.document.onclick = clearpopup;
	window.document.onmousedown = clearpopup;
	window.document.body.onclick = clearpopup;
	window.document.body.onmousedown = clearpopup;
	window.document.body.onresizestart = clearpopup;
	window.document.body.onbeforeactivate = clearpopup;
	window.document.body.onfocusin = clearpopup;
	window.document.body.onactivate = clearpopup;
	window.document.body.onbeforeeditfocus = clearpopup;
	window.document.body.ondrag = clearpopup;
	window.document.body.ondragstart = clearpopup;
	window.document.body.onscroll = clearpopup;
	window.document.body.onfocus = clearpopup;
	window.document.body.onclick = clearpopup;
	window.document.body.oncontextmenu = clearpopup;
	window.document.body.ondblclick = clearpopup;
	window.document.body.onselectstart = clearpopup;
}

var currentLid = 'lid1';
function lidpick(elem) {
	document.getElementById(currentLid).className = "";
	elem.className = "selected";
	currentLid = elem.id;
	canvas.setlid(currentLid);
}

function lidretreived(color) {
	lidpick(document.getElementById(color));
}

function focusfix() {
	document.getElementById('focusfixer').focus();
	canvas.focus();
}

function noflash() {
	drawDialog("<strong>This Website Requires Flash</strong><br />We have detected that you do not have the Flash player installed. You will need to download it in order to use this site.", 'window.open("http://www.adobe.com/go/getflashplayer", "_blank"); askreload();', null, 'Go here to Download Now', '' );
}

function askreload() {
	drawDialog("Please wait for installation of the Flash player", 'document.location.reload();', null, 'Continue', '');
}

var dialog_yes;
var dialog_no;



function drawDialog(text, yesCallback, noCallback, yestext, notext) {
    dialog_yes = yesCallback;
    dialog_no = noCallback;

    if ( yestext == undefined ) {
        yestext = 'Yes';
    }
    if ( notext == undefined ) {
        notext = 'No';
    }
	
    var backdrop = document.createElement('div');
    backdrop.id = 'blackout';
    document.body.appendChild(backdrop);
    backdrop.style.height = getPageSizeWithScroll()[1] + 'px';
    backdrop.style.width = document.body.clientWidth + 'px';

    var dialog = document.createElement('div');
    dialog.id = 'dialog';
    document.body.appendChild(dialog);
	
    dialog.innerHTML = text;
    if ( yestext != '') { 
    	dialog.innerHTML += '<a href="javascript: dialogCallback(true);" class="dialog_link">'+yestext+'</a>';
    }
    if ( notext != '' ) {
    	dialog.innerHTML += '<a href="javascript: dialogCallback(false);" class="dialog_link">'+notext+'</a>'
    }
    dialog.style.top = ( getOffsetTop(document.getElementById('top_toolbar')) - dialog.offsetHeight + document.getElementById('top_toolbar').offsetHeight ) + 'px';
    
}

function getOffsetTop(elem) {
	if ( elem.offsetParent ) {
		return elem.offsetTop + getOffsetTop(elem.offsetParent);
	} else {
		return elem.offsetTop;
	}
}

function dialogCallback(result) {
    document.body.removeChild(did('blackout'));
    document.body.removeChild(did('dialog'));

    if ( result ) {
        eval(dialog_yes);
    } else {
        eval(dialog_no);
    }
}

function clearDialog() {
	document.body.removeChild(did('blackout'));
	document.body.removeChild(did('dialog'));
}

function did(id) {
    return document.getElementById(id)
}

function alertBg() {
	alert("You must select a background to begin");
}

function maxScaleReached() {
	if ( !confirm("This image is already at its maximum recommended size. Continuing to enlarge this image will result in degraded image quality.") ) {
		canvas.undo();
	}
	
}

function canvasSave() {
	if ( typeof(savedcanvas) == 'undefined' ) {
		canvas.save('save');
	} else {
		drawDialog("What do you want to do?",
		"canvas.save('saveover/"+savedcanvas+"')", "canvas.save('save')", 'Save Over Your Previously Saved Design', 'Save As a New Design');
	}
	
}

function histkeep() {
	window.setTimeout(function() {
		document.getElementById('histkeep').contentWindow.location = document.getElementById('histkeep').contentWindow.location + '/checker/'+Math.random();
	}, 1000);
}
var leavecount = 0;
function leaving() {
	if ( leavecount > 0 ) {
		drawDialog("Wait! Do You Want to Save Your Work?<a href='javascript: clearDialog(); canvasSave();'>Yes, Save to My Account</a><br /><a href='javascript: clearDialog(); window.history.go(-1);'>No, Exit without Saving</a><br /><a href='javascript: clearDialog(); document.getElementById(\"histkeep\").contentWindow.history.go(1);'>Continue Editing</a>", '', '', '', '');
	}
	leavecount++;
	
}

function leavecheck(url) {
	drawDialog("Wait! Do You Want to Save Your Work?<a href='javascript: clearDialog(); canvasSave();'>Yes, Save to My Account</a><a href='javascript: clearDialog(); window.location = \""+url+"\";'>No, Exit without Saving</a><a href='javascript: clearDialog(); document.getElementById(\"histkeep\").contentWindow.history.go(1);'>Continue Editing</a>", '', '', '', '');

	return false;
}

function getPageSizeWithScroll(){
	if (window.innerHeight && window.scrollMaxY) {// Firefox
		yWithScroll = window.innerHeight + window.scrollMaxY;
		xWithScroll = window.innerWidth + window.scrollMaxX;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		yWithScroll = document.body.scrollHeight;
		xWithScroll = document.body.scrollWidth;
	} else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
		yWithScroll = document.body.offsetHeight;
		xWithScroll = document.body.offsetWidth;
  	}
	arrayPageSizeWithScroll = new Array(xWithScroll,yWithScroll);
	//alert( 'The height is ' + yWithScroll + ' and the width is ' + xWithScroll );
	return arrayPageSizeWithScroll;
}

function switchLid(id) {
	lidpick(document.getElementById('lid'+id));
}

function clipartCatChange(select) {
	document.getElementById('clipart_container').innerHTML = '<div style="margin:10px auto;text-align:center;"><img style="width:16px;height:16px;" src="images/loading.gif" alt="loading" /></div>';
	var framechange = new asyncrpc('canvas/getClipart/'+select.value, false, fillClipart);
}

function frameCatChange(select) {
	document.getElementById('frames_container').innerHTML = '<div style="margin:10px auto;text-align:center;"><img style="width:16px;height:16px;" src="images/loading.gif" alt="loading" /></div>';
	var catchange = new asyncrpc('canvas/getFrames/'+select.value, false, fillFrames);
}

function fillFrames(res) {
	document.getElementById('frames_container').innerHTML = SXOOP.template.parse(document.getElementById('frames_template').value, res);
}

function fillClipart(res) {
	document.getElementById('clipart_container').innerHTML = SXOOP.template.parse(document.getElementById('clipart_template').value, res);
	
}

var slideopened = false;
function showSlider() {
	if ( $('slider').style.display == 'none' ) {
		if ( $('text_slider').style.display == '' ) {
			textSlideOut();
		}
		new Effect.BlindDown('slider',{queue:'end', afterFinish:function() { }});
		if ( !slideopened ) {
			slideopened = true;
			//clipartCatChange(document.getElementById("clipart_category"));
			//frameCatChange(document.getElementById("frame_category"));
		}
	} else {
		slideOut();
	}
	
}

function showTextSlider() {
	if ( $('text_slider').style.display == 'none' ) {
		if ( $('slider').style.display == '' ) {
			slideOut();
		}
		new Effect.BlindDown('text_slider',{queue:'end'});
	} else {
		textSlideOut();
	}
	
}

function textSlideOut() {
	new Effect.BlindUp('text_slider', {queue:'end'});
}

function slideOut() {
	
	new Effect.BlindUp('slider',{queue:'end'});
}



var tempholder;

function jsTemplate(arr, templateholder) {
	var dest = '';

	//var template = templateholder.innerHTML.substring(templateholder.innerHTML.indexOf('<!--template') + 12, templateholder.innerHTML.indexOf('template-->'));
	var template = templateholder.value;
	template = template.replace(/\'/g, "\\'");
	while( template.indexOf('{') > -1) {
		var start = template.indexOf('{');
		var key = template.substring(start + 1, template.indexOf('}', start));
		template = template.replace('{'+key+'}', "'+arr[x]['"+key+"']+'");
				
	}
	template = template.replace(/[\n\r]/g, "");
	template = "var res = '"+template+"';";
	for(var x=0; x < arr.length; x++) {
		eval(template);
		dest += res;
	}
	return dest;
	
}


function asyncrpc(path, input, callback) {
	this.callback = callback;
	this.request = false;
	
	this.rpcback = function() {
		if ( this.request.readyState == 4 ) {     
				if ( this.request.status == 200 ) {
					eval("var res="+this.request.responseText);
					this.callback(res);
				}
		}
	}
	
	var requestType = "POST";
	
	
	if ( !input ) {
		requestType = "GET";
		input = null;
	}
	
	if ( window.XMLHttpRequest ) {
			this.request = new XMLHttpRequest();
	} else if ( window.ActiveXObject ) {
		try {
			this.request = new ActiveXObject( "Msxml2.XMLHTTP" );
		} catch ( error ) {
			try {
				this.request = new ActiveXObject( "Microsoft.XMLHTTP" );
			} catch ( error2 ) {
				return alert("Fatal Error: No XMLHttp Interface Available");
			}
		}
	} else {
		return alert("Fatal Error: No XMLHttp Interface Available");
	}
	
	this.request.open(requestType, 'rpc/'+path, true);
	this.request.onreadystatechange = createDelegate(this, 'rpcback');
	this.request.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );		
	this.request.send(input);
	
	
	
}


function createDelegate(oObject, sMethodName) {
	return function () {
		return oObject[sMethodName].apply(oObject, arguments);
	};
}

var SXOOP = SXOOP || {};

SXOOP.template = {};

/**
 * Does this need explaining  ?
 */
SXOOP.template.map = function(array, func)
{
   var result = [];
   for (var i = 0;i < array.length; i++){ 
       var mapped = func(array[i]);
       for (var j = 0; j < mapped.length; j++){
           result.push(mapped[j]);
       }
   }
   return result;
};

/**
 * Parse a template (supplied as a string), substituting
 * the supplied object ($_) 
 * The $_ variable refers to the object which was passed into the parse function
 * Of course, all other global variables/functions are accessible too.
 */
SXOOP.template.parse = function(str,$_)
{
    var singleLine = str.replace(/[\n\r]/g,"");
    // innerHTML automatically converts < to &lt; and > to &gt;
    singleLine = singleLine.replace(/&lt;/g,"<");
    singleLine = singleLine.replace(/&gt;/g,">");

    /**
     * The include function facilitates inclusion of inner templates
     * Note: This include function is local to the parse function and will
     * override a global include function in the template scope only.
     */
    var include = function(elementId){
        var included = document.getElementById(elementId).innerHTML;
        return SXOOP.template.parse(included,$_);
    };
   
    /**
     * Split the template into parts
     */
    var parts = SXOOP.template.map(singleLine.split("[:"),function (part){
        var result = [];
        if (part.match(/:\]/)){
            result = part.split(/:\]/g);
            result[0] = "[:" + result[0];
        }else{
            result = [part];
        }
        return result;
    });
    /**
     * In firefox the following would suffice instead.
     * IE's implementation of split() is broken -  doesn't retain captured parts.
     *
     * parts = singleLine.split(/(\[:.*?):\]/);
     *
     * Process each part
     */
    var result = SXOOP.template.map(parts,function (part){
        var result = "";
        if (part.match(/\[:=/)){
            var inner = part.replace(/^\[:=\s*/,"");
            return ["theArray.push(" + inner + ");"];
        }
        if (part.match(/^\[:/)){
            var inner = part.replace(/^\[:/,"");
            return [inner];
        }else{
            part = part.replace(/\"/g,"\\\"");
            return ["theArray.push(\"" + part + "\");"];
        }
    });
    var theArray = [];
    result.push("theArray.join('');");
    var javascript = result.join("\n");
    return eval(javascript);
};

function imguploadstep(step) {
	document.getElementById('photoup1').style.display = 'none';
	document.getElementById('photoup2').style.display = 'none';
	document.getElementById('photoup3').style.display = 'none';
	document.getElementById('photoup'+step).style.display = '';
}

var coloredboxes = {"White":"FFFFFF","Ivory":"FFFFF0","Light Yellow":"FFFFE0","Yellow":"FFFF00","Snow":"FFFAFA","Floral White":"FFFAF0","Lemon Chiffon":"FFFACD","Cornsilk":"FFF8DC","Sea Shell":"FFF5EE","Lavender Blush":"FFF0F5","Papaya Whip":"FFEFD5","Blanched Almond":"FFEBCD","Misty Rose":"FFE4E1","Bisque":"FFE4C4","Moccasin":"FFE4B5","Navajo White":"FFDEAD","Peach Puff":"FFDAB9","Gold":"FFD700","Pink":"FFC0CB","Light Pink":"FFB6C1","Orange":"FFA500","Light Salmon":"FFA07A","Darkorange":"FF8C00","Coral":"FF7F50","Hot Pink":"FF69B4","Tomato":"FF6347","Orange Red":"FF4500","Deep Pink":"FF1493","Fuchsia":"FF00FF","Red":"FF0000","Old Lace":"FDF5E6","Light Golden Rod Yellow":"FAFAD2","Linen":"FAF0E6","Antique White":"FAEBD7","Salmon":"FA8072","Ghost White":"F8F8FF","Mint Cream":"F5FFFA","White Smoke":"F5F5F5","Beige":"F5F5DC","Wheat":"F5DEB3","Sandy Brown":"F4A460","Azure":"F0FFFF","Honey Dew":"F0FFF0","Alice Blue":"F0F8FF","Khaki":"F0E68C","Light Coral":"F08080","Pale Golden Rod":"EEE8AA","Violet":"EE82EE","Dark Salmon":"E9967A","Lavender":"E6E6FA","Light Cyan":"E0FFFF","Burly Wood":"DEB887","Plum":"DDA0DD","Gainsboro":"DCDCDC","Crimson":"DC143C","Golden Rod":"DAA520","Orchid":"DA70D6","Thistle":"D8BFD8","Pale Violet Red":"D87093","Light Gray":"D3D3D3","Tan":"D2B48C","Chocolate":"D2691E","Peru":"CD853F","Indian Red":"CD5C5C","Medium Violet Red":"C71585","Silver":"C0C0C0","Dark Khaki":"BDB76B","Rosy Brown":"BC8F8F","Medium Orchid":"BA55D3","Dark Golden Rod":"B8860B","Fire Brick":"B22222","Powder Blue":"B0E0E6","Light Steel Blue":"B0C4DE","Pale Turquoise":"AFEEEE","Green Yellow":"ADFF2F","Light Blue":"ADD8E6","Dark Grey":"A9A9A9","Brown":"A52A2A","Sienna":"A0522D","Yellow Green":"9ACD32","Dark Orchid":"9932CC","Pale Green":"98FB98","Dark Violet":"9400D3","Medium Purple":"9370D8","Light Green":"90EE90","Dark Sea Green":"8FBC8F","Saddle Brown":"8B4513","Dark Magenta":"8B008B","Dark Red":"8B0000","Blue Violet":"8A2BE2","Light Sky Blue":"87CEFA","Sky Blue":"87CEEB","Grey":"808080","Olive":"808000","Purple":"800080","Maroon":"800000","Aquamarine":"7FFFD4","Chartreuse":"7FFF00","Lawn Green":"7CFC00","Medium Slate Blue":"7B68EE","Light Slate Grey":"778899","Slate Grey":"708090","Olive Drab":"6B8E23","Slate Blue":"6A5ACD","Dim Gray":"696969","Medium Aqua Marine":"66CDAA","Cornflower Blue":"6495ED","Cadet Blue":"5F9EA0","Dark Olive Green":"556B2F","Indigo":"4B0082","Medium Turquoise":"48D1CC","Dark Slate Blue":"483D8B","Steel Blue":"4682B4","Royal Blue":"4169E1","Turquoise":"40E0D0","Medium Sea Green":"3CB371","Lime Green":"32CD32","Dark Slate Gray":"2F4F4F","Sea Green":"2E8B57","Forest Green":"228B22","Light Sea Green":"20B2AA","Dodger Blue":"1E90FF","Midnight Blue":"191970","Cyan":"00FFFF","Spring Green":"00FF7F","Lime":"00FF00","Medium Spring Green":"00FA9A","Dark Turquoise":"00CED1","Deep Sky Blue":"00BFFF","Dark Cyan":"008B8B","Teal":"008080","Green":"008000","Dark Green":"006400","Blue":"0000FF","Medium Blue":"0000CD","Dark Blue":"00008B","Navy":"000080","Black":"000000"};


