
if(!this.JSON){JSON=function(){function f(n){return n<10?'0'+n:n;}
Date.prototype.toJSON=function(){return this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z';};var m={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};function stringify(value,whitelist){var a,i,k,l,r=/["\\\x00-\x1f\x7f-\x9f]/g,v;switch(typeof value){case'string':return r.test(value)?'"'+value.replace(r,function(a){var c=m[a];if(c){return c;}
c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+
(c%16).toString(16);})+'"':'"'+value+'"';case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
if(typeof value.toJSON==='function'){return stringify(value.toJSON());}
a=[];if(typeof value.length==='number'&&!(value.propertyIsEnumerable('length'))){l=value.length;for(i=0;i<l;i+=1){a.push(stringify(value[i],whitelist)||'null');}
return'['+a.join(',')+']';}
if(whitelist){l=whitelist.length;for(i=0;i<l;i+=1){k=whitelist[i];if(typeof k==='string'){v=stringify(value[k],whitelist);if(v){a.push(stringify(k)+':'+v);}}}}else{for(k in value){if(typeof k==='string'){v=stringify(value[k],whitelist);if(v){a.push(stringify(k)+':'+v);}}}}
return'{'+a.join(',')+'}';}}
return{stringify:stringify,parse:function(text,filter){var j;function walk(k,v){var i,n;if(v&&typeof v==='object'){for(i in v){if(Object.prototype.hasOwnProperty.apply(v,[i])){n=walk(i,v[i]);if(n!==undefined){v[i]=n;}}}}
return filter(k,v);}
if(/^[\],:{}\s]*$/.test(text.replace(/\\./g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(:?[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof filter==='function'?walk('',j):j;}
throw new SyntaxError('parseJSON');}};}();}

var TP={recursivelyCollect:function(element){var elements=[];while(element.nodeType==1){elements.push(element);if(element.parentNode!==null){element=element.parentNode;}else{break;}}
return elements;},ancestors:function(element){return this.recursivelyCollect(element);},getPagePosition:function(object){var x=0;var y=0;if(object.offsetParent){x=object.offsetLeft;y=object.offsetTop;while(object=object.offsetParent){x+=object.offsetLeft;y+=object.offsetTop;}}
return[x,y];},moveBetweenSelects:function(fromSelect,toSelect,callback){var firstSelectedIndex=null;for(var currentIndex=0;currentIndex<fromSelect.options.length;currentIndex++){var currentOption=fromSelect.options[currentIndex];if(currentOption.selected){if(!firstSelectedIndex){firstSelectedIndex=currentIndex;}
fromSelect.remove(currentIndex);try{toSelect.add(currentOption,null);}catch(e){toSelect.add(new Option(currentOption.text,currentOption.value));}
currentIndex--;}}
if((firstSelectedIndex-1)>-1&&fromSelect.options[firstSelectedIndex-1]!==undefined){fromSelect.selectedIndex=firstSelectedIndex-1;}else if(fromSelect.options[0]!==undefined){fromSelect.selectedIndex=0;}
if(typeof callback==='function'){callback();}},getSelectedIndexes:function(select){var selectedIndexes=[];for(var i=0;i<select.options.length;i++){if(select.options[i].selected){selectedIndexes.push(i);}}
return selectedIndexes;},selectSortUp:function(selectBox,callback){if(typeof selectBox.selectedIndex!=='undefined'){var selectedIndexes=TP.getSelectedIndexes(selectBox);for(var i=0;i<selectedIndexes.length;i++){var selectedIndex=selectedIndexes[i];if(selectedIndex>0&&selectedIndex<selectBox.options.length){var selectedOption=selectBox.options[selectedIndex];try{selectBox.add(selectedOption,selectBox.options[selectedIndex-1]);}catch(e){selectBox.add(new Option(selectedOption.text,selectedOption.value),selectBox.options[selectedIndex-1]);selectBox.remove(selectedIndex+1);}
if(typeof callback==='function'){callback();}}}}},selectSortDown:function(selectBox,callback){if(typeof selectBox.selectedIndex!=='undefined'){var selectedIndexes=TP.getSelectedIndexes(selectBox);selectedIndexes.reverse();for(var i=0;i<selectedIndexes.length;i++){var selectedIndex=selectedIndexes[i];if(selectedIndex>=0&&selectedIndex<selectBox.options.length){var selectedOption=selectBox.options[selectedIndex];if(selectedIndex<(selectBox.options.length-1)){try{selectBox.add(selectedOption,selectBox.options[selectedIndex+2]);}catch(e){selectBox.add(new Option(selectedOption.text,selectedOption.value),selectBox.options[selectedIndex+2]);selectBox.remove(selectedIndex);}}
if(typeof callback==='function'){callback();}}}}},CHAR_CODE_ENTER:13,characterCode:function(e){var code=null;if(!e){var e=window.event;}
if(e){if(e.keyCode){code=e.keyCode;}else if(e.which){code=e.which;}
return code;}
return null;},setCookie:function(name,value,days,path,domain){if(days){var date=new Date();date.setTime(date.getTime()+(days*24*60*60*1000));var expires="; expires="+date.toGMTString();}else{var expires="";}
if(typeof path==='undefined'){path="/";}
var domainString="";if(typeof domain!=='undefined'){domainString="; domain="+domain;}
document.cookie=name+"="+value+expires+"; path="+path+domainString;},getCookie:function(name){var nameEQ=name+"=";var ca=document.cookie.split(';');for(var i=0;i<ca.length;i++){var c=ca[i];while(c.charAt(0)==' '){c=c.substring(1,c.length);}
if(c.indexOf(nameEQ)==0){return c.substring(nameEQ.length,c.length);}}
return null;},saveScroll:function(event,name){if(!name){name=document.location.href.replace(/#.*$/,'').replace(/[=]/g,'');}
var scrollX=window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft;var scrollY=window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop;TP.setCookie(name+'_x',scrollX,1/48);TP.setCookie(name+'_y',scrollY,1/48);},restoreScroll:function(name){if(!name){name=document.location.href.replace(/#.*$/,'').replace(/[=]/g,'');}
var xCookieName=name+'_x';var yCookieName=name+'_y';var scrollX=TP.getCookie(xCookieName);var scrollY=TP.getCookie(yCookieName);TP.setCookie(xCookieName,null);TP.setCookie(yCookieName,null);if(scrollX||scrollY){window.scrollTo(scrollX,scrollY);}},click:function(element){if(typeof element==='string'){element=document.getElementById(element);}
if(element){var event=document.createEvent("MouseEvents");event.initMouseEvent("click",true,true,window,0,0,0,0,0,false,false,false,false,0,null);element.dispatchEvent(event);}},isObject:function(item){return typeof item=='object'&&item!==null;},extendObject:function(destination,source){var args=Array.prototype.slice.call(arguments);if(args.length>1){for(var i=1;i<args.length;i++){var current=args[i];for(var property in current){destination[property]=current[property];}}}
return destination;},copy:function(object){return this.extendObject({},object);},deepCopy:function(source){var output={};for(var property in source){if(TP.isObject(source[property])){output[property]=this.deepCopy(source[property]);}else{output[property]=source[property];}}
return output;},getObjectString:function(object,recursive,indent){if(typeof recursive=='undefined'){recursive=false;}
if(typeof indent=='undefined'){indent=0;}
var string='';for(var property in object){for(var i=0;i<indent;i++){string+='  ';}
if(recursive&&TP.isObject(object[property])){string+=property+':\n';string+=this.getPrettyObjectString(object[property],recursive,indent+1);}else{string+=property+': '+object[property]+'\n';}}
return string;},ucFirst:function(string){return string.substring(0,1).toUpperCase()+string.substring(1);},BrowserDetect:{init:function(){this.browser=this.searchString(this.dataBrowser)||"unknown";this.version=this.searchVersion(navigator.userAgent)||this.searchVersion(navigator.appVersion)||"unknown";this.OS=this.searchString(this.dataOS)||"unknown";},searchString:function(data){for(var i=0;i<data.length;i++){var dataString=data[i].string;var dataProp=data[i].prop;this.versionSearchString=data[i].versionSearch||data[i].identity;if(dataString){if(dataString.indexOf(data[i].subString)!=-1){return data[i].identity;}}
else if(dataProp){return data[i].identity;}}
return undefined;},searchVersion:function(dataString){var index=dataString.indexOf(this.versionSearchString);if(index==-1){return undefined;}
return parseFloat(dataString.substring(index+this.versionSearchString.length+1));},dataBrowser:[{string:navigator.userAgent,subString:"OmniWeb",versionSearch:"OmniWeb/",identity:"OmniWeb"},{string:navigator.vendor,subString:"Apple",identity:"Safari"},{prop:window.opera,identity:"Opera"},{string:navigator.vendor,subString:"iCab",identity:"iCab"},{string:navigator.vendor,subString:"KDE",identity:"Konqueror"},{string:navigator.userAgent,subString:"Firefox",identity:"Firefox"},{string:navigator.vendor,subString:"Camino",identity:"Camino"},{string:navigator.userAgent,subString:"Netscape",identity:"Netscape"},{string:navigator.userAgent,subString:"MSIE",identity:"Explorer",versionSearch:"MSIE"},{string:navigator.userAgent,subString:"Mozilla",identity:"Firefox",versionSearch:"Minefield"},{string:navigator.userAgent,subString:"Gecko",identity:"Mozilla",versionSearch:"rv"},{string:navigator.userAgent,subString:"Mozilla",identity:"Netscape",versionSearch:"Mozilla"}],dataOS:[{string:navigator.userAgent,subString:"Windows NT 6.0",identity:"Windows/Vista"},{string:navigator.userAgent,subString:"Windows NT 5.1",identity:"Windows/XP"},{string:navigator.userAgent,subString:"Windows NT 6.1",identity:"Windows/7"},{string:navigator.platform,subString:"Win",identity:"Windows"},{string:navigator.userAgent,subString:"Mac OS X",identity:"Mac"},{string:navigator.platform,subString:"Linux",identity:"Linux"}]},BrowserCheck:{supported:false,supportedBrowsers:[{os:'Mac',browser:'Safari',version:'3'},{os:'Mac',browser:'Firefox',version:'3'},{os:'Mac',browser:'Firefox',version:'3.5'},{os:'Windows/XP',browser:'Firefox',version:'3'},{os:'Windows/XP',browser:'Firefox',version:'3.5'},{os:'Windows/XP',browser:'Explorer',version:'6'},{os:'Windows/XP',browser:'Explorer',version:'7'},{os:'Windows/XP',browser:'Explorer',version:'8'},{os:'Windows/Vista',browser:'Firefox',version:'3.5'},{os:'Windows/Vista',browser:'Firefox',version:'3'},{os:'Windows/Vista',browser:'Explorer',version:'7'},{os:'Windows/Vista',browser:'Explorer',version:'8'},{os:'Linux',browser:'Firefox',version:'3.5'},{os:'Windows/7',browser:'Explorer',version:'7'},{os:'Windows/7',browser:'Explorer',version:'8'},{os:'Windows/7',browser:'Firefox',version:'3.5'},{os:'Windows/7',browser:'Firefox',version:'3'}],init:function(){TP.BrowserDetect.init();for(var i=0;i<this.supportedBrowsers.length;i++){var current=this.supportedBrowsers[i];if(TP.BrowserDetect.browser=='Safari'){this.supported=true;break;}
if(TP.BrowserDetect.browser==current.browser&&TP.BrowserDetect.OS==current.os&&TP.BrowserDetect.version==current.version){this.supported=true;break;}}}}};TP.Associator=function(prefix,options){this.prefix=prefix;this.associatedSelect=document.getElementById(this.prefix+'_associated');this.availableSelect=document.getElementById(this.prefix+'_available');this.sortUpElement=document.getElementById(this.prefix+'_sortUp');this.sortDownElement=document.getElementById(this.prefix+'_sortDown');this.associateElement=document.getElementById(this.prefix+'_associate');this.disassociateElement=document.getElementById(this.prefix+'_disassociate');this.associatedIdsElement=document.getElementById(this.prefix+'_associatedIds');this.preAssociate=function(){};this.postAssociate=function(){};this.preDisassociate=function(){};this.postDisassociate=function(){};this.preSortUp=function(){};this.postSortUp=function(){};this.preSortDown=function(){};this.postSortDown=function(){};if(typeof options=='object'){if(typeof options.preAssociate=='function'){this.preAssociate=options.preAssociate;}
if(typeof options.postAssociate=='function'){this.postAssociate=options.postAssociate;}
if(typeof options.preDisassociate=='function'){this.preDisassociate=options.preDisassociate;}
if(typeof options.postDisassociate=='function'){this.postDisassociate=options.postDisassociate;}
if(typeof options.preSortUp=='function'){this.preSortUp=options.preSortUp;}
if(typeof options.postSortUp=='function'){this.postSortUp=options.postSortUp;}
if(typeof options.preSortDown=='function'){this.preSortDown=options.preSortDown;}
if(typeof options.postSortDown=='function'){this.postSortDown=options.postSortDown;}}
var associator=this;if(this.sortUpElement){this.sortUpElement.onclick=function(){associator.preSortUp();TP.selectSortUp(associator.associatedSelect,function(){associator.updateAssociatedIds();});associator.postSortUp();return false;};}
if(this.sortDownElement){this.sortDownElement.onclick=function(){associator.preSortDown();TP.selectSortDown(associator.associatedSelect,function(){associator.updateAssociatedIds();});associator.postSortDown();return false;};}
if(this.associatedIdsElement){this.updateAssociatedIds();if(this.associateElement){this.associateElement.onclick=function(){associator.preAssociate();TP.moveBetweenSelects(associator.availableSelect,associator.associatedSelect,function(){associator.updateAssociatedIds();});associator.postAssociate();return false;};}
if(this.disassociateElement){this.disassociateElement.onclick=function(){associator.preDisassociate();TP.moveBetweenSelects(associator.associatedSelect,associator.availableSelect,function(){associator.updateAssociatedIds();});associator.postDisassociate();return false;};}}};TP.extendObject(TP.Associator.prototype,{prefix:null,associatedSelect:null,availableSelect:null,sortUpElement:null,sortDownElement:null,associateElement:null,disassociateElement:null,associatedIdsElement:null,updateAssociatedIds:function(){var associated=this.associatedSelect.options;var associatedIdsArray=[];for(var i=0;i<associated.length;i++){associatedIdsArray.push(associated[i].value);}
this.associatedIdsElement.value=associatedIdsArray;},compareAssociatedOptions:function(targetAssociator){var associatedOptions=this.associatedSelect.options;var targetOptions=targetAssociator.associatedSelect.options;if(associatedOptions.length!==targetOptions.length){return false;}
for(var idx=0;idx<associatedOptions.length;idx++){var associatedOption=associatedOptions[idx];var comparisonOption=targetOptions[idx];if(associatedOption.value!==comparisonOption.value){return false;}}
return true;}});if(typeof Function.prototype.bind=='undefined'){Function.prototype.bind=function(){var __method=this;var object=arguments[0];var args=[];for(var i=1;i<arguments.length;i++){args.push(arguments[i]);}
return function(){return __method.apply(object,args);}};}
if(typeof Function.prototype.bindAsEventListener=='undefined'){Function.prototype.bindAsEventListener=function(){var __method=this;var object=arguments[0];var args=[];for(var i=1;i<arguments.length;i++){args.push(arguments[i]);}
return function(event){return __method.apply(object,[event||window.event].concat(args));}}}

var PrettySelect=Class.create();PrettySelect.prototype={initialize:function(options){this.container=$(options.container);this.button=$(options.button);this.selected=$(options.selected);this.list=$(options.list);if(!window.XMLHttpRequest){this.ie=true;this.listShim=document.createElement('iframe');this.listShim.style.display='none';this.listShim.style.position='absolute';this.listShim.style.left='0';this.listShim.style.top='0';this.listShim.src='javascript:false;';this.listShim.frameBorder='0';this.listShim.scrolling='no';this.list.parentNode.insertBefore(this.listShim,this.list);}else{this.ie=false;}
this.itemPrefix=options.itemPrefix;this.selectionId=options.selectionId;this.input=$(options.input);this.onselect=options.onselect;this.container.addClassName("prettySelect");this.button.addClassName("prettySelectButton");this.selected.addClassName("prettySelectSelected");this.list.addClassName("prettySelectList");this.lastValue="";this.enabled=(typeof options.enabled=='undefined')?true:options.enabled;var prettySelect=this;this.button.onclick=this.selected.onclick=function(){prettySelect.buttonPress();prettySelect.showList();};this.items=this.list.getElementsByClassName("prettySelectItem");for(var i=0;i<this.items.length;i++){var currentItem=this.items[i];var currentBgColor=currentItem.style.backgroundColor;currentItem.onclick=function(){prettySelect.select(this);};currentItem.onmouseover=function(){if(prettySelect.parseItemId(this.id)!=prettySelect.selectionId)this.style.backgroundColor="#A9D1FF";};currentItem.onmouseout=function(){if(prettySelect.parseItemId(this.id)!=prettySelect.selectionId)this.style.backgroundColor=currentBgColor;};}
var listItems=this.list.getElementsByTagName("li");this.updateSelected();this.updateListActive();},buttonPress:function(){},updateSelected:function(){var selection=document.getElementById(this.itemPrefix+this.selectionId);if(selection!=null){this.selected.innerHTML=selection.innerHTML;var dividers=this.selected.getElementsByClassName("prettySelectDivider");for(var i=0;i<dividers.length;i++){var currentDivider=dividers[i];currentDivider.parentNode.removeChild(currentDivider);}}},showList:function(){if(this.enabled){var listStatic=this.list;if(!listStatic.visible()){this.list.show();if(this.ie==true){this.listShim.style.display=this.list.style.display;this.listShim.style.width=this.list.offsetWidth;this.listShim.style.height=this.list.offsetHeight;this.listShim.style.top=this.list.style.top;this.listShim.style.left=this.list.style.left;this.listShim.style.zIndex=this.list.style.zIndex-1;}}}},hideList:function(){this.list.hide();if(this.ie==true){this.listShim.style.display=this.list.style.display;this.listShim.style.width=this.list.offsetWidth;this.listShim.style.height=this.list.offsetHeight;this.listShim.style.top=this.list.style.top;this.listShim.style.left=this.list.style.left;this.listShim.style.zIndex=this.list.style.zIndex-1;}},select:function(element){if(element!==null){this.selectionId=this.parseItemId(element.id);this.buttonPress();this.updateSelected();this.updateListActive();this.hideList();this.input.value=this.selectionId;this.lastValue=element.id;this.onselect(this.selectionId);}},updateListActive:function(){for(var i=0;i<this.items.length;i++){var currentItem=this.items[i];if(this.parseItemId(currentItem.id)==this.selectionId){currentItem.style.backgroundColor="#A9D1FF";}
else{if(i%2==1){currentItem.style.backgroundColor="#EDF5FF";}
else{currentItem.style.backgroundColor="#FFFFFF";}}}},parseItemId:function(itemId){var chunks=itemId.split("_");return(chunks[chunks.length-1])?chunks[chunks.length-1]:null;},enable:function(){this.enabled=true;this.container.style.backgroundColor="#FFFFFF";},disable:function(){this.hideList();this.enabled=false;this.container.style.backgroundColor="#EEEEEE";this.selected.update("");}};

var TPBalloon=function(options){this.options={borderColor:'#53351A',borderWidth:1,borderStyle:'solid',backgroundColor:'#FFFFE1',imageBase:'',stemPosition:'rightTop',content:'',anchor:'',width:30,height:30,fadeTime:0.5,contentClass:'',animator:null,zIndex:40000};this.options=Object.extend(this.options,options);this.render();this.visible=false;}
TPBalloon.prototype={show:function(){if(this.visible)return;this.position();this.visible=true;this.box.appear({duration:this.options.fadeTime});if(this.options.animator)this.options.animator.start();},hide:function(){if(!this.visible)return;this.visible=false;this.box.fade({duration:this.options.fadeTime});if(this.options.animator)this.options.animator.stop();},position:function(){var anchor=$(this.options.anchor);var anchorPosition=anchor.viewportOffset();var scroll=document.viewport.getScrollOffsets();anchorPosition.top+=scroll.top;anchorPosition.left+=scroll.left;switch(this.options.stemPosition){case'rightTop':this.tipBox.setStyle({top:'0px',left:'0px'});this.tipStem.setStyle({top:'0px',left:(this.options.width+this.options.borderWidth)+'px'});this.box.setStyle({top:anchorPosition.top+'px',left:(anchorPosition.left-this.options.width-20)+'px'});break;case'rightMiddle':this.tipBox.setStyle({top:'0px',left:'0px'});this.tipStem.setStyle({top:((this.options.height/2)-(this.stemImage.height/2))+'px',left:(this.options.width+this.options.borderWidth)+'px'});this.box.setStyle({top:(anchorPosition.top)+'px',left:(anchorPosition.left-this.options.width-20)+'px'});break;}},render:function(){this.box=new Element('div',{id:this.options.anchor+'_balloonBox',style:'position: absolute'});this.container=new Element('div',{id:this.options.anchor+'_balloonContainer',style:'position:relative'});this.tipBox=new Element('div',{id:this.options.anchor+'_balloonTipBox',style:'position: absolute'});this.tipStem=new Element('div',{id:this.options.anchor+'_balloonTipStem',style:'position: absolute'});this.tipStem.insert(this.getStemImage());this.tipBox.setStyle({border:this.options.borderWidth+'px '+this.options.borderStyle+' '+this.options.borderColor,backgroundColor:this.options.backgroundColor,width:this.options.width+'px',height:this.options.height+'px'})
this.tipBox.update(new Element('div',{'class':this.options.contentClass}).update(this.options.content));this.container.insert(this.tipBox);this.container.insert(this.tipStem);this.box.insert(this.container);this.box.setStyle({top:'50px',left:'400px',zIndex:this.options.zIndex});this.box.hide();if(this.options.animator)this.options.animator.init(this.box);$(document.body).insert(this.box);},getStemImage:function(){this.stemImage=new Image();this.stemImage.src=this.options.imageBase+this.options.stemPosition.toLowerCase()+'.gif';return this.stemImage;}}
var TPBalloonPointerAnimator=function(options){this.obj=null;this.active=false;this.options={repetitions:0,distance:30,pullBackDuration:0.5,springFwdDuration:0.4,delay:0}
this.repetitions=0;this.options=Object.extend(this.options,options);}
TPBalloonPointerAnimator.prototype={init:function(obj){this.obj=obj;},start:function(){this.repetitions=0;this.active=true;setTimeout(this.pullBack.bind(this),this.options.delay*1000);},stop:function(){this.active=false;},pullBack:function(){if(this.options.repetitions>0)if(this.repetitions>=this.options.repetitions)return;this.repetitions++;if(!this.active)return;new Effect.Move(this.obj,{x:-(this.options.distance),y:0,mode:'relative',duration:this.options.pullBackDuration,transition:Effect.Transitions.sinoidal,afterFinish:this.springFwd.bind(this)});},springFwd:function(){try{new Effect.Move(this.obj,{x:this.options.distance,y:0,mode:'relative',duration:this.options.springFwdDuration,transition:Effect.Transitions.spring,afterFinish:this.pullBack.bind(this)});}catch(e){console.log(e);}}}
var TPBalloonDartAnimator=function(options){this.obj=null;this.active=false;this.options={distance:300,duration:0.5}
this.options=Object.extend(this.options,options);}
TPBalloonDartAnimator.prototype={init:function(obj){this.obj=obj;},start:function(){new Effect.Move(this.obj,{x:-(this.options.distance),y:0,mode:'relative',duration:0,afterFinish:this.shootDart.bind(this)});},stop:function(){},shootDart:function(){new Effect.Move(this.obj,{x:(this.options.distance),y:0,mode:'relative',duration:this.options.duration,transition:Effect.Transitions.sinoidal});}}

var Personalize=function(){}
Personalize.prototype={STEP_STATUS_ACTIVE:'active',STEP_STATUS_INACTIVE:'inactive',STEP_STATUS_CLICKABLE:'clickable',VARIABLE_TYPE_TEXT:1,VARIABLE_TYPE_TEXTBOX:2,VARIABLE_TYPE_DATE:3,VARIABLE_TYPE_TIME:4,VARIABLE_TYPE_WEIGHT:5,VARIABLE_TYPE_LENGTH:6,VARIABLE_TYPE_NAME:7,VARIABLE_TYPE_AGE:8,popupZIndex:50001,maskZIndex:50000,editorZIndex:40000,handleZIndex:10000,photoZIndex:100,textboxZIndex:200,layoutZIndex:300,overlayZIndex:400,separatorZIndex:500,doodleZIndex:900,defaultDoodleSize:70,imageEffects:{1:'grayscale',2:'sepia'},IMAGE_EFFECT_NONE:0,IMAGE_EFFECT_GRAYSCALE:1,IMAGE_EFFECT_SEPIA:2,PHOTO_SERVICE_FLICKR:'flickr',PHOTO_SERVICE_SMUGMUG:'smugmug',PHOTO_SERVICE_PICASA:'picasa',MAILING_SERVICE_SHIPNONE:0,MAILING_SERVICE_SHIPALL:1,MAILING_SERVICE_SHIPSOME:2,mainElement:$('pageContainer'),renderingDecimalPrecision:0,maxUserPhotos:20,userPhotos:[],returnAddressLabelData:{returnAddressLabel:null,returnAddressLabelProductId:null,returnAddressLabelQuantity:null},ie6:(window.external&&typeof window.XMLHttpRequest=='undefined'),ie7:((navigator.appVersion.indexOf('MSIE 7.')==-1)?false:true),safari:(/Safari/.test(navigator.userAgent)),isIe:function(){return(this.ie6||this.ie7);},environment:null,hosts:{"static":null,images:null,imagesProxy:null},store:null,steps:[],uris:[],eventHandlers:{'changecolor':[],'changepanel':[],'changelayout':[],'infoentered':[],'login':[],'userphotosloaded':[],'toggleoutlines':[],'afterchangepanel':[],'changeenvelope':[],'changemailingservice':[],'changepra':[],'changeprafont':[],'changepratext':[],'changeprafontcolor':[],'changestamp':[],'changeextraenvelopesquantity':[],'enteredinfo':[],'changemailforme':[],'changeshiptome':[],'photouploaded':[],'changestep':[],'removephoto':[],'addphototocard':[],'removephotofromcard':[],'changerecipientaddresscheckbox':[],'changequantity':[],'envelopesstepactivate':[],'recipientsstepactivate':[],'changeaddresslabel':[],'changeaddresslabelquantity':[],'textboxclick':[],'changemailingserviceavailable':[],'changedoodle':[],'activaterecipients':[],'changerecipientsloginstate':[],'changerecipientsreturnaddress':[],'clickshiptomestamps':[],'editcontact':[]},activeStepIndex:null,activeStep:null,preShippedEnvelopes:false,recentlyViewedPopupDomId:'recentlyViewedPopup',numbersToWords:{0:'zero',1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine'},showLoadingPopup:function(){if(!this.loadingPopup){this.loadingPopup=new PersonalizePopup('Loading ... ','loadingP13n');}
var elem=this.loadingPopup.getPopupElement();var loaderDiv=new Element('div',{align:'center','class':'loginLoader'});var loaderText=new Element('div').update('Loading your project ..');var loaderImg=new Image();loaderImg=$(loaderImg);loaderImg.src=Personalize.hosts['static']+'image/tp/personalize/smallSpinner.gif';loaderDiv.insert(loaderText);loaderDiv.insert(loaderImg);elem.update(loaderDiv);this.loadingPopup.showPopup();},hideLoadingPopup:function(){this.loadingPopup.hidePopup();},init:function(){if(!Personalize.personalization){Personalize.personalization={};Personalize.personalization.id=null;}
var fragment=window.location.hash.split('_');if(fragment.length<2){if(!Personalize.personalization.id&&(window.location.hash=='#personalizeEnterInfo'||window.location.hash=='#Personalize'||window.location.hash=='#personalizeReview'||window.location.hash=='#personalizeEnvelopes')){window.location.hash='#';this.urlFragment='';}}
if(window.opera){history.navigationMode='compatible';}
Event.observe(window,'unload',function(){Personalize.services.saveSessionPersonalization();});this.startCheckingUrl();$('saveButton').hide();if(!Personalize.productPhotoEffects){Personalize.productPhotoEffects={};var productEffectsCookie=TP.getCookie("productPhotoEffects");if(productEffectsCookie){Personalize.productPhotoEffects=JSON.parse(TP.getCookie("productPhotoEffects"));}}},setStepUrl:function(){var hash=this.steps[this.activeStepIndex].name;if(Personalize.personalization.id){hash+='_'+Personalize.personalization.id;}
if(!(window.location.hash==''&&hash=='enterInfo')){window.location.hash=hash;}},checkStepUrl:function(){var fragment=window.location.hash;if(fragment){if(fragment!=''){fragment=fragment.substr(1);if(fragment==this.urlFragment)return false;this.urlFragment=fragment;var fragmentParts=fragment.split('_');if(fragmentParts.length>1){var possibleStepIndex=fragmentParts[0];var possiblePersonalizationId=fragmentParts[1];if(possiblePersonalizationId!=Personalize.personalization.id){Personalize.services.loadPersonalization(possiblePersonalizationId,{onComplete:function(){if(Personalize.activeStepIndex){Personalize.activeStepIndex=null;}
Personalize.stopCheckingUrl();Personalize.personalizationLoaded=true;Personalize.activateStep(possibleStepIndex);}});}else{if(possibleStepIndex!=this.activeStepIndex){this.activateStep(possibleStepIndex);}}}else{var possibleStepIndex=fragment;this.activateStep(possibleStepIndex);}}}},startCheckingUrl:function(){this.urlCheckTimer=setInterval("Personalize.checkStepUrl();",200);},stopCheckingUrl:function(){if(this.urlCheckTimer){clearTimeout(this.urlCheckTimer);}},registerSteps:function(stepsArray){this.steps=stepsArray;for(var stepId in this.steps){this.steps[stepId].init();}
this.activeStepIndex=this.findFirstAvailableStep();this.activeStep=this.steps[this.activeStepIndex];this.activeStep.activate();this.renderNavigationTabs();},findFirstAvailableStep:function(){for(var stepId in this.steps){if(this.steps[stepId].available)return stepId;}
return false;},findNextAvailableStep:function(){var stepIndex=this.activeStepIndex;var returnNextAvailable=false;for(var currentStepIndex in this.steps){var step=this.steps[currentStepIndex];if(currentStepIndex==stepIndex){returnNextAvailable=true;}else if(returnNextAvailable&&step.available){return currentStepIndex;}}
return null;},findPreviousAvailableStep:function(stepIndex){if(!stepIndex){stepIndex=this.activeStepIndex;}
var availableStepIndex=null;for(var currentStepIndex in this.steps){var step=this.steps[currentStepIndex];if(currentStepIndex==stepIndex){return availableStepIndex;}
if(step.available){availableStepIndex=currentStepIndex;}}
return null;},getStepByName:function(stepName){for(var stepId in this.steps){step=this.steps[stepId];if(step.name===stepName&&step.available)return step;}
return null;},next:function(){var newStep=this.findNextAvailableStep();if(newStep){if(this.activeStep.next()){this.trigger('changestep',newStep.name);this.activeStep.deactivate();this.activeStepIndex=newStep;this.activeStep=this.steps[this.activeStepIndex];this.activeStep.activate(true);this.updateNavigationTabs();this.setStepUrl();}}else{if(this.activeStep){if(this.activeStep.next()){this.finish();}}else{this.finish();}}},back:function(){var newStep=this.findPreviousAvailableStep();if(newStep){if(this.activeStep.back()){this.trigger('changestep',newStep.name);this.activeStep.deactivate();this.activeStepIndex=newStep;this.activeStep=this.steps[this.activeStepIndex];this.activeStep.activate(false);this.updateNavigationTabs();this.setStepUrl();}}},finish:function(){Personalize.services.savePersonalization(false,function(){var p=Personalize.personalization;var returnAddressLines=(p.returnAddressText)?p.returnAddressText.split('\n'):[];var finalEnvelopeId=null;if(p.envelopePairId){var pair=Personalize.envelopesPairs[p.envelopePairId];finalEnvelopeId=pair.outerEnvelopeId;if(p.pairLinedEnvelopeId){finalInnerEnvelopeId=p.pairLinedEnvelopeId;}else{finalInnerEnvelopeId=pair.innerEnvelopeId;}}else{finalEnvelopeId=(p.linedEnvelopeId)?p.linedEnvelopeId:p.envelopeId;finalInnerEnvelopeId=null;}
var addToCartParameters={pid:p.productId,quantity:p.quantity,personalizationId:p.id,instructions:p.instructions,envelopeId:finalEnvelopeId,innerEnvelopeId:finalInnerEnvelopeId,additionalEnvelopes:p.additionalEnvelopes,returnAddress:(parseFloat(p.returnAddress)==1)?1:0,returnAddressLine1:returnAddressLines[0]||null,returnAddressLine2:returnAddressLines[1]||null,returnAddressLine3:returnAddressLines[2]||null,returnAddressLine4:returnAddressLines[3]||null,returnAddressFontId:p.returnAddressFontId,returnAddressFontColorId:p.returnAddressFontColorId,returnAddressFontSize:p.returnAddressFontSize,returnAddressLeading:p.returnAddressLeading,redirect:'/related.html?pid='+p.productId+Personalize.product.color.number};var returnAddressLabelData={returnAddressLabel:Personalize.returnAddressLabelData.returnAddressLabel,returnAddressLabelProductId:Personalize.returnAddressLabelData.returnAddressLabelProductId,returnAddressLabelQuantity:Personalize.returnAddressLabelData.returnAddressLabelQuantity};if(Personalize.returnAddressLabelData.returnAddressLabel){TP.extendObject(addToCartParameters,returnAddressLabelData);}
if(Personalize.cartItemId){addToCartParameters.ciid=Personalize.cartItemId;}
if(Personalize.orderId){addToCartParameters.oid=Personalize.orderId;}
var addToCartFormElement=new Element('form',{action:'/addtocart.php',method:'POST',style:'display: none;'});for(var parameterName in addToCartParameters){var parameterValue=addToCartParameters[parameterName];var parameterElement=new Element('input',{name:parameterName,value:parameterValue});addToCartFormElement.insert(parameterElement);}
$(document.body).insert(addToCartFormElement);addToCartFormElement.submit();});},activateStep:function(stepName){for(var stepId in this.steps){var step=this.steps[stepId];if(step.name==stepName){this.activeStepIndex=stepId;if(Personalize.personalizationLoaded||this.activeStep!=step){this.trigger('changestep',stepName);this.activeStep.deactivate();this.activeStep=this.steps[this.activeStepIndex];this.activeStep.activate(false);this.updateNavigationTabs();this.setStepUrl();Personalize.personalizationLoaded=false;return;}}}},renderNavigationTabs:function(){var tabsListContainer=$("personalizeStepTabsList");var stepOrderNum=0;for(var stepId in this.steps){step=this.steps[stepId];if(step.available){stepOrderNum++;if(!$(step.name+"StepTabImage")){var li=new Element('li',{'class':'personalizeStepTab',id:step.name+'StepTab'});tabsListContainer.insert(li);var a=new Element('a',{style:'text-decoration: none'});li.insert(a);var stepImg=new Element('div',{id:step.name+"StepTabImage",'class':"stepTabImage sprite-icon-step"+stepOrderNum+"-disabled",style:"float:left"});a.insert(stepImg);var stepTabName=new Element('div',{id:step.name+"StepTabName",'class':"personalizeStepTabName disabled"}).update(step.title.toLowerCase());a.insert(stepTabName);}}}
this.updateNavigationTabs();},updateNavigationTabs:function(){for(var stepId in this.steps){var step=this.steps[stepId];if($(step.name+"StepTabImage")){var stepNs={stepName:step.name};activateStep=function(){return Personalize.activateStep(this.stepName);};if(stepId<this.activeStepIndex){var stepImg=$(step.name+"StepTabImage");stepImg.className=stepImg.className.sub('enabled','available');stepImg.className=stepImg.className.sub('disabled','available');stepImg.parentNode.observe('click',activateStep.bind(stepNs));stepImg.parentNode.setStyle({cursor:'pointer'});}else if(stepId>this.activeStepIndex){$(step.name+"StepTabName").addClassName('disabled');var stepImg=$(step.name+"StepTabImage");stepImg.className=stepImg.className.sub('enabled','disabled');stepImg.className=stepImg.className.sub('available','disabled');stepImg.parentNode.stopObserving('click');stepImg.parentNode.setStyle({cursor:''});}else{$("personalizeStepTitle").update(step.title);$(step.name+"StepTabName").removeClassName('disabled');if(step.description!==""&&typeof step.description!=="undefined"){$("personalizeStepDescription").update(step.description);}
var stepImg=$(step.name+"StepTabImage");stepImg.className=stepImg.className.sub('disabled','enabled');stepImg.className=stepImg.className.sub('available','enabled');stepImg.parentNode.observe('click',activateStep.bind(stepNs));stepImg.parentNode.setStyle({cursor:'pointer'});var backBtns=document.getElementsByClassName('sprite-btn-back');for(var i=0;i<backBtns.length;i++){if(this.findFirstAvailableStep()==stepId){backBtns[i].hide();}else{backBtns[i].show();}}}}}},roundForRendering:function(number){var roundingMultiplier=Math.pow(10,this.renderingDecimalPrecision);return Math.round(number*roundingMultiplier)/roundingMultiplier;},trigger:function(event){var args=[];for(var i=1;i<arguments.length;i++){args.push(arguments[i]);}
for(var handlerId=0;handlerId<Personalize.eventHandlers[event].length;handlerId++){var handler=Personalize.eventHandlers[event][handlerId];try{handler.apply(handler,args);}catch(e){}}},observe:function(event,handler){event=event.toLowerCase();Personalize.eventHandlers[event].push(handler);},addUriToCache:function(uri){for(var i=0;i<this.uris.length;i++){if(this.uris[i]==uri){return false;}}
this.uris.push(uri);return true;},windowSize:function(){var x,y;if(self.innerHeight){x=self.innerWidth;y=self.innerHeight;}else if(document.documentElement&&document.documentElement.clientHeight){x=document.documentElement.clientWidth;y=document.documentElement.clientHeight;}else if(document.body){x=document.body.clientWidth;y=document.body.clientHeight;}
return[x,y];},getPhotoExtension:function(photo){var mediaTypes={'image/bmp':'bmp','image/gif':'gif','image/jpeg':'jpg','image/png':'png','image/tiff':'tif','application/pdf':'pdf'};if(photo&&typeof mediaTypes[photo.type]!=='undefined'){return mediaTypes[photo.type];}
return null;},getUserPhoto:function(id){for(var i=0;i<this.userPhotos.length;i++){if(this.userPhotos[i].id==id)return this.userPhotos[i];}
return false;},actualPosition:function(object){var x=0,y=0;if(object){if(object.offsetParent){x=object.offsetLeft;y=object.offsetTop;while(object=object.offsetParent){x+=object.offsetLeft;y+=object.offsetTop;}}}
return[x,y];},popupRecentlyViewed:function(){if(!this.recentlyViewedPopup){this.recentlyViewedPopup=new PersonalizePopup('Recently Viewed','recentlyViewedPopup_');try{$('moreRecentlyViewed').observe('click',function(){if(this.extended){$('recentlyViewedContainerExtendedList').hide();$('recentlyViewedContainerList').show();}else{$('recentlyViewedContainerExtendedList').show();$('recentlyViewedContainerList').hide();}
this.extended=!this.extended;}.bind(this.recentlyViewedPopup));}catch(e){}
this.recentlyViewedPopup.extended=false;}
this.recentlyViewedPopup.getPopupElement().update($('recentlyViewedContainer'));this.recentlyViewedPopup.showPopup();},resolutionConvert:function(size,origRes,newRes){return((newRes*size)/origRes);},pxToNumber:function(pxString){return parseFloat(pxString.substring(0,pxString.length-1));},makeHover:function(element,baseClass,hoverClass){element.addClassName(baseClass);if(!hoverClass){var hoverClass=baseClass+'-hover';}
element.observe('mouseover',function(baseClass,hoverClass){this.removeClassName(baseClass);this.addClassName(hoverClass);}.bind(element,baseClass,hoverClass));element.observe('mouseout',function(baseClass,hoverClass){this.addClassName(baseClass);this.removeClassName(hoverClass);}.bind(element,baseClass,hoverClass));},getProjectDisplayName:function(){return((Personalize.personalization.name)?Personalize.personalization.name:Personalize.product.name);},isPhotoMontage:function(){return(Personalize.product.fulfillmentItemType.name=="Photo Montage");},help:function(){if(!this.helpDlg){this.helpDlg=new PersonalizePopup('Personalization Help','helpPopup_');var content=this.helpDlg.getPopupElement();var helpText='';var hasLogos=this.productHasLogos();var hasPhotos=(this.countProductPhotos()>0);if(Personalize.site=='TP'){if(parseFloat(Personalize.product.corporate)==1){if(hasPhotos){if(hasLogos){helpText=Personalize.strings.TPC_LOGOCARD_HELP;}else{helpText=Personalize.strings.TPC_PHOTOCARD_HELP;}}else{helpText=Personalize.strings.TPC_TEXTCARD_HELP;}}else{if(hasPhotos){helpText=Personalize.strings.TP_PHOTOCARD_HELP;}else{helpText=Personalize.strings.TP_TEXTCARD_HELP;}}}else{helpText=Personalize.strings.WPD_HELP;}
var text=new Element('div',{align:'left'}).update(helpText);var button=new Element('div',{'class':'sprite-btn_close clickable'});button.observe('click',this.helpDlg.hidePopup.bind(this.helpDlg));var buttonCont=new Element('div',{align:'right'}).update(button);content.insert(text);content.insert(buttonCont);content.setStyle({padding:'20px',fontFamily:'Helvetica',fontSize:'12px',width:'400px'});this.helpDlg.hidePopup();}
console.log('Here');try{var linkPos=$('helpBtnText').cumulativeOffset();var left=linkPos[0]+$('helpBtnText').getWidth()-440;var top=linkPos[1]+16;}catch(e){console.log(e);}
this.helpDlg.showPopup(left,top);},helpPreview:function(){if(!this.helpDlg){this.helpDlg=new PersonalizePopup('Preview Help','helpPopup_');var content=this.helpDlg.getPopupElement();var text=new Element('div',{align:'left'}).update('<ul class="helpText" style="list-style-type: disc;"><li>If you have any special requests that cannot be completed on the website, please enter them in the special instructions box. A professional designer will work with you to accommodate your requests.</li><li>A professional designer will review and may enhance your logo(s) and photo(s) for the best quality printing. Please visit <a href="http://www.tinyprints.com/tiny-prints-difference.htm" target="_blank">here</a> for more details.</li><li>Visit the <a href="'+Personalize.hosts.www+(Personalize.product.corporate==1?'tiny-prints-corporate-holiday-faq.htm':'orderinfo.htm')+'" target="_blank">Frequently Asked Questions</a> section for more information.</li></ul>');var button=new Element('div',{'class':'sprite-btn_close clickable'});button.observe('click',this.helpDlg.hidePopup.bind(this.helpDlg));var buttonCont=new Element('div',{align:'right'}).update(button);content.insert(text);content.insert(buttonCont);content.setStyle({padding:'20px',fontFamily:'Helvetica',fontSize:'12px',width:'400px'});this.helpDlg.hidePopup();}
this.helpDlg.showPopup();},effects:{transitions:{elastic:function(pos){return-1*Math.pow(4,-8*pos)*Math.sin((pos*6-1)*(2*Math.PI)/2)+1;},swingFromTo:function(pos){var s=1.70158;if((pos/=0.5)<1)return 0.5*(pos*pos*(((s*=(1.525))+1)*pos-s));return 0.5*((pos-=2)*pos*(((s*=(1.525))+1)*pos+s)+2);},swingFrom:function(pos){var s=1.70158;return pos*pos*((s+1)*pos-s);},swingTo:function(pos){var s=1.70158;return(pos-=1)*pos*((s+1)*pos+s)+1;},bounce:function(pos){if(pos<(1/2.75)){return(7.5625*pos*pos);}else if(pos<(2/2.75)){return(7.5625*(pos-=(1.5/2.75))*pos+.75);}else if(pos<(2.5/2.75)){return(7.5625*(pos-=(2.25/2.75))*pos+.9375);}else{return(7.5625*(pos-=(2.625/2.75))*pos+.984375);}},bouncePast:function(pos){if(pos<(1/2.75)){return(7.5625*pos*pos);}else if(pos<(2/2.75)){return 2-(7.5625*(pos-=(1.5/2.75))*pos+.75);}else if(pos<(2.5/2.75)){return 2-(7.5625*(pos-=(2.25/2.75))*pos+.9375);}else{return 2-(7.5625*(pos-=(2.625/2.75))*pos+.984375);}},easeFromTo:function(pos){if((pos/=0.5)<1)return 0.5*Math.pow(pos,4);return-0.5*((pos-=2)*Math.pow(pos,3)-2);},easeFrom:function(pos){return Math.pow(pos,4);},easeTo:function(pos){return Math.pow(pos,0.25);}},reverts:{instantRevert:function(element,top_offset,left_offset){new Effect.Move(element,{x:-left_offset,y:-top_offset,duration:0,queue:{scope:'revert',position:'end'}});}}},countProductPhotos:function(){var photoCount=0;for(var panelId in Personalize.product.panels){var panel=Personalize.product.panels[panelId];for(var photoId in panel.photos){photoCount++;}
for(var layoutId in panel.layouts){var layout=panel.layouts[layoutId];for(var layoutPhotoId in layout.photos){photoCount++;}}}
return photoCount;},productHasLogos:function(){for(var panelId in Personalize.product.panels){var panel=Personalize.product.panels[panelId];for(var photoId in panel.photos){if(parseFloat(panel.photos[photoId])==1)return true;}
for(var layoutId in panel.layouts){var layout=panel.layouts[layoutId];for(var layoutPhotoId in layout.photos){if(parseFloat(layout.photos[layoutPhotoId])==1)return true;}}}
return false;}}
Object.extend(Event,{wheel:function(event){var delta=0;if(!event)event=window.event;if(event.wheelDelta){delta=event.wheelDelta/120;if(window.opera)delta=-delta;}else if(event.detail){delta=-event.detail/3;}
return Math.round(delta);}});var PersonalizePopup=function(title,cssPrefix,modal){if(typeof modal=='undefined'){this.modal=false;}else{this.modal=modal;}
if(this.modal){this.callback=this.defaultModalClick.bind(this);}
this.title=title;this.cssPrefix=cssPrefix;this.zIndex=0;this.domElement=new Element('div',{'class':this.cssPrefix+'Window personalizePopup'});this.handle=new Element('div',{align:'right','class':this.cssPrefix+'Handle moveable personalizePopupHandle'});this.titleElem=new Element('div',{'class':this.cssPrefix+'Title personalizePopupTitle'}).update(this.title);if(!this.modal){this.closeBox=new Element('div',{'class':this.cssPrefix+'Close clickable sprite-icon-close personalizePopupClose'});this.closeBox.onclick=this.outsideClick.bind(this);this.closeBoxTxt=new Element('div',{'class':this.cssPrefix+'Close clickable personalizePopupCloseTxt'}).update('Close');this.closeBoxTxt.onclick=this.outsideClick.bind(this);this.handle.insert(this.closeBox);this.handle.insert(this.closeBoxTxt);}
this.handle.insert(this.titleElem);this.contentElement=new Element('div',{'class':this.cssPrefix+'Content'});this.domElement.insert(this.handle);this.domElement.insert(new Element('div',{style:'clear:both'}));this.domElement.insert(this.contentElement);this.maskElement=new Element('div');this.maskElement.setOpacity(0.2);this.maskElement.setStyle({position:'absolute',top:0,left:0,zIndex:(++Personalize.popupZIndex),width:'100%',backgroundColor:'#000',display:'none'});if(!Personalize.ie6){this.maskElement.setStyle({position:'fixed'});}
this.draggable=new Draggable(this.domElement,{handle:this.handle});this.keyDownHandler=this.handleKeydown.bindAsEventListener(this);document.body.insertBefore(this.maskElement,document.body.childNodes[0]);document.body.insertBefore(this.domElement,document.body.childNodes[0]);}
PersonalizePopup.prototype={getPopupElement:function(){return this.contentElement;},showPopup:function(pX,pY){this.maskElement.style.height=document.viewport.getHeight()+'px';this.maskElement.onclick=this.outsideClick.bind(this);this.maskElement.setOpacity(0);this.maskElement.show();this.maskElement.fade({duration:0.2,from:0,to:0.6});this.maskElement.setStyle({zIndex:(++Personalize.popupZIndex)});this.zIndex=(++Personalize.popupZIndex)
this.domElement.setStyle({position:'absolute',backgroundColor:'#FFF',zIndex:this.zIndex,display:'none'});this.draggable.options.zindex=this.zIndex
if(!Personalize.ie6){this.domElement.setStyle({position:'fixed'});}
this.domElement.show();this.domElement.setStyle({width:this.contentElement.getWidth()+'px'});var width=this.contentElement.getWidth();if(Personalize.isIe()){this.domElement.setStyle({width:(this.contentElement.getWidth())+'px'});}
if(pX&&pY){var leftPos=pX;var topPos=pY;}else{var leftPos=(document.viewport.getWidth()-this.domElement.getWidth())/2;var topPos=(document.viewport.getHeight()-this.domElement.getHeight())/2;}
this.domElement.setStyle({left:leftPos+'px',top:topPos+'px'});Event.observe(document,'keypress',this.keyDownHandler);},handleKeydown:function(ev){switch(ev.keyCode){case 27:this.outsideClick();break;default:break;}},recenter:function(){this.domElement.setStyle({width:this.contentElement.getWidth()+'px'});var width=this.contentElement.getWidth();if(Personalize.isIe()){this.domElement.setStyle({width:(this.contentElement.getWidth())+'px'});}
var leftPos=(document.viewport.getWidth()-this.domElement.getWidth())/2;var topPos=(document.viewport.getHeight()-this.domElement.getHeight())/2;this.domElement.setStyle({left:leftPos+'px',top:topPos+'px'});},outsideClick:function(){if(this.callback){this.callback();}else{this.hidePopup();}},defaultModalClick:function(){},hidePopup:function(){Event.stopObserving(document,'keypress',this.keyDownHandler);this.maskElement.hide();this.domElement.hide();},destroy:function(){this.domElement.remove();this.maskElement.remove();}}
var PersonalizeZoomBox=Class.create({});PersonalizeZoomBox.prototype={zoomDlg:null,uris:[],initialize:function(title,uri){this.title=title;this.uri=uri;},showZoom:function(){if(!this.zoomDlg){this.zoomDlg=new PersonalizePopup(this.title,'zoomBox');this.zoomDlg.domElement.setStyle({width:"260px",height:"70px"});}
var content=this.zoomDlg.getPopupElement();content.setStyle({width:'260px',height:'70px',overflow:'hidden'});var loader=new Element('div');var img=new Element('img',{src:Personalize.hosts['static']+'image/wpd/loading-bar.gif'});loader.insert(img);var text=new Element('div',{'style':'font-family:Helvetica; font-size: 12px; color: #3992B4'}).update('Loading Zoom');loader.insert(text);content.update(loader);this.zoomDlg.showPopup();var previewImage=new Element('img',{src:this.uri});previewImage.observe('load',this.zoomLoaded.bindAsEventListener(this,loader,previewImage));content.insert(previewImage);if(Personalize.isIe()){if(previewImage.complete){this.zoomLoaded(null,loader,previewImage);}}},zoomLoaded:function(ev,loader,image){if(loader!==null){loader.remove();}
var content=this.zoomDlg.getPopupElement();content.setStyle({width:image.getWidth()+10+'px',height:image.getHeight()+10+'px'});this.zoomDlg.domElement.setStyle({width:image.getWidth()+10+'px',height:image.getHeight()+20+'px'});this.zoomDlg.recenter();}};var SuperDraggable=Class.create();TP.extendObject(SuperDraggable.prototype,Draggable.prototype,{initialize:function(element){var defaults={handle:false,reverteffect:function(element,top_offset,left_offset){var dur=Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;new Effect.Move(element,{x:-left_offset,y:-top_offset,duration:dur,queue:{scope:'_draggable',position:'end'}});},endeffect:function(element){var toOpacity=typeof element._opacity=='number'?element._opacity:1.0;new Effect.Opacity(element,{duration:0.2,from:0.7,to:toOpacity,queue:{scope:'_draggable',position:'end'},afterFinish:function(){Draggable._dragging[element]=false}});},zindex:55000,revert:false,scroll:false,scrollSensitivity:20,scrollSpeed:15,snap:false,delay:0};if(!arguments[1]||typeof arguments[1].endeffect=='undefined')
Object.extend(defaults,{starteffect:function(element){element._opacity=Element.getOpacity(element);Draggable._dragging[element]=true;new Effect.Opacity(element,{duration:0.2,from:element._opacity,to:0.7});}});var options=Object.extend(defaults,arguments[1]||{});this.element=$(element);if(options.handle&&(typeof options.handle=='string'))
this.handle=this.element.down('.'+options.handle,0);if(!this.handle)this.handle=$(options.handle);if(!this.handle)this.handle=this.element;if(options.scroll&&!options.scroll.scrollTo&&!options.scroll.outerHTML){options.scroll=$(options.scroll);this._isScrollChild=Element.childOf(this.element,options.scroll);}
Element.makePositioned(this.element);this.delta=this.currentDelta();this.options=options;this.dragging=false;if(options.ghostingResize){if(typeof options.ghostingResize=='object'){this.ghostingResizeX=this.options.ghostingResize[0];this.ghostingResizeY=this.options.ghostingResize[1];}
else{this.ghostingResizeX=this.options.ghostingResize;this.ghostingResizeY=this.options.ghostingResize;}}
this.eventMouseDown=this.initDrag.bindAsEventListener(this);Event.observe(this.handle,"mousedown",this.eventMouseDown);Draggables.register(this);},startDrag:function(event){this.startingScroll={top:0,left:0};this.startingScroll.top=this.element.up().up().scrollTop;this.dragging=true;if(this.options.zindex){this.originalZ=parseInt(Element.getStyle(this.element,'z-index')||0);this.element.style.zIndex=this.options.zindex;}
if(this.options.ghosting){this._clone=this.element.cloneNode(true);Position.absolutize(this.element);this.element.parentNode.insertBefore(this._clone,this.element);Element.remove(this.element);this._bodyElement=document.body.appendChild(this.element);if(this.options.ghostingResize){var bodyElementWidth=parseFloat(Element.getStyle(this._bodyElement,'width'));var bodyElementHeight=parseFloat(Element.getStyle(this._bodyElement,'height'));if(bodyElementWidth>bodyElementHeight){var multiplier=this.ghostingResizeX/bodyElementWidth;}
else{var multiplier=this.ghostingResizeY/bodyElementHeight;}
var bodyElementNewWidth=bodyElementWidth*multiplier;var bodyElementNewHeight=bodyElementHeight*multiplier;this._bodyElement.style.width=bodyElementNewWidth+'px';this._bodyElement.style.height=bodyElementNewHeight+'px';}}
if(this.options.scroll){if(this.options.scroll==window){var where=this._getWindowScroll(this.options.scroll);this.originalScrollLeft=where.left;this.originalScrollTop=where.top;}else{this.originalScrollLeft=this.options.scroll.scrollLeft;this.originalScrollTop=this.options.scroll.scrollTop;}}
Draggables.notify('onStart',this,event);if(this.options.starteffect)this.options.starteffect(this.element);},finishDrag:function(event,success){this.dragging=false;if(this.options.ghosting){Position.relativize(this.element);Element.remove(this._bodyElement);this._clone.parentNode.insertBefore(this._bodyElement,this._clone);Element.remove(this._clone);this._clone=null;}
if(success)Droppables.fire(event,this.element);Draggables.notify('onEnd',this,event);var revert=this.options.revert;if(revert&&typeof revert=='function')revert=revert(this.element);var d=this.currentDelta();if(revert&&this.options.reverteffect){this.options.reverteffect(this.element,d[1]-this.delta[1],d[0]-this.delta[0]);}else{this.delta=d;}
if(this.options.zindex)
this.element.style.zIndex=this.originalZ;if(this.options.endeffect)
this.options.endeffect(this.element);Draggables.deactivate(this);Droppables.reset();},updateDrag:function(event,pointer){if(!this.dragging)this.startDrag(event);if(!this.options.quiet){Position.prepare();Droppables.show(pointer,this.element);}
Draggables.notify('onDrag',this,event);this.draw(pointer);this.element.style.top=Personalize.pxToNumber(this.element.style.top)-this.startingScroll.top+'px';if(this.options.change)this.options.change(this);if(this.options.scroll){this.stopScrolling();var p;if(this.options.scroll==window){with(this._getWindowScroll(this.options.scroll)){p=[left,top,left+width,top+height];}}else{p=Position.page(this.options.scroll);p[0]+=this.options.scroll.scrollLeft+Position.deltaX;p[1]+=this.options.scroll.scrollTop+Position.deltaY;p.push(p[0]+this.options.scroll.offsetWidth);p.push(p[1]+this.options.scroll.offsetHeight);}
var speed=[0,0];if(pointer[0]<(p[0]+this.options.scrollSensitivity))speed[0]=pointer[0]-(p[0]+this.options.scrollSensitivity);if(pointer[1]<(p[1]+this.options.scrollSensitivity))speed[1]=pointer[1]-(p[1]+this.options.scrollSensitivity);if(pointer[0]>(p[2]-this.options.scrollSensitivity))speed[0]=pointer[0]-(p[2]-this.options.scrollSensitivity);if(pointer[1]>(p[3]-this.options.scrollSensitivity))speed[1]=pointer[1]-(p[3]-this.options.scrollSensitivity);this.startScrolling(speed);}
if(Prototype.Browser.WebKit)window.scrollBy(0,0);Event.stop(event);},keyPress:function(event){if(event.keyCode!=Event.KEY_ESC)return;this.finishDrag(event,false);Event.stop(event);}});var FlexUploadApi=Class.create({flexUploadDomId:'flexPhotoUpload',environment:null,flexComponent:null,progressBar:null,initialize:function(){this.uploadedCount=0;if($(this.flexUploadDomId)){this.flexUploadDom=$(this.flexUploadDomId);}
if(this.isSupported()){if($(this.flexUploadDomId)){this.flexComponent=$('wpdfileupload');this.flexUploadDom.insert({top:this.flexComponent});this.flexComponent.width=90;this.flexComponent.height=27;this.flexComponent.setStyle({float:'left'});try{this.flexComponent.show();}catch(e){}
this.progressBar=new ProgressBarComp(200,15,"progressBarContainer");}}},getFlexUploadDom:function(){return this.flexUploadDom;},getEnvironmentVars:function(){this.environment=function(){return{url:Personalize.hosts.imagesProxy+'personalize/photo/',curPhotoCount:Personalize.activeStep.getUserPhotos().length,sessionId:Personalize.sessionId};}();return this.environment;},updateUploadStatus:function(responseData){switch(responseData.status){case'complete':var photo=responseData.data.evalJSON();Personalize.activeStep.photoUploaderAddPhoto(photo);Personalize.activeStep.photoUploaderCheckAddToOpener(photo);Personalize.activeStep.addPhotoToTray(photo);this.uploadedCount+=1;this.progressBar.setUploadCount(this.uploadedCount);break;case'updateprogress':this.progressBar.setProgress(responseData.min,responseData.max);break;case'resetprogress':this.progressBar.reset();this.uploadedCount=0;break;case'ioerror':case'oversize':case'maxallowed':case'security':case'debug':default:alert('Upload Failed :'+responseData.message);break;}},isSupported:function(){return hasProductInstall&&hasRequestedVersion;},testFlex:function(){this.flexComponent.jsBrowseAndUpload();}});var ProgressBarComp=Class.create({label:null,width:100,height:25,containerDom:null,progressBar:null,label:null,uploadedLabel:null,barWidth:10,curDisplayBar:0,initialize:function(width,height,containerDomId){this.width=width;this.height=height;if($(containerDomId)){this.containerDom=$(containerDomId);this.render();}},render:function(){var progressBar=new Element('div',{'class':'progress-bar',style:'width: '+this.width+'px; height:'+this.height+'px'});var label=new Element('div',{'class':'progress-bar-label'});var uploadedLabel=new Element('div',{'class':'progress-bar-uploadedLabel'});this.progressBar=progressBar;this.label=label;this.uploadedLabel=uploadedLabel;this.containerDom.insert(progressBar);this.containerDom.insert(label);this.containerDom.insert(uploadedLabel);},setUploadCount:function(uploadedCount){this.uploadedLabel.update(uploadedCount+" photo(s) uploaded");},setProgress:function(min,max){if(min>max){max=min;}
var mb=1000000;var kb=1000;var totalNumBars=parseInt(this.width/this.barWidth);var ratio=parseFloat(min/max);var numberRequiredBar=parseInt(ratio*totalNumBars);for(var i=this.curDisplayBar;i<numberRequiredBar;i++){var bar=new Element('div',{'class':'percentage-bar',style:'width: '+(this.barWidth-1)+'px; height: 15px; float: left'});this.progressBar.insert(bar);var percentage=parseInt(100*(min/max));if(max>mb){this.label.update(this.format(min/mb)+"MB of "+this.format(max/mb)+"MB&nbsp;&nbsp;-&nbsp;&nbsp;"+percentage+"%");}else if(max>kb){this.label.update(this.format(min/kb)+"KB of "+this.format(max/kb)+"KB&nbsp;&nbsp;-&nbsp;&nbsp;"+percentage+"%");}else{this.label.update(min+"bytes of "+max+"bytes "+percentage+"%");}
this.curDisplayBar++;}},format:function(val){return formatVal=parseInt(val*100)/100;},reset:function(){this.progressBar.update('');this.label.update('Browsing... 0%');this.curDisplayBar=0;}});

var Personalization=function(){this.primaryProxy={id:null,memberId:null,sessionId:null,cartItemId:null,orderId:null,project:null,textboxLock:null,photoLock:null,layoutLock:null,publicAccess:null,passphrase:null,created:null,modified:null,accessEmails:[]};this.panels={};this.templateCodeValues={};};Personalization.prototype={id:null,productId:null,productColorId:null,memberId:null,sessionId:null,name:null,quantity:null,priceAtQuantity:null,instructions:null,envelopeId:null,linedEnvelopeId:null,envelopePairId:null,pairLinedEnvelopeId:null,additionalEnvelopes:null,additionalEnvelopesPrice:null,returnAddress:null,returnAddressFront:null,returnAddressSetupPrice:null,returnAddressPrice:null,returnAddressAlignmentId:null,returnAddressX:null,returnAddressY:null,returnAddressWidth:null,returnAddressHeight:null,returnAddressText:null,returnAddressFontId:null,returnAddressFontColorId:null,returnAddressFontSize:12,returnAddressLeading:null,returnAddressDoodleX:null,returnAddressDoodleY:null,returnAddressDoodleHeight:null,returnAddressDoodleWidth:null,timestamp:null,paperId:null,colorCyan:null,colorMagenta:null,colorYellow:null,colorBlack:null,mailingService:null,stampId:null,doodleId:null,recipientContacts:null,primaryProxy:{id:null,memberId:null,sessionId:null,cartItemId:null,orderId:null,project:null,textboxLock:null,photoLock:null,layoutLock:null,publicAccess:null,passphrase:null,created:null,modified:null,accessEmails:[]},panels:{},templateCodeValues:{},loadJSON:function(json){if(json){TP.extendObject(this,json);if(json.primaryProxy){TP.extendObject(this.primaryProxy,json.primaryProxy);}
this.primaryProxy.accessEmails=[];if(json.accessEmails){for(var accessEmailIndex=0;accessEmailIndex<json.accessEmails.length;accessEmailIndex++){var accessEmail=json.accessEmails[accessEmailIndex];this.accessEmails.push(accessEmail);}}
if(json.panels){for(var panelJsonIndex in json.panels){var panelJson=json.panels[panelJsonIndex];var panel=new Panel();panel.loadJSON(panelJson);this.panels[panelJsonIndex]=panel;}}
if(json.templateCodeValues){this.templateCodeValues=json.templateCodeValues;}}},toJSON:function(){var self=this;return{id:self.id,productId:self.productId,productColorId:self.productColorId,memberId:self.memberId,sessionId:self.sessionId,name:self.name,quantity:self.quantity,priceAtQuantity:self.priceAtQuantity,instructions:self.instructions,envelopeId:self.envelopeId,linedEnvelopeId:self.linedEnvelopeId,envelopePairId:self.envelopePairId,pairLinedEnvelopeId:self.pairLinedEnvelopeId,additionalEnvelopes:self.additionalEnvelopes,additionalEnvelopesPrice:self.additionalEnvelopesPrice,returnAddress:self.returnAddress,returnAddressFront:self.returnAddressFront,returnAddressSetupPrice:self.returnAddressSetupPrice,returnAddressPrice:self.returnAddressPrice,returnAddressAlignmentId:self.returnAddressAlignmentId,returnAddressX:self.returnAddressX,returnAddressY:self.returnAddressY,returnAddressWidth:self.returnAddressWidth,returnAddressHeight:self.returnAddressHeight,returnAddressText:self.returnAddressText,returnAddressFontId:self.returnAddressFontId,returnAddressFontColorId:self.returnAddressFontColorId,returnAddressFontSize:self.returnAddressFontSize,returnAddressLeading:self.returnAddressLeading,returnAddressDoodleX:self.returnAddressDoodleX,returnAddressDoodleY:self.returnAddressDoodleY,returnAddressDoodleHeight:self.returnAddressDoodleHeight,returnAddressDoodleWidth:self.returnAddressDoodleWidth,proof:self.proof,proofPrice:self.proofPrice,timestamp:self.timestamp,paperId:self.paperId,colorCyan:self.colorCyan,colorMagenta:self.colorMagenta,colorYellow:self.colorYellow,colorBlack:self.colorBlack,mailingService:self.mailingService,stampId:self.stampId,doodleId:self.doodleId,recipientContacts:self.recipientContacts,primaryProxy:self.primaryProxy,accessEmails:self.accessEmails,panels:self.panels,templateCodeValues:self.templateCodeValues};}};var Panel=function(){this.textboxes={};this.photos={};this.overlays={};this.separators={};this.designAreas={};this.layoutTextboxes={};this.layoutPhotos={};this.layoutOverlays={};};Panel.prototype={id:null,personalizationId:null,panelId:null,layoutId:null,layoutX:null,layoutY:null,layoutWidth:null,layoutHeight:null,layoutZ:null,approvalInitial:null,approvalTimestamp:null,textboxes:{},photos:{},overlays:{},separators:{},designAreas:{},doodles:{},layoutTextboxes:{},layoutPhotos:{},layoutOverlays:{},loadJSON:function(json){if(json){TP.extendObject(this,json);this.layoutX=parseFloat(this.layoutX);this.layoutY=parseFloat(this.layoutY);this.layoutWidth=parseFloat(this.layoutWidth);this.layoutHeight=parseFloat(this.layoutHeight);this.layoutZ=parseFloat(this.layoutZ);if(json.textboxes){for(var textboxJsonIndex in json.textboxes){var textboxJson=json.textboxes[textboxJsonIndex];var textbox=new Textbox();textbox.loadJSON(textboxJson);this.textboxes[textboxJsonIndex]=textbox;}}
if(json.photos){for(var photoJsonIndex in json.photos){var photoJson=json.photos[photoJsonIndex];var photo=new Photo();photo.loadJSON(photoJson);this.photos[photoJsonIndex]=photo;}}
if(json.overlays){for(var overlayJsonIndex in json.overlays){var overlayJson=json.overlays[overlayJsonIndex];var overlay=new Overlay();overlay.loadJSON(overlayJson);this.overlays[overlayJsonIndex]=overlay;}}
if(json.separators){for(var separatorJsonIndex in json.separators){var separatorJson=json.separators[separatorJsonIndex];var separator=new Separator();separator.loadJSON(separatorJson);this.separators[separatorJsonIndex]=separator;}}
if(json.designAreas){for(var designAreaJsonIndex in json.designAreas){var designAreaJson=json.designAreas[designAreaJsonIndex];var designArea=new DesignArea();designArea.loadJSON(designAreaJson);this.designAreas[designAreaJsonIndex]=designArea;}}
if(json.doodles){for(var doodleJsonIndex in json.doodles){var doodleJson=json.doodles[doodleJsonIndex];var doodle=new Doodle();doodle.loadJSON(doodleJson);this.doodles[doodleJsonIndex]=doodle;}}
if(json.layoutTextboxes){for(var layoutTextboxJsonIndex in json.layoutTextboxes){var layoutTextboxJson=json.layoutTextboxes[layoutTextboxJsonIndex];var layoutTextbox=new LayoutTextbox();layoutTextbox.loadJSON(layoutTextboxJson);this.layoutTextboxes[layoutTextboxJsonIndex]=layoutTextbox;}}
if(json.layoutPhotos){for(var layoutPhotoJsonIndex in json.layoutPhotos){var layoutPhotoJson=json.layoutPhotos[layoutPhotoJsonIndex];var layoutPhoto=new LayoutPhoto();layoutPhoto.loadJSON(layoutPhotoJson);this.layoutPhotos[layoutPhotoJsonIndex]=layoutPhoto;}}
if(json.layoutOverlays){for(var layoutOverlayJsonIndex in json.layoutOverlays){var layoutOverlayJson=json.layoutOverlays[layoutOverlayJsonIndex];var layoutOverlay=new LayoutOverlay();layoutOverlay.loadJSON(layoutOverlayJson);this.layoutOverlays[layoutOverlayJsonIndex]=layoutOverlay;}}}},toJSON:function(){var self=this;return{id:self.id,personalizationId:self.personalizationId,panelId:self.panelId,layoutId:self.layoutId,layoutX:self.layoutX,layoutY:self.layoutY,layoutWidth:self.layoutWidth,layoutHeight:self.layoutHeight,layoutZ:self.layoutZ,approvalInitial:self.approvalInitial,approvalTimestamp:self.approvalTimestamp,textboxes:self.textboxes,photos:self.photos,overlays:self.overlays,separators:self.separators,designAreas:self.designAreas,layoutTextboxes:self.layoutTextboxes,layoutPhotos:self.layoutPhotos,layoutOverlays:self.layoutOverlays,doodles:self.doodles};},show:function(){},hide:function(){}};var Textbox=function(){};Textbox.prototype={id:null,panelId:null,textboxId:null,typeId:null,name:null,content:null,x:null,y:null,width:null,height:null,controlX:null,controlY:null,controlWidth:null,controlHeight:null,z:null,leading:null,tracking:null,stroke:null,horizontalAlignmentId:null,verticalAlignmentId:null,defaultCasingId:null,angle:null,fontId:null,fontColorId:null,fontSize:null,loadJSON:function(json){if(json){TP.extendObject(this,json);}
this.x=parseFloat(this.x);this.y=parseFloat(this.y);this.width=parseFloat(this.width);this.height=parseFloat(this.height);this.controlX=parseFloat(this.controlX);this.controlY=parseFloat(this.controlY);this.controlWidth=parseFloat(this.controlWidth);this.controlHeight=parseFloat(this.controlHeight);this.z=parseFloat(this.z);},toJSON:function(){var self=this;return{id:self.id,panelId:self.panelId,textboxId:self.textboxId,typeId:self.typeId,name:self.name,content:self.content,x:self.x,y:self.y,width:self.width,height:self.height,controlX:self.controlX,controlY:self.controlY,controlWidth:self.controlWidth,controlHeight:self.controlHeight,z:self.z,leading:self.leading,tracking:self.tracking,stroke:self.stroke,horizontalAlignmentId:self.horizontalAlignmentId,verticalAlignmentId:self.verticalAlignmentId,defaultCasingId:self.defaultCasingId,angle:self.angle,fontId:self.fontId,fontColorId:self.fontColorId,fontSize:self.fontSize};}};var Photo=function(){};Photo.prototype={id:null,panelId:null,photoId:null,x:null,y:null,width:null,height:null,z:null,minimumWidth:null,minimumHeight:null,recommendedWidth:null,recommendedHeight:null,frameWidth:null,frameStyle:null,frameColorId:null,logo:null,overlayImageId:null,contentPhotoId:null,cropX:null,cropY:null,cropWidth:null,cropHeight:null,rotation:null,effectId:null,loadJSON:function(json){if(json){TP.extendObject(this,json);}
this.x=parseFloat(this.x);this.y=parseFloat(this.y);this.width=parseFloat(this.width);this.height=parseFloat(this.height);this.z=parseFloat(this.z);this.minimumWidth=parseFloat(this.minimumWidth);this.minimumHeight=parseFloat(this.minimumHeight);this.recommendedWidth=parseFloat(this.recommendedWidth);this.recommendedHeight=parseFloat(this.recommendedHeight);this.frameWidth=parseFloat(this.frameWidth);this.logo=parseFloat(this.logo);this.cropX=parseFloat(this.cropX);this.cropY=parseFloat(this.cropY);this.cropWidth=parseFloat(this.cropWidth);this.cropHeight=parseFloat(this.cropHeight);this.rotation=parseFloat(this.rotation);},toJSON:function(){var self=this;return{id:self.id,panelId:self.panelId,photoId:self.photoId,x:self.x,y:self.y,width:self.width,height:self.height,z:self.z,minimumWidth:self.minimumWidth,minimumHeight:self.minimumHeight,recommendedWidth:self.recommendedWidth,recommendedHeight:self.recommendedHeight,frameWidth:self.frameWidth,frameStyle:self.frameStyle,frameColorId:self.frameColorId,logo:self.logo,overlayImageId:self.overlayImageId,contentPhotoId:self.contentPhotoId,cropX:self.cropX,cropY:self.cropY,cropWidth:self.cropWidth,cropHeight:self.cropHeight,rotation:self.rotation,effectId:self.effectId};}};var Overlay=function(){};Overlay.prototype={id:null,panelId:null,overlayId:null,x:null,y:null,width:null,height:null,z:null,imageId:null,loadJSON:function(json){if(json){TP.extendObject(this,json);}
this.x=parseFloat(this.x);this.y=parseFloat(this.y);this.width=parseFloat(this.width);this.height=parseFloat(this.height);this.z=parseFloat(this.z);},toJSON:function(){var self=this;return{id:self.id,panelId:self.panelId,overlayId:self.overlayId,x:self.x,y:self.y,width:self.width,height:self.height,z:self.z,imageId:self.imageId};}};var Separator=function(){};Separator.prototype={id:null,panelId:null,separatorId:null,x:null,y:null,width:null,height:null,loadJSON:function(json){if(json){TP.extendObject(this,json);}
this.x=parseFloat(this.x);this.y=parseFloat(this.y);this.width=parseFloat(this.width);this.height=parseFloat(this.height);},toJSON:function(){var self=this;return{id:self.id,panelId:self.panelId,separatorId:self.separatorId,x:self.x,y:self.y,width:self.width,height:self.height};}};var DesignArea=function(){}
DesignArea.prototype={id:null,panelId:null,designAreaId:null,x:null,y:null,width:null,height:null,alignmentId:null,horizontalDistributionId:null,verticalDistributionId:null,loadJSON:function(json){if(json){TP.extendObject(this,json);}
this.x=parseFloat(this.x);this.y=parseFloat(this.y);this.width=parseFloat(this.width);this.height=parseFloat(this.height);},toJSON:function(){var self=this;return{id:self.id,panelId:self.panelId,designAreaId:self.designAreaId,x:self.x,y:self.y,width:self.width,height:self.height,alignmentId:self.alignmentId,horizontalDistributionId:self.horizontalDistributionId,verticalDistributionId:self.verticalDistributionId};}};var Doodle=function(){};Doodle.prototype={id:null,panelId:null,doodleId:null,name:null,displayName:null,imageId:null,x:null,y:null,width:null,height:null,z:null,loadJSON:function(json){if(json){TP.extendObject(this,json);}
this.x=parseFloat(this.x);this.y=parseFloat(this.y);this.width=parseFloat(this.width);this.height=parseFloat(this.height);this.z=parseFloat(this.z);},toJSON:function(){var self=this;return{id:self.id,panelId:self.panelId,doodleId:self.doodleId,name:self.name,displayName:self.displayName,imageId:self.imageId,x:self.x,y:self.y,width:self.width,height:self.height,z:self.z};}};var LayoutTextbox=function(){};LayoutTextbox.prototype=new Textbox();var LayoutPhoto=function(){};LayoutPhoto.prototype=new Photo();var LayoutOverlay=function(){};LayoutOverlay.prototype=new Overlay();

var Step=function(element,title,navStates){if(typeof element!=='undefined'){this.element=(typeof element==='string')?document.getElementById(element):element;try{$(this.element.id).hide();}catch(e){}}
if(typeof title!=='undefined'){this.title=title;}
if(typeof navStates!=='undefined'){this.navStates=navStates;}};Step.prototype={element:null,title:null,description:null,available:false,navStates:null,status:null,init:function(){},activate:function(){return true;},deactivate:function(){},back:function(){return true;},next:function(){return true;},setError:function(){return true}};

var PersonalizeServices=function(){};PersonalizeServices.prototype={savePersonalization:function(title,callback,createNew){var creatingNew=(createNew||!Personalize.personalization.id)?true:false;var personalization=Personalize.personalization;try{personalization.templateCodeValues=this.getP13nStep().getTemplateCodeValues();}catch(e){personalization.templateCodeValues={};}
if(createNew){personalization.name=title;}
if(Personalize.member){if(Personalize.member.id){Personalize.personalization.memberId=Personalize.member.id;Personalize.personalization.primaryProxy.memberId=Personalize.member.id;}}
new Ajax.Request('/personalization/'+((!creatingNew)?personalization.id:''),{parameters:{personalization:JSON.stringify(personalization)},onSuccess:function(transport){var savedPersonalization=transport.responseJSON;if(savedPersonalization){var p=Personalize.personalization;var sp=savedPersonalization;p.timestamp=sp.timestamp;p.primaryProxy.modified=sp.primaryProxy.modified;if(creatingNew){p.primaryProxy.created=sp.primaryProxy.created;p.id=sp.id;p.primaryProxy.id=sp.primaryProxy.id;for(var panelId in p.panels){var pPanel=p.panels[panelId];var spPanel=sp.panels[panelId];if(spPanel){pPanel.id=spPanel.id;for(var textboxId in pPanel.textboxes){var pTextbox=pPanel.textboxes[textboxId];var spTextbox=spPanel.textboxes[textboxId];if(spTextbox){pTextbox.id=spTextbox.id;pTextbox.panelId=spTextbox.panelId;}}
for(var photoId in pPanel.photos){var pPhoto=pPanel.photos[photoId];var spPhoto=spPanel.photos[photoId];if(spPhoto){pPhoto.id=spPhoto.id;pPhoto.panelId=spPhoto.panelId;}}
for(var overlayId in pPanel.overlays){var pOverlay=pPanel.overlays[overlayId];var spOverlay=spPanel.overlays[overlayId];if(spOverlay){pOverlay.id=spOverlay.id;pOverlay.panelId=spOverlay.panelId;}}
for(var separatorId in pPanel.separators){var pSeparator=pPanel.separators[separatorId];var spSeparator=spPanel.separators[separatorId];if(spSeparator){pSeparator.id=spSeparator.id;pSeparator.panelId=spSeparator.panelId;}}
for(var layoutTextboxId in pPanel.layoutTextboxes){var pLayoutTextbox=pPanel.layoutTextboxes[layoutTextboxId];var spLayoutTextbox=spPanel.layoutTextboxes[layoutTextboxId];if(spLayoutTextbox){pLayoutTextbox.id=spLayoutTextbox.id;pLayoutTextbox.panelId=spLayoutTextbox.panelId;}}
for(var layoutPhotosId in pPanel.layoutPhotos){var pLayoutPhoto=pPanel.layoutPhotos[layoutPhotosId];var spLayoutPhoto=spPanel.layoutPhotos[layoutPhotosId];if(spLayoutPhoto){pLayoutPhoto.id=spLayoutPhoto.id;pLayoutPhoto.panelId=spLayoutPhoto.panelId;}}
for(var layoutOverlayId in pPanel.layoutOverlays){var pLayoutOverlay=pPanel.layoutOverlays[layoutOverlayId];var spLayoutOverlay=spPanel.layoutOverlays[layoutOverlayId];if(spLayoutOverlay){pLayoutOverlay.id=spLayoutOverlay.id;pLayoutOverlay.panelId=spLayoutOverlay.panelId;}}}}}}
if(typeof callback==='function'){callback();}}.bind(this),onFailure:function(){},onException:function(transport,exception){}});},loadPersonalization:function(personalizationId,options){new Ajax.Request('/personalization/'+personalizationId,{method:'get',onSuccess:function(transport){var savedPersonalization=transport.responseJSON;if(savedPersonalization){try{Personalize.personalization.loadJSON(savedPersonalization);}catch(e){}
Personalize.product.color=Personalize.product.colors[Personalize.personalization.productColorId];for(var panelId in Personalize.personalization.panels){var panel=Personalize.personalization.panels[panelId];for(var layoutTextboxId in panel.layoutTextboxes){var layoutTextbox=panel.layoutTextboxes[layoutTextboxId];var myLayoutId=Personalize.personalization.panels[panelId].layoutId;if(myLayoutId){for(var groupId in Personalize.product.templates.groups){var group=Personalize.product.templates.groups[groupId];for(var templateId in group.templates){var template=group.templates[templateId];for(var layoutId in template.layouts){if(layoutId==myLayoutId){try{var layout=template.layouts[layoutId];var textboxes=layout.textboxes;var productLayoutTextbox=textboxes[layoutTextboxId];layoutTextbox.styleClassId=productLayoutTextbox.styleClassId;}catch(e){}}}}}}}
for(var textboxId in panel.textboxes){var textbox=panel.textboxes[textboxId];var productPanel=Personalize.product.panels[panelId];var productTextbox=productPanel.textboxes[textboxId];textbox.styleClassId=this.createStyleClass(panel.panelId,productTextbox.fonts,productTextbox.colors,productTextbox.fontSizes);}}
this.getP13nStep().loadPersonalizationTemplateCodeValues();this.getP13nStep().init();}
if(options){if(typeof options.onSuccess==='function'){options.onSuccess();}
if(typeof options.onComplete==='function'){options.onComplete();}}}.bind(this),onFailure:function(){if(options){if(typeof options.onFailure==='function'){options.onFailure();}
if(typeof options.onComplete==='function'){options.onComplete();}}},onException:function(transport,exception){if(options){if(typeof options.onFailure==='function'){options.onFailure();}
if(typeof options.onComplete==='function'){options.onComplete();}}}});},createPersonalization:function(){var product=Personalize.product;var p13n=new Personalization();p13n.productId=product.id;p13n.productColorId=product.color.id;p13n.quantity=Personalize.quantity;p13n.priceAtQuantity=Personalize.priceAtQuantity;p13n.returnAddressFront=Personalize.product.returnAddressFront;p13n.paperId=product.paperId;var requestVars=this.getUrlVars();function secretCMYKDecoderAKAEnigmaMachine(val){val-=42;val=(val<0)?101+val:val;return val;}
if(typeof requestVars['c']!=='undefined')p13n.colorCyan=secretCMYKDecoderAKAEnigmaMachine(requestVars['c']);if(typeof requestVars['m']!=='undefined')p13n.colorMagenta=secretCMYKDecoderAKAEnigmaMachine(requestVars['m']);if(typeof requestVars['y']!=='undefined')p13n.colorYellow=secretCMYKDecoderAKAEnigmaMachine(requestVars['y']);if(typeof requestVars['k']!=='undefined')p13n.colorBlack=secretCMYKDecoderAKAEnigmaMachine(requestVars['k']);p13n.panels={};for(var productPanelId in product.panels){var productPanel=product.panels[productPanelId];var panel=new Panel();panel.panelId=productPanel.id;panel.textboxes={};for(var textboxIndex in productPanel.textboxes){var productTextbox=productPanel.textboxes[textboxIndex];var textbox=new Textbox();textbox.textboxId=productTextbox.id;textbox.typeId=productTextbox.typeId;textbox.name=productTextbox.name;textbox.content=productTextbox.content;textbox.x=productTextbox.x;textbox.y=productTextbox.y;textbox.width=productTextbox.width;textbox.height=productTextbox.height;textbox.controlX=productTextbox.controlX;textbox.controlY=productTextbox.controlY;textbox.controlWidth=productTextbox.controlWidth;textbox.controlHeight=productTextbox.controlHeight;textbox.z=productTextbox.z;textbox.leading=productTextbox.leading;textbox.tracking=productTextbox.tracking;textbox.stroke=productTextbox.stroke;textbox.horizontalAlignmentId=productTextbox.horizontalAlignmentId;textbox.verticalAlignmentId=productTextbox.verticalAlignmentId;textbox.angle=productTextbox.angle;textbox.styleClassId=this.createStyleClass(panel.panelId,productTextbox.fonts,productTextbox.colors,productTextbox.fontSizes);var firstFontId=null;for(var i in productTextbox.fonts){var font=productTextbox.fonts[i];if(!firstFontId){firstFontId=font.fontId;}
if(parseFloat(font['default'])===1){textbox.fontId=font.fontId;}}
if(!textbox.fontId&&firstFontId){textbox.fontId=firstFontId;}
var firstFontSize=null;for(var i in productTextbox.fontSizes){var fontSize=productTextbox.fontSizes[i];if(!firstFontSize){firstFontSize=fontSize.fontSize;}
if(parseFloat(fontSize['default'])===1){textbox.fontSize=fontSize.fontSize;}}
if(!textbox.fontSize&&firstFontSize){textbox.fontSize=firstFontSize;}
var firstFontColorId=null;for(var i in productTextbox.fontColors){var fontColor=productTextbox.fontColors[i];if(!firstFontColorId){firstFontColorId=fontColor.fontColorId;}
if(parseFloat(fontColor['default'])===1){textbox.fontColorId=fontColor.fontColorId;}}
if(!textbox.fontColorId&&firstFontColorId){textbox.fontColorId=firstFontColorId;}
panel.textboxes[textboxIndex]=textbox;}
panel.photos={};for(var photoIndex in productPanel.photos){var productPhoto=productPanel.photos[photoIndex];var photo=new Photo();photo.photoId=productPhoto.id;photo.x=productPhoto.x;photo.y=productPhoto.y;photo.width=productPhoto.width;photo.height=productPhoto.height;photo.z=productPhoto.z;photo.minimumWidth=productPhoto.minimumWidth;photo.minimumHeight=productPhoto.minimumHeight;photo.recommendedWidth=productPhoto.recommendedWidth;photo.recommendedHeight=productPhoto.recommendedHeight;photo.frameWidth=productPhoto.frameWidth;photo.frameStyle=productPhoto.frameStyle;photo.frameColorId=productPhoto.color.frameColorId;photo.overlayImageId=productPhoto.color.overlayImageId;panel.photos[photoIndex]=photo;}
panel.overlays={};for(var overlayIndex in productPanel.overlays){var productOverlay=productPanel.overlays[overlayIndex];var overlay=new Overlay();overlay.overlayId=productOverlay.id;overlay.x=productOverlay.x;overlay.y=productOverlay.y;overlay.width=productOverlay.width;overlay.height=productOverlay.height;overlay.z=productOverlay.z;overlay.imageId=productOverlay.color.imageId;panel.overlays[overlayIndex]=overlay;}
panel.separators={};for(var separatorIndex in productPanel.separators){var productSeparator=productPanel.separators[separatorIndex];var separator=new Separator();separator.separatorId=productSeparator.id;separator.x=productSeparator.x;separator.y=productSeparator.y;separator.width=productSeparator.width;separator.height=productSeparator.height;panel.separators[separatorIndex]=separator;}
panel.designAreas={};for(var designAreaIndex in productPanel.designAreas){var productDesignArea=productPanel.designArea[designAreaIndex];var designArea=new DesignArea();designArea.designAreaId=productDesignArea.id;designArea.x=productDesignArea.x;designArea.y=productDesignArea.y;designArea.width=productDesignArea.width;designArea.height=productDesignArea.height;designArea.alignmentId=productDesignArea.alignmentId;designArea.horizontalDistributionId=productDesignArea.horizontalDistributionId;designArea.verticalDistributionId=productDesignArea.verticalDistributionId;panel.designAreas[designAreaIndex]=designArea;}
panel.doodles={};p13n.panels[productPanelId]=panel;}
return p13n;},addLayoutTextbox:function(panel,layoutTextbox){var textbox=new Textbox();textbox.textboxId=layoutTextbox.id;textbox.typeId=layoutTextbox.typeId;textbox.name=layoutTextbox.name;textbox.content=layoutTextbox.content;textbox.x=layoutTextbox.x;textbox.y=layoutTextbox.y;textbox.width=layoutTextbox.width;textbox.height=layoutTextbox.height;textbox.controlX=layoutTextbox.controlX;textbox.controlY=layoutTextbox.controlY;textbox.controlWidth=layoutTextbox.controlWidth;textbox.controlHeight=layoutTextbox.controlHeight;textbox.z=layoutTextbox.z;textbox.leading=layoutTextbox.leading;textbox.tracking=layoutTextbox.tracking;textbox.stroke=layoutTextbox.stroke;textbox.horizontalAlignmentId=layoutTextbox.horizontalAlignmentId;textbox.verticalAlignmentId=layoutTextbox.verticalAlignmentId;textbox.angle=layoutTextbox.angle;textbox.styleClassId=layoutTextbox.styleClassId;textbox.defaultCasingId=layoutTextbox.defaultCasingId;var firstFontId=null;for(var i in layoutTextbox.fonts){var font=layoutTextbox.fonts[i];if(!firstFontId){firstFontId=font.fontId;}
if(parseFloat(font['default'])===1){textbox.fontId=font.fontId;}}
if(!textbox.fontId&&firstFontId){textbox.fontId=firstFontId;}
var firstFontSize=null;for(var i in layoutTextbox.fontSizes){var fontSize=layoutTextbox.fontSizes[i];if(!firstFontSize){firstFontSize=fontSize.fontSize;}
if(parseFloat(fontSize['default'])===1){textbox.fontSize=fontSize.fontSize;}}
if(!textbox.fontSize&&firstFontSize){textbox.fontSize=firstFontSize;}
var firstFontColorId=null;for(var i in layoutTextbox.fontColors){var fontColor=layoutTextbox.fontColors[i];if(!firstFontColorId){firstFontColorId=fontColor.fontColorId;}
if(parseFloat(fontColor['default'])===1){textbox.fontColorId=fontColor.fontColorId;}}
if(!textbox.fontColorId&&firstFontColorId){textbox.fontColorId=firstFontColorId;}
if(typeof panel.layoutTextboxes==='undefined')panel.layoutTextboxes=new Object();panel.layoutTextboxes[textbox.textboxId]=textbox;},createStyleClass:function(panelId,fontStyles,fontColors,fontSizes){var maxId=0;for(styleClassId in Personalize.product.styleClasses){if(parseInt(styleClassId)>parseInt(maxId)){maxId=styleClassId;}}
maxId++;Personalize.product.styleClasses[maxId]=new Object();Personalize.product.styleClasses[maxId].panelId=panelId;Personalize.product.styleClasses[maxId].style=new Object;Personalize.product.styleClasses[maxId].style.fonts=fontStyles;Personalize.product.styleClasses[maxId].style.fontColors=new Object();Personalize.product.styleClasses[maxId].style.fontColors=fontColors;Personalize.product.styleClasses[maxId].style.fontSizes=fontSizes;Personalize.product.styleClasses[maxId].styleId=null;Personalize.product.styleClasses[maxId].styleClassId=maxId;return maxId;},getTextboxUrl:function(textbox){var textboxImageUrl=Personalize.hosts.images+'personalize/textbox';for(var key in textbox){textboxImageUrl+='/'+key+'/'+parameters[key];}
textboxImageUrl+='.png';return textboxImageUrl;},getPhotoUrl:function(photo){},personalizeVarFormat:function(variable,data){},populateTextFromTemplate:function(callback){var productTextboxContents={};for(var panelIndex in Personalize.personalization.panels){var panel=Personalize.personalization.panels[panelIndex];var productPanel=Personalize.product.panels[panel.panelId];for(var textboxIndex in panel.textboxes){var textbox=panel.textboxes[textboxIndex];var productTextbox=productPanel.textboxes[textbox.textboxId];try{productTextboxContents[textbox.textboxId]=productTextbox.content;}catch(e){productTextboxContents[textbox.textboxId]='';}}
for(var textboxIndex in panel.layoutTextboxes){var textbox=panel.layoutTextboxes[textboxIndex];try{var productTextbox=productPanel.templateLayouts[Personalize.steps[1].getSelectedVerse()].textboxes[textbox.textboxId];productTextboxContents[textbox.textboxId]=productTextbox.content;}catch(e){productTextboxContents[textbox.textboxId]='';}}}
var templateConditionalCodes={};var p13nStep=this.getP13nStep();var templateConditionals=p13nStep.getTemplateConditionals();var templateVariables=p13nStep.getTemplateVariables();var templateCodeValues=p13nStep.getTemplateCodeValues();for(var templateConditionalId in templateConditionals){var templateConditional=templateConditionals[templateConditionalId];var templateConditionalVariable=templateVariables[templateConditional.variableId];var templateConditionalValue=null;for(templateConditionalValueId in templateConditional.values){templateConditionalValue=templateConditional.values[templateConditionalValueId];break;}
if(templateConditionalValue){var comparisonValue=(templateConditionalValue.comparison=='BLANK'||templateConditionalValue.comparison=='0'||templateConditionalValue.comparison=='')?'':templateConditionalValue.comparison;var templateCodeValue=templateCodeValues[templateConditionalVariable.code]||null;var notEqual=(parseFloat(templateConditionalValue.notEqual)===1)?true:false;var templateCodeValueString='';switch(parseFloat(templateCodeValue.type)){case Personalize.VARIABLE_TYPE_TEXT:case Personalize.VARIABLE_TYPE_TEXTBOX:templateCodeValueString=templateCodeValue.text||'';break;case Personalize.VARIABLE_TYPE_NAME:templateCodeValueString=templateCodeValue.name||'';break;case Personalize.VARIABLE_TYPE_AGE:templateCodeValueString=templateCodeValue.age||'';break;case Personalize.VARIABLE_TYPE_DATE:templateCodeValueString=(templateCodeValue.year||'')+(templateCodeValue.month||'')+(templateCodeValue.date||'');break;case Personalize.VARIABLE_TYPE_TIME:templateCodeValueString=(templateCodeValue.hour||'')+(templateCodeValue.minute||'')+(templateCodeValue.second||'');break;case Personalize.VARIABLE_TYPE_WEIGHT:templateCodeValueString=(templateCodeValue.weightMajor||'')+(templateCodeValue.weightMajorUnit||'')+(templateCodeValue.weightMinor||'')+(templateCodeValue.weightMinorUnit||'');break;case Personalize.VARIABLE_TYPE_LENGTH:templateCodeValueString=(templateCodeValue.length||'')+(templateCodeValue.unit||'');break;}
if((!notEqual&&comparisonValue==templateCodeValueString)||((notEqual&&comparisonValue!=templateCodeValueString))){templateConditionalCodes[templateConditional.code]=templateConditionalValue.value;}else{templateConditionalCodes[templateConditional.code]='';}}}
for(productTextboxId in productTextboxContents){var productTextboxContent=productTextboxContents[productTextboxId];for(var templateConditionalCode in templateConditionalCodes){var templateConditionalCodeValue=templateConditionalCodes[templateConditionalCode];productTextboxContents[productTextboxId]=productTextboxContents[productTextboxId].replace(templateConditionalCode,templateConditionalCodeValue);}
for(var templateConditionalCode in templateConditionalCodes){var templateConditionalCodeValue=templateConditionalCodes[templateConditionalCode];productTextboxContents[productTextboxId]=productTextboxContents[productTextboxId].replace(templateConditionalCode,templateConditionalCodeValue);}}
var formatRequestsData=[];var formatRequests=[];var templateVariablesRegex=/_([^_]+)_(?:\{([^}]+)\})?/g;var templateVariableRegex=/_([^_]+)_(?:\{([^}]+)\})?/;for(var panelIndex in Personalize.personalization.panels){var panel=Personalize.personalization.panels[panelIndex];var productPanel=Personalize.product.panels[panel.panelId];for(var textboxIndex in panel.textboxes){var textbox=panel.textboxes[textboxIndex];var productTextbox=productPanel.textboxes[textbox.textboxId];var productTextboxContent=productTextboxContents[textbox.textboxId];var templateVariableMatches=productTextboxContent.match(templateVariablesRegex);if(templateVariableMatches){for(var i=0;i<templateVariableMatches.length;i++){var templateVariableMatch=templateVariableRegex.exec(templateVariableMatches[i]);var code='_'+templateVariableMatch[1]+'_'||null;var format=templateVariableMatch[2]||null;var codeValue=(typeof templateCodeValues[code]!=='undefined')?templateCodeValues[code]:{};var formatRequest=TP.extendObject({},codeValue);formatRequest.format=format;formatRequestsData.push({code:code,format:format});formatRequests.push(formatRequest);}}}
for(var layoutTextboxIndex in panel.layoutTextboxes){try{var textbox=panel.layoutTextboxes[layoutTextboxIndex];var productTextbox=productPanel.templateLayouts[Personalize.steps[1].getSelectedVerse()].textboxes[textbox.textboxId];var productTextboxContent=productTextboxContents[textbox.textboxId];var templateVariableMatches=productTextboxContent.match(templateVariablesRegex);if(templateVariableMatches){for(var i=0;i<templateVariableMatches.length;i++){var templateVariableMatch=templateVariableRegex.exec(templateVariableMatches[i]);var code='_'+templateVariableMatch[1]+'_'||null;var format=templateVariableMatch[2]||null;var codeValue=(typeof templateCodeValues[code]!=='undefined')?templateCodeValues[code]:{};var formatRequest=TP.extendObject({},codeValue);formatRequest.format=format;formatRequestsData.push({code:code,format:format});formatRequests.push(formatRequest);}}}catch(e){}}}
var requestJsonString=JSON.stringify(formatRequests);new Ajax.Request('/personalize/format.json',{parameters:{requests:requestJsonString},onSuccess:function(transport){var responses=transport.responseJSON;for(var panelIndex in Personalize.personalization.panels){var panel=Personalize.personalization.panels[panelIndex];var productPanel=Personalize.product.panels[panel.panelId];for(var textboxIndex in panel.textboxes){var textbox=panel.textboxes[textboxIndex];var productTextbox=productPanel.textboxes[textbox.textboxId];var productTextboxContent=productTextboxContents[textbox.textboxId];textbox.content=productTextboxContent;}}
var variableCodeResponses={};for(var i=0;i<formatRequestsData.length;i++){var formatRequestData=formatRequestsData[i];var responseValue=(typeof responses[i]!=='undefined'&&typeof responses[i].string!=='undefined')?responses[i].string:'';if(typeof variableCodeResponses[formatRequestData.code]==='undefined'){variableCodeResponses[formatRequestData.code]={};}
variableCodeResponses[formatRequestData.code][formatRequestData.format]=responseValue;}
for(var panelIndex in Personalize.personalization.panels){var panel=Personalize.personalization.panels[panelIndex];for(var textboxIndex in panel.textboxes){var textbox=panel.textboxes[textboxIndex];var templateVariableMatches=textbox.content.match(templateVariablesRegex);if(templateVariableMatches){for(var i=0;i<templateVariableMatches.length;i++){var templateVariableMatch=templateVariableRegex.exec(templateVariableMatches[i]);var templateVariableCode='_'+templateVariableMatch[1]+'_';var templateVariableFormat=templateVariableMatch[2]||null;try{textbox.content=textbox.content.replace(templateVariableMatch[0],(typeof variableCodeResponses[templateVariableCode][templateVariableFormat]!=='undefined')?variableCodeResponses[templateVariableCode][templateVariableFormat]:'');}catch(e){}}}}
for(var textboxIndex in panel.layoutTextboxes){var textbox=panel.layoutTextboxes[textboxIndex];var templateVariableMatches=textbox.content.match(templateVariablesRegex);if(templateVariableMatches){for(var i=0;i<templateVariableMatches.length;i++){var templateVariableMatch=templateVariableRegex.exec(templateVariableMatches[i]);var templateVariableCode='_'+templateVariableMatch[1]+'_';var templateVariableFormat=templateVariableMatch[2]||null;try{textbox.content=textbox.content.replace(templateVariableMatch[0],(typeof variableCodeResponses[templateVariableCode][templateVariableFormat]!=='undefined')?variableCodeResponses[templateVariableCode][templateVariableFormat]:'');}catch(e){}}}}}
for(var panelIndex in Personalize.personalization.panels){var panel=Personalize.personalization.panels[panelIndex];var productPanel=Personalize.product.panels[panel.panelId];for(var textboxIndex in panel.textboxes){var textbox=panel.textboxes[textboxIndex];var productTextbox=productPanel.textboxes[textbox.textboxId];textbox.content=Personalize.services.applyCasing(textbox.content,productTextbox.defaultCasingId);}}
for(var panelIndex in Personalize.personalization.panels){var panel=Personalize.personalization.panels[panelIndex];var productPanel=Personalize.product.panels[panel.panelId];for(var textboxIndex in panel.layoutTextboxes){var textbox=panel.layoutTextboxes[textboxIndex];textbox.content=Personalize.services.applyCasing(textbox.content,textbox.defaultCasingId);}}
if(typeof callback==='function'){callback();}},onFailure:function(){},onException:function(transport,exception){}});},applyCasing:function(text,casingId){switch(parseFloat(casingId)){case 1:text=text.toUpperCase();break;case 2:text=text.toLowerCase();break;case 3:text=text.replace(/(\b)([a-z])/g,function(str,p1,p2){return p1+p2.toUpperCase();});break;case 4:for(var i=0;i<text.length;i++){var character=text.charAt(i);if(/\w/.test(character)){text=character.toUpperCase()+text.substring(i+1);break;}}
break;}
return text;},saveSessionPersonalization:function(){var sessionPersonalization={};sessionPersonalization.productId=Personalize.personalization.productId;sessionPersonalization.productColorId=Personalize.personalization.productColorId;sessionPersonalization.panels={};if(typeof Personalize.personalization.panels!=='undefined'){for(var panelId in Personalize.personalization.panels){var panel=Personalize.personalization.panels[panelId];var sessionPanel={};sessionPanel.textboxes={};if(typeof panel.textboxes!=='undefined'){for(var textboxId in panel.textboxes){var textbox=panel.textboxes[textboxId];sessionPanel.textboxes[textboxId]={fontId:textbox.fontId,fontColorId:textbox.fontColorId,fontSize:textbox.fontSize};}}
sessionPanel.photos={};if(typeof panel.photos!=='undefined'){for(var photoId in panel.photos){var photo=panel.photos[photoId];sessionPanel.photos[photoId]={contentPhotoId:photo.contentPhotoId,cropX:photo.cropX,cropY:photo.cropY,cropWidth:photo.cropWidth,cropHeight:photo.cropHeight,rotation:photo.rotation,effectId:photo.effectId,zoom:photo.zoom};}}
sessionPersonalization.panels[panelId]=sessionPanel;}}
var sessionPersonalizations=[];var cookieSessionPersonalizations=TP.getCookie('sessionPersonalizations');if(cookieSessionPersonalizations){var sessionPersonalizations=JSON.parse(JSON.parse(decodeURIComponent(cookieSessionPersonalizations)));}
for(var i=0;i<sessionPersonalizations.length;i++){if(sessionPersonalizations[i].productId==sessionPersonalization.productId){delete sessionPersonalizations[i];}}
sessionPersonalizations.push(sessionPersonalization);var sessionPersonalizationsJsonString=encodeURIComponent(JSON.stringify(sessionPersonalizations));while(sessionPersonalizationsJsonString.length>2048){sessionPersonalizations.shift();sessionPersonalizationsJsonString=encodeURIComponent(JSON.stringify(sessionPersonalizations));}
TP.setCookie('sessionPersonalizations',sessionPersonalizationsJsonString);},loadSessionPersonalization:function(){var sessionPersonalizations=TP.getCookie('sessionPersonalizations');if(sessionPersonalizations){var parsedSessionPersonalizations=JSON.parse(JSON.parse(decodeURIComponent(sessionPersonalizations)));for(var i=(parsedSessionPersonalizations.length-1);i>=0;i--){var parsedSessionPersonalization=parsedSessionPersonalizations[i];if(parsedSessionPersonalization.productId==Personalize.personalization.productId&&parsedSessionPersonalization.productColorId==Personalize.personalization.productColorId&&typeof parsedSessionPersonalization.panels!=='undefined'){for(var panelId in parsedSessionPersonalization.panels){var panel=parsedSessionPersonalization.panels[panelId];if(typeof Personalize.personalization.panels[panelId]!=='undefined'){if(typeof panel.textboxes!=='undefined'){for(var textboxId in panel.textboxes){if(typeof Personalize.personalization.panels[panelId].textboxes[textboxId]!=='undefined'){TP.extendObject(Personalize.personalization.panels[panelId].textboxes[textboxId],panel.textboxes[textboxId]);}}}
if(typeof panel.photos!=='undefined'){for(var photoId in panel.photos){if(typeof Personalize.personalization.panels[panelId].photos[photoId]!=='undefined'){TP.extendObject(Personalize.personalization.panels[panelId].photos[photoId],panel.photos[photoId]);}}}}}}}}},getUrlVars:function(){var vars=[],hash;var variables=window.location.href.slice(window.location.href.indexOf('?')+1);if(window.location.href.indexOf('#')>0)variables=variables.slice(0,window.location.href.indexOf('#'));var hashes=variables.split('&');for(var i=0;i<hashes.length;i++){hash=hashes[i].split('=');vars.push(hash[0]);vars[hash[0]]=hash[1];}
return vars;},getP13nStep:function(){var step=Personalize.getStepByName('Personalize');return step;}};

var personalizeVerseSelect=new Step('verseStep','Select Verse');TP.extendObject(personalizeVerseSelect,{selectedGroup:null,selectedTemplate:null,openContainer:null,selectedVerse:null,templateSelectElement:null,templateTree:{},verseSelectElement:null,groupTemplateContainers:[],associatedTemplateLayouts:[],associatedTemplates:[],selectedGroup:null,sampleImageId:null,minVerseShown:3,init:function(){this.name='personalizeVerseSelect';this.description='Start customizing your wedding invitations by selecting the type of host and overall style of your upcoming ceremony.';if(!this.findFirstTemplateLayoutPanel()){this.available=false;return;}
this.available=true;this.templateSelectElementId=this.element.id+"_selectTemplate";this.verseSelectElementId=this.element.id+"_selectVerse";this.verseSelectBoxId=this.element.id+"_verseSelectBox";this.sampleImageContainer=$(this.element.id+"_sampleImageContainer");this.zoomBtn=$('verseStep_zoomBtn');this.recentViewsContainer=$("verseStep_seeMore");this.createTemplateSelection();this.createVerseList();if(this.zoomBtn){this.zoomBtn.observe('click',this.showZoom.bind(this));$('verseStep_zoomBtn_sprite').observe('click',this.showZoom.bind(this));;}
if(this.recentViewsContainer){this.recentViewsContainer.observe('click',this.showRecentViews.bind(this));}},activate:function(){$(this.element.id).show();$('saveButton').hide();},deactivate:function(){$(this.element.id).hide();return true;},next:function(){if(!this.selectedVerse){this.showNoVerseSelectError();return false;}
this.selectedGroup=this.selectedTreeObj.group;this.selectedTemplate=this.selectedTreeObj.template;if(Personalize.personalization.id){delete Personalize.personalization;Personalize.personalization=Personalize.services.createPersonalization();}
Personalize.personalization.panels[this.findFirstTemplateLayoutPanel()].layoutId=this.selectedVerse;return true;},selectVerse:function(layoutId){this.setSelectedVerse(layoutId);Personalize.next();},setSelectedVerse:function(id){this.sampleImageId=(typeof Personalize.product.templates.groups[this.selectedGroup].templates[this.selectedTemplate]!=='undefined')?Personalize.product.templates.groups[this.selectedGroup].templates[this.selectedTemplate].layouts[id].sampleImageId:Personalize.product.templates.groups[this.chosenGroup].templates[this.selectedTemplate].layouts[id].sampleImageId;if(this.sampleImageId){this.setSampleImage(this.sampleImageId);}
this.selectedVerse=id;this.removeWarningMsg();this.selectedTreeObj=function(g,t,v){return{group:g,template:t,verse:v};}(this.selectedGroup,this.selectedTemplate,this.selectedVerse);},getSampleImageId:function(){return this.sampleImageId;},setSampleImage:function(id){this.showLoadingBox();var imgElem=new Image();imgElem.onload=this.hideLoadingBox.bindAsEventListener(this,imgElem);imgElem.src=Personalize.hosts.images+'/image/product/'+id+'/width/450/height/450/shadow/1.jpg';},showLoadingBox:function(){this.loadingBoxElem=new Element('div',{style:"padding-top:8px;background-color:#FFF; width: 250px; height: 60px; border:1px solid #E0E0E0; position: absolute; top: 100px; left: 100px;"});var img=new Element('img',{src:Personalize.hosts['static']+'image/wpd/loading-bar.gif'});this.loadingBoxElem.insert(img);var text=new Element('div',{'style':'font-family:Helvetica; font-size: 12px; color: #3992B4'}).update('Updating Preview Image..');;this.loadingBoxElem.insert(text);this.sampleImageContainer.insert(this.loadingBoxElem);},hideLoadingBox:function(ev,imgElem){try{this.loadingBoxElem.remove();this.sampleImageContainer.update('');this.sampleImageContainer.insert(imgElem);}catch(e){}},getSelectedVerse:function(){return this.selectedVerse;},findFirstTemplateLayoutPanel:function(){for(var i in Personalize.product.panels){var panel=Personalize.product.panels[i];for(var j in panel.templateLayouts){return i;}}
return false;},createVersePreview:function(layoutTextboxes,panelTextboxes){var textboxes=[];var ignoreList=new Object;for(panelTextboxId in panelTextboxes){panelTextbox=panelTextboxes[panelTextboxId];if(panelTextbox.layoutTextboxId){if(layoutTextboxes[panelTextbox.layoutTextboxId]){ignoreList[panelTextbox.layoutTextboxId]=true;textboxes.push(panelTextbox);}}else{textboxes.push(panelTextbox);}}
for(layoutTextboxId in layoutTextboxes){if(ignoreList[layoutTextboxId])continue;textboxes.push(layoutTextboxes[layoutTextboxId]);}
textboxes.sort(function(a,b){if(parseFloat(a.y)<parseFloat(b.y)){return-1;}else if(parseFloat(a.y)>parseFloat(b.y)){return 1;}else if(parseFloat(a.x)<parseFloat(b.x)){return-1;}else if(parseFloat(a.x)>parseFloat(b.x)){return 1;}
return 0;});var result='';var text='';for(var i=0;i<textboxes.length;i++){text=textboxes[i].content;for(var find in Personalize.product.templateFormattedSampleCodeValues[this.selectedTemplate]){var replace=Personalize.product.templateFormattedSampleCodeValues[this.selectedTemplate][find];text=text.replace(find,replace);}
text=Personalize.services.applyCasing(text,textboxes[i].defaultCasingId);result+=text+'<br><br>';}
result=result.replace(/\n/g,'<br />');return result;},createVerseList:function(){if(!this.selectedGroup||!this.selectedTemplate){$(this.verseSelectBoxId).hide();return;}
$(this.verseSelectBoxId).show();var group=Personalize.product.templates.groups[this.selectedGroup];var template=group.templates[this.selectedTemplate];var globalVerseContainer=new Element('div');var layoutCount=0;var tabOrder=200;for(var templateLayoutId in template.layouts){var layout=this.layoutPanel.templateLayouts[templateLayoutId];if(typeof layout!=='undefined'){var elementId='radio_layoutId_'+templateLayoutId;var container=new Element('div',{id:'verse_container_layoutId_'+templateLayoutId});var titleContainer=new Element('div');if(++layoutCount>this.minVerseShown){container.hide();}
var radioBtnContainer=new Element('div',{style:'float: right; line-height: 22px'});var radioBtnLabel=new Element('label',{'for':elementId}).update('select this option');radioBtnContainer.insert(radioBtnLabel);var radioBtn=new Element('input',{tabindex:tabOrder++,type:'radio',id:elementId,'class':'radio-layout',value:templateLayoutId,name:'layoutGroup',style:'line-height: 22px'});radioBtn.stepHandle=this;radioBtnContainer.insert(radioBtn);titleContainer.insert(radioBtnContainer);var title=new Element('div').update(layout.layout.displayName);var description=new Element('div').update(layout.layout.description);container.layoutId=templateLayoutId;container.stepHandle=this;container.radio=radioBtn;var displayText=this.createVersePreview(layout.textboxes,this.layoutPanel.textboxes);var text=new Element('div').update(displayText);titleContainer.insert(title);titleContainer.insert(description);container.insert(titleContainer);container.insert(new Element('div',{style:'clear:both'}));container.insert(text);container.addClassName('verseContainer');title.addClassName("verseTitle");description.addClassName("verseDescription");titleContainer.addClassName('verseTitleContainer');text.addClassName('verseText');Event.observe(container,'mouseover',function(ev){this.addClassName('verseContainerOver');this.removeClassName('verseContainer');});Event.observe(container,'mouseout',function(ev){this.removeClassName('verseContainerOver');this.addClassName('verseContainer');});Event.observe(container,'click',function(ev,el){this.setSelectedVerse(el.layoutId);el.radio.checked=true;}.bindAsEventListener(this,container));globalVerseContainer.insert(container);}}
if(layoutCount>this.minVerseShown){globalVerseContainer.insert(new Element('div',{style:'height: 1px; width: 100%; background-color: #e9e9e9;'}));var moreOption=new Element('a',{href:'#','class':'more-link'}).update('> more options');moreOption.clickHandle=this;Event.observe(moreOption,'click',function(ev){this.clickHandle.showMoreOptions()});globalVerseContainer.insert(new Element('div',{id:'moreOption',style:'text-align: right; width: 97%;'}).update(moreOption));}
if($(this.verseSelectElementId).firstDescendant()){new Effect.Fade($(this.verseSelectElementId).firstDescendant(),{duration:0.3,from:1,to:0,afterFinish:function(el){el.element.remove();globalVerseContainer.setOpacity(0);$(this.verseSelectElementId).insert({bottom:globalVerseContainer});new Effect.Fade(globalVerseContainer,{duration:0.3,from:0,to:1});}.bind(this)});}else{globalVerseContainer.setOpacity(0);$(this.verseSelectElementId).insert(globalVerseContainer);new Effect.Fade(globalVerseContainer,{duration:0.3,from:0,to:1});}},showMoreOptions:function(){var group=Personalize.product.templates.groups[this.selectedGroup];var template=group.templates[this.selectedTemplate];var layoutCount=0;for(var templateLayoutId in template.layouts){var layout=this.layoutPanel.templateLayouts[templateLayoutId];if(++layoutCount>this.minVerseShown){if(typeof layout!=='undefined'){new Effect.Parallel([new Effect.SlideDown($('verse_container_layoutId_'+templateLayoutId),{duration:0.3}),new Effect.Opacity($('verse_container_layoutId_'+templateLayoutId),{sync:true,from:0,to:1})],{duration:0.3});}}}
$('moreOption').hide();$('moreOption').previousSiblings()[0].hide();},createTemplateSelection:function(){this.layoutPanel=Personalize.product.panels[this.findFirstTemplateLayoutPanel()];var templateTree=this.templateTree;for(var groupId in Personalize.product.templates.groups){var group=Personalize.product.templates.groups[groupId];for(var templateId in group.templates){var groupTemplate=group.templates[templateId];for(var layoutId in this.layoutPanel.templateLayouts){if(typeof groupTemplate.layouts[layoutId]!=='undefined'){if(typeof templateTree[groupId]==='undefined'){templateTree[groupId]={};}
if(typeof templateTree[groupId][templateId]==='undefined'){templateTree[groupId][templateId]={};}
if(typeof templateTree[groupId][templateId]==='undefined'){templateTree[groupId][templateId][layoutId]=1;}else{templateTree[groupId][templateId][layoutId]+=1;}}}}}
var orderedGroups=[];var tabOrder=100;for(var i in templateTree){var treeGroup=templateTree[i];var group=Personalize.product.templates.groups[i];if(group.templates){var elementId=this.templateSelectElementId+"_group_"+group.id+"_radio";var templateContainerId=this.templateSelectElementId+"_group_"+group.id+"_radio_container";var groupRadio=new Element('input',{type:'radio',id:elementId,value:group.id,name:'templateGroup',style:'display: none'});var radioLabel=new Element('span',{'for':elementId,value:group.id,style:'color: #3992b4; font-weight: bold; cursor: pointer',tabindex:tabOrder++}).update(group.name);groupRadio.templateContainer=new Element('div',{id:templateContainerId,'class':'templateContainer',style:'display:none'});this.groupTemplateContainers[group.id]=groupRadio.templateContainer;groupRadio.templateContainerContainer=new Element('div');groupRadio.templateContainer.insert(groupRadio.templateContainerContainer);var indicator=new Element('div',{id:elementId+'_indicator','class':'sprite-icon-arrow-right clickable',style:'margin-left: 25px; margin-right: 4px; float: left'});$(this.templateSelectElementId).insert(indicator);$(this.templateSelectElementId).insert(groupRadio);$(this.templateSelectElementId).insert(radioLabel);$(this.templateSelectElementId).insert(new Element('div',{style:'clear:both'}));$(this.templateSelectElementId).insert(groupRadio.templateContainer);for(var i in treeGroup){template=group.templates[i];templateElementId=this.templateSelectElementId+"_group_"+group.id+"_template_"+template.id+"_radio";var templateRadio=new Element('input',{tabindex:tabOrder++,type:'radio',id:templateElementId,value:template.id,name:'group_'+group.id+'_template',style:'margin-left: 40px;'});var templateLabel=new Element('label',{'for':templateElementId}).update(template.name);groupRadio.templateContainerContainer.insert(templateRadio);groupRadio.templateContainerContainer.insert(templateLabel);groupRadio.templateContainerContainer.insert(new Element('div',{style:'clear:both'}))
templateRadio.observe('click',this.templateChange.bindAsEventListener(this,templateRadio));}
indicator.observe('click',this.templateGroupChange.bindAsEventListener(this,groupRadio));radioLabel.observe('click',this.templateGroupChange.bindAsEventListener(this,groupRadio));}}},templateGroupChange:function(event,clickedRadio){if(this.openContainer){if(this.openContainer==clickedRadio.templateContainer)return;new Effect.Parallel([new Effect.SlideUp(this.openContainer,{duration:0.3}),new Effect.Opacity(this.openContainer,{sync:true,from:1,to:0})],{duration:0.3});}
this.chosenGroup=this.selectedGroup;this.selectedGroup=clickedRadio.value;this.setTemplateGroup(this.selectedGroup);},setGroupSelectionIndicator:function(){var indicatorId=this.templateSelectElementId+"_group_"+this.getTemplateGroup()+"_radio"+"_indicator";var indicatorArr=$(this.templateSelectElementId).getElementsByClassName('sprite-icon-arrow-down');for(var i=0;i<indicatorArr.length;i++){indicatorArr[i].className='sprite-icon-arrow-right clickable';}
if(typeof $(indicatorId)!=='undefined'){$(indicatorId).className='sprite-icon-arrow-down clickable';}},setTemplateGroup:function(groupId){var templateContainer=this.groupTemplateContainers[this.selectedGroup];this.setGroupSelectionIndicator();new Effect.Parallel([new Effect.SlideDown(templateContainer,{duration:0.3}),new Effect.Opacity(templateContainer,{sync:true,from:0,to:1})],{duration:0.3});this.openContainer=templateContainer;this.openContainer.select('input:checked').each(function(el){this.templateChange(null,el)}.bind(this));},getTemplateGroup:function(){return this.selectedGroup;},getTemplateGroupList:function(){var list={};for(var i in this.templateTree){var group=Personalize.product.templates.groups[i];list[i]=group.name;}
return list;},templateChange:function(event,clickedRadio){this.setTemplate(clickedRadio.value);},setTemplate:function(templateId){if(this.selectedTemplate!=templateId){this.selectedTemplate=templateId;this.createVerseList();this.removeWarningMsg();}},getTemplateList:function(groupId){var list={};var group=Personalize.product.templates.groups[groupId];for(var i in this.templateTree[groupId]){list[i]=group.templates[i].name;}
return list;},getTemplate:function(){return this.selectedTemplate;},getVerseList:function(groupId,templateId){var list={};var group=Personalize.product.templates.groups[groupId];var template=group.templates[templateId];for(var templateLayoutId in template.layouts){var layout=this.layoutPanel.templateLayouts[templateLayoutId];list[templateLayoutId]=layout.layout.displayName;}
return list;},showZoom:function(){if(this.getSampleImageId()){var uri=Personalize.hosts.images+'image/product/'+this.getSampleImageId()+'/width/740/height/560/shadow/1.jpg';}else{var uri=Personalize.hosts.images+'product/'+Personalize.product.id+'/panel/1/color/'+Personalize.product.color.number+'/width/740/height/560/1.jpg';}
this.zoomBox=new PersonalizeZoomBox("Zoomed Image",uri);this.zoomBox.showZoom();},showRecentViews:function(){if(!this.recentViewsDlg){this.recentViewsDlg=new PersonalizePopup('Recently Viewed','enterInfoZoom');}
var content=this.recentViewsDlg.getPopupElement();content.setStyle({width:'870px',height:'400px',overflow:'hidden'});var list=$('verse_recentlyViewedContainerList_Popup');content.update(list.show());this.recentViewsDlg.showPopup();},showNoVerseSelectError:function(){if(!this.selectedTemplate){var msg="Please select a host and a verse style before moving on to the next step.";var containerDom=$('templateSelectBox').select('div[class="wpdBoxContent"]')[0];}else{var msg="Please select a verse style before moving on to the next step.";var containerDom=$(this.verseSelectBoxId).select('div[class="wpdBoxContent"]')[0];}
this.removeWarningMsg();this.addWarningMsg(containerDom,msg);},addWarningMsg:function(containerDom,msg){if(containerDom){var textErrorDom=new Element('div',{id:'textErrorDom','class':'textErrorWarning errorHilite',style:'height:35px'});var warningIcon=new Element('div',{'class':'sprite-icon-warning-small-red',style:'float:left;margin-right:8px'});var warningText=new Element('div',{'class':'textErrorWarningText',style:'margin-right:8px'}).update(msg);var warningBold=new Element('span',{style:'font-weight: bold'}).update("Warning: ");warningText.insert({'top':warningBold});textErrorDom.insert(warningIcon);textErrorDom.insert(warningText);containerDom.insert({'top':textErrorDom});}},removeWarningMsg:function(){if(this.selectedTemplate){var templateContainerDom=$('templateSelectBox').select('div[class="wpdBoxContent"]')[0];if(templateContainerDom&&$('textErrorDom')){$('textErrorDom').remove();}}
var containerDom=$(this.verseSelectBoxId).select('div[class="wpdBoxContent"]')[0];if(containerDom&&$('textErrorDom')){$('textErrorDom').remove();}}});

var personalizeEnterInfo=new Step('enterInfo','Enter Info');TP.extendObject(personalizeEnterInfo,{selectedGroupId:null,selectedTemplateId:null,selectedVerseId:null,groupList:null,wizard:null,wizardStepTabsDomId:'enterInfo_enterInfo',activeWizardStepId:null,templateVariables:null,templateConditionals:null,templateCodeValues:{},init:function(){this.name='personalizeEnterInfo';this.description='Enter the details you would like included on your invitations. You can also click "Edit" to go back and make a change to either the host or style of your ceremony.';this.available=true;this.verseBoxElementId=this.element.id+"_verseBox";this.templateSelectElementId=this.element.id+"_templateAccess";this.verseSelectElementId=this.element.id+"_verseAccess";this.enterInfoElementId=this.element.id+"_enterInfo";this.sampleImageElementId="enterInfo_sampleImageContainer";this.zoomBtn=$('enterInfoStep_zoomBtn');if(this.zoomBtn){this.zoomBtn.observe('click',this.showZoom.bind(this));$('enterInfoStep_zoomBtn_sprite').observe('click',this.showZoom.bind(this));}
this.requiredVariables=[];this.verseStep=Personalize.getStepByName('personalizeVerseSelect');if(!this.verseStep){$(this.verseBoxElementId).hide();this.description='Enter the details you would like included on your invitations.';}
$('enterInfoStepNumber').update('1');this.recentViewsContainer=$("enterInfoStep_seeMore");if(this.recentViewsContainer){this.recentViewsContainer.observe('click',this.showRecentViews.bind(this));}
Personalize.calendars={};this.loadCookieTemplateCodeValues();},activate:function(){if(this.verseStep){if(!this.verseStep.getSelectedVerse()){Personalize.back();return;}}
$(this.element.id).show();this.selectedGroupId=this.getTemplateGroupSelection();this.selectedTemplateId=this.getTemplateSelection();if(typeof Personalize.product.template==='undefined'){if(this.selectedGroupId&&this.selectedTemplateId){var template=Personalize.product.templates.groups[this.selectedGroupId].templates[this.selectedTemplateId]
if(template.templateConditionals&&template.templateVariables){this.templateConditionals=template.templateConditionals;this.templateVariables=template.templateVariables;}}}else{this.templateConditionals=Personalize.product.template.templateConditionals;this.templateVariables=Personalize.product.template.templateVariables;}
this.showEnterInfoBox();this.renderCurrentSelections();if(this.verseStep){$(this.sampleImageElementId).update(new Element('img',{src:Personalize.hosts.images+'image/product/'+this.getSampleImageId()+'/width/450/height/450/shadow/1.jpg'}));}else{$(this.sampleImageElementId).update(new Element('img',{src:Personalize.hosts.images+'product/'+Personalize.product.id+'/panel/1/color/'+Personalize.product.color.number+'/width/450/height/450.jpg'}));}
$('saveButton').hide();},deactivate:function(){$(this.element.id).hide();try{this.next();}catch(e){}
return true;},next:function(){if(this.activeWizardStepId){var wizardStepIdToActivate=null;var activateNextWizardStep=false;for(var i in this.wizard.steps){var currentStep=this.wizard.steps[i];if(activateNextWizardStep){wizardStepIdToActivate=currentStep.id;break;}else if(currentStep.id==this.activeWizardStepId){activateNextWizardStep=true;}}
if(wizardStepIdToActivate){this.deactivateWizardStep(this.activeWizardStepId);this.activateWizardStep(wizardStepIdToActivate);Personalize.writeButtons(true,true);return false;}}
this.loadTemplateCodeValuesFromForm();if(!Personalize.personalization.id){this.setCookieTemplateCodeValues();}
return true;},setCookieTemplateCodeValues:function(){var cookieValue=encodeURIComponent(JSON.stringify(this.templateCodeValues));if(cookieValue.length<=1536){TP.setCookie('templateCodeValues',cookieValue);}},loadCookieTemplateCodeValues:function(){var cookieTemplateCodeValues=TP.getCookie('templateCodeValues');if(cookieTemplateCodeValues){try{var parsedCookie=JSON.parse(decodeURIComponent(cookieTemplateCodeValues));}catch(e){}
if(parsedCookie){this.templateCodeValues=parsedCookie;}}},loadPersonalizationTemplateCodeValues:function(){if(Personalize.personalization.id){var templateCodeValues={};for(var i in Personalize.personalization.templateCodeValues){try{templateCodeValues[i]=JSON.parse(Personalize.personalization.templateCodeValues[i]);}catch(e){}}
this.templateCodeValues=templateCodeValues;this.updateFormWithTemplateCodeValues();}},layoutTextboxesToPersonalization:function(){if(!this.verseStep)return;var textboxes=Personalize.product.templates.groups[this.selectedGroupId].templates[this.selectedTemplateId].layouts[this.verseStep.getSelectedVerse()].textboxes;for(var panelId in Personalize.personalization.panels){var panel=Personalize.personalization.panels[panelId];panel.layoutTextboxes={};}
for(panelId in Personalize.product.panels){var panel=Personalize.product.panels[panelId];for(layoutId in panel.templateLayouts){if(layoutId==this.verseStep.getSelectedVerse()){for(var textboxId in textboxes){Personalize.services.addLayoutTextbox(Personalize.personalization.panels[panelId],textboxes[textboxId]);}
return true;}}}
return false;},showEnterInfoBox:function(){this.renderWizard();this.updateFormWithTemplateCodeValues();},showZoom:function(){if(this.getSampleImageId()){var uri=Personalize.hosts.images+'image/product/'+this.getSampleImageId()+'/width/740/height/560/shadow/1.jpg';}else{var uri=Personalize.hosts.images+'product/'+Personalize.product.id+'/panel/1/color/'+Personalize.product.color.number+'/width/740/height/560.jpg';}
this.zoomBox=new PersonalizeZoomBox("Zoomed Image",uri);this.zoomBox.showZoom();},getTemplateGroupList:function(){if(!this.verseStep)return false;return this.verseStep.getTemplateGroupList();},getTemplateGroupSelection:function(){if(!this.verseStep)return false;return this.verseStep.getTemplateGroup();},setTemplateGroupSelection:function(groupId){if(!this.verseStep)return false;this.verseStep.setTemplateGroup(groupId);},getTemplateSelection:function(){if(!this.verseStep)return false;return this.verseStep.getTemplate();},setTemplateSelection:function(templateId){if(!this.verseStep)return false;this.verseStep.setTemplate(templateId);},getTemplateList:function(groupId){if(!this.verseStep)return false;return this.verseStep.getTemplateList(groupId);},getSampleImageId:function(){if(!this.verseStep)return false;return this.verseStep.getSampleImageId();},getVerseSelection:function(){if(!this.verseStep)return false;return this.verseStep.getSelectedVerse();},getVerseList:function(selectedGroupId,selectedTemplateId){if(!this.verseStep)return false;return this.verseStep.getVerseList(selectedGroupId,selectedTemplateId);},getWizard:function(){if(typeof Personalize.product.templates!=='undefined'&&this.selectedGroupId&&this.selectedTemplateId){this.wizard=Personalize.product.templates.groups[this.selectedGroupId].templates[this.selectedTemplateId].wizard;}else if(Personalize.product.templateId){this.wizard=Personalize.product.template.wizard;}else{this.wizard=null;}
return this.wizard;},getWizardStepTabDomId:function(stepId){return'wizardStepTab_'+stepId;},getWizardStepDomId:function(stepId){return'wizardStep_'+stepId;},renderCurrentSelections:function(){if(!this.verseStep)return false;if(this.selectedTemplateId){var groupDom=$(this.templateSelectElementId).firstDescendant();groupDom.update(Personalize.product.templates.groups[this.selectedGroupId].name);var templateDom=groupDom.next();templateDom.update(Personalize.product.templates.groups[this.selectedGroupId].templates[this.selectedTemplateId].name);var verseDom=$(this.verseSelectElementId).firstDescendant();verseDom.update(Personalize.product.templates.groups[this.selectedGroupId].templates[this.selectedTemplateId].layouts[this.verseStep.getSelectedVerse()].displayName);}else if(Personalize.product.templateId){$(this.verseBoxElementId).hide();}},renderWizard:function(){var wizard=this.getWizard();if(!wizard){return;}
var container=$(this.wizardStepTabsDomId);container.update(new Element('div',{'class':"instruction"}).update('Enter the details you would like to include on your '+Personalize.product.categoryName.toLowerCase()+'. We will use your information to generate an online preview of your personalized design'));for(var stepId in wizard.steps){var step=wizard.steps[stepId];var newTab=new Element('div',{id:"wizardStep_"+step.id,style:'clear: both;'});Element.insert(container,newTab);var tabOrder=1100;for(var elementId in step.elements){var element=step.elements[elementId];var requiredElements=element.required==1?true:false;if(typeof element.question!=='undefined'){}else if(typeof element.variable!=='undefined'){var currentVariable=element.variable;var currentVariableCode=currentVariable.code;var namespace="wizardStepVariable_"+currentVariable.id.toString();newTab.insert(new Element('input',{id:namespace+"_code",name:namespace+"_code",type:'hidden',value:currentVariableCode}));newTab.insert(new Element('input',{id:namespace+"_type",name:namespace+"_type",type:'hidden',value:currentVariable.type}));if(currentVariable.type==Personalize.VARIABLE_TYPE_TEXT||currentVariable.type==Personalize.VARIABLE_TYPE_NAME||currentVariable.type==Personalize.VARIABLE_TYPE_AGE){newTab.insert(new Element('div',{'class':"enterInfoLabel",style:"float:left; clear: left"}).update(currentVariable.name));if(requiredElements){newTab.insert(new Element('span',{'class':"required",style:"float:left"}).update("*"));}
newTab.insert((new Element('div',{'class':"enterInfofield",style:"clear:both"})).insert(new Element('input',{tabindex:tabOrder++,id:namespace,name:namespace,onkeyup:"enterKeyNext(event)"})));if(currentVariable.help){newTab.insert(new Element('div',{'class':"enterInfoHelp"}).update(currentVariable.help));}}else if(currentVariable.type==Personalize.VARIABLE_TYPE_TEXTBOX){newTab.insert(new Element('div',{'class':"enterInfoLabel",style:"float:left; clear: left"}).update(currentVariable.name));if(requiredElements){newTab.insert(new Element('span',{'class':"required",style:"float:left"}).update("*"));}
newTab.insert((new Element('div',{'class':"enterInfofield",style:"clear:both; margin-left:10px"})).insert(new Element('textarea',{tabindex:tabOrder++,id:namespace,name:namespace,rows:8,cols:35})));if(currentVariable.help){newTab.insert(new Element('div',{'class':"enterInfoHelp"}).update(currentVariable.help));}}else if(currentVariable.type==Personalize.VARIABLE_TYPE_DATE){newTab.insert(new Element('div',{'class':"enterInfoLabel",style:"float:left; clear: left"}).update(currentVariable.name));if(requiredElements){newTab.insert(new Element('span',{'class':"required",style:"float:left"}).update("*"));}
var enterInfofield=new Element('div',{'class':"enterInfofield",style:"clear:both"});newTab.insert(enterInfofield);var monthSelect=new Element('select',{tabindex:tabOrder++,id:namespace+"_month",name:namespace+"_month",onchange:"updateDateStringField('"+namespace+"');",style:"float: left; margin-left: 10px"});enterInfofield.insert(monthSelect);monthSelect.insert(new Element('option',{value:''}).update('month'));var months=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];for(var i=1;i<13;i++){monthSelect.insert(new Element('option',{value:i}).update(months[i-1]));}
enterInfofield.insert(new Element('span',{style:'float: left; margin-left:4px'}).update("&nbsp;"));var daySelect=new Element('select',{tabindex:tabOrder++,id:namespace+"_date",name:namespace+"_date",onchange:"updateDateStringField('"+namespace+"');",style:"float: left"})
enterInfofield.insert(daySelect);daySelect.insert(new Element('option',{value:''}).update('day'));for(var i=1;i<32;i++){daySelect.insert(new Element('option',{value:i}).update(i));}
enterInfofield.insert(new Element('span',{style:'float: left; margin-left:4px'}).update("&nbsp;"));var yearSelect=new Element('select',{tabindex:tabOrder++,id:namespace+"_year",name:namespace+"_year",onchange:"updateDateStringField('"+namespace+"');",style:"float: left"});enterInfofield.insert(yearSelect);yearSelect.insert(new Element('option',{value:''}).update('year'));var d=new Date();var curYear=d.getFullYear();for(var i=(curYear-1);i<(curYear+8);i++){yearSelect.insert(new Element('option',{value:i}).update(i));}
enterInfofield.insert(new Element('span',{style:'float: left; margin-left:4px'}).update("&nbsp;"));enterInfofield.insert(new Element('span',{tabindex:tabOrder++,id:namespace+"_calendarButton",'class':"sprite-btn-calendar",style:"float:left; margin-left: 5px; margin-top: 5px; cursor: pointer;"}));enterInfofield.insert(new Element('input',{id:namespace+"_dateString",name:namespace+"_dateString",type:"hidden"}));var calendarNamespace=new String(namespace);var fnNs={calendarNamespace:namespace};calendarDateStatusFunc=function(date){return checkDate(this.calendarNamespace,date);};calendarOnUpdate=function(){updateDateInputs(this.calendarNamespace);};Personalize.calendars[calendarNamespace]=Calendar.setup({inputField:calendarNamespace+"_dateString",ifFormat:"%Y-%m-%d",button:calendarNamespace+"_calendarButton",weekNumbers:false,dateStatusFunc:calendarDateStatusFunc.bind(fnNs),onUpdate:calendarOnUpdate.bind(fnNs)});if(currentVariable.help){newTab.insert(new Element('div',{'class':"enterInfoHelp",style:"clear:both"}).update(currentVariable.help));}
newTab.insert(new Element('div',{style:"clear:both; height: 1px"}));}else if(currentVariable.type==Personalize.VARIABLE_TYPE_TIME){newTab.insert(new Element('div',{'class':"enterInfoLabel",style:"float:left; clear: left"}).update(currentVariable.name));if(requiredElements){newTab.insert(new Element('span',{'class':"required",style:"float:left"}).update("*"));}
var enterInfofield=new Element('div',{'class':"enterInfofield",style:"clear:both"});newTab.insert(enterInfofield);var hourSelect=new Element('select',{tabindex:tabOrder++,id:namespace+"_hour",name:namespace+"_hour",style:"margin-left: 10px"});enterInfofield.insert(hourSelect);hourSelect.insert(new Element('option',{value:''}).update('hour'));for(var i=1;i<13;i++){hourSelect.insert(new Element('option',{value:i}).update(i));}
enterInfofield.insert(new Element('span',{style:'margin-left:4px; margin-right:4px'}).update(":"));var minuteSelect=new Element('select',{tabindex:tabOrder++,id:namespace+"_minute",name:namespace+"_minute"});enterInfofield.insert(minuteSelect);minuteSelect.insert(new Element('option',{value:''}).update('minute'));for(var i=0;i<60;i++){minuteSelect.insert(new Element('option',{value:i}).update(i<=9?"0"+i:i));}
enterInfofield.insert(new Element('span',{style:'margin-left:4px'}).update("&nbsp;"));var meridiemSelect=new Element('select',{tabindex:tabOrder++,id:namespace+"_meridiem",name:namespace+"_meridiem"});enterInfofield.insert(meridiemSelect);meridiemSelect.insert(new Element('option',{value:'am'}).update('am'));meridiemSelect.insert(new Element('option',{value:'pm'}).update('pm'));if(currentVariable.help){newTab.insert(new Element('div',{'class':"enterInfoHelp"}).update(currentVariable.help));}
newTab.insert(new Element('div',{style:"clear:both; height: 1px"}));}else if(currentVariable.type==Personalize.VARIABLE_TYPE_WEIGHT){}else if(currentVariable.type==Personalize.VARIABLE_TYPE_LENGTH){}}}}},updateFormWithTemplateCodeValues:function(){var wizard=this.getWizard();if(!wizard){return;}
for(var stepIndex in wizard.steps){var step=wizard.steps[stepIndex];for(var elementIndex in step.elements){var element=step.elements[elementIndex];if(element.question){var question=element.question;var questionCode=question.code;var questionDomPrefix='wizardStepQuestion_'+variable.id;var questionCodeValue=this.templateCodeValues[questionCode];}else if(element.variable){var variable=element.variable;var variableCode=variable.code;var variableDomPrefix='wizardStepVariable_'+variable.id;var variableCodeValue=this.templateCodeValues[variableCode];switch(parseFloat(variable.type)){case Personalize.VARIABLE_TYPE_TEXT:case Personalize.VARIABLE_TYPE_TEXTBOX:var codeField=document.getElementById(variableDomPrefix+'_code');var code=codeField.value;var codeValue=this.templateCodeValues[code];if(codeValue){var textField=document.getElementById(variableDomPrefix);textField.value=codeValue.text;}
break;case Personalize.VARIABLE_TYPE_NAME:var codeField=document.getElementById(variableDomPrefix+'_code');var code=codeField.value;var codeValue=this.templateCodeValues[code];if(codeValue){var nameField=document.getElementById(variableDomPrefix);nameField.value=codeValue.name;}
break;case Personalize.VARIABLE_TYPE_AGE:var codeField=document.getElementById(variableDomPrefix+'_code');var code=codeField.value;var codeValue=this.templateCodeValues[code];if(codeValue){var ageField=document.getElementById(variableDomPrefix);ageField.value=codeValue.age;}
break;case Personalize.VARIABLE_TYPE_DATE:var codeField=document.getElementById(variableDomPrefix+'_code');var code=codeField.value;var codeValue=this.templateCodeValues[code];if(codeValue){var monthSelect=document.getElementById(variableDomPrefix+'_month');var dateSelect=document.getElementById(variableDomPrefix+'_date');var yearSelect=document.getElementById(variableDomPrefix+'_year');for(var i=0;i<yearSelect.options.length;i++){var currentYearOption=yearSelect.options[i];if(parseFloat(currentYearOption.value)==parseFloat(codeValue.year)){yearSelect.selectedIndex=i;break;}}
for(var i=0;i<monthSelect.options.length;i++){var currentMonthOption=monthSelect.options[i];if(parseFloat(currentMonthOption.value)==parseFloat(codeValue.month)){monthSelect.selectedIndex=i;break;}}
for(var i=0;i<dateSelect.options.length;i++){var currentDayOption=dateSelect.options[i];if(parseFloat(currentDayOption.value)==parseFloat(codeValue.date)){dateSelect.selectedIndex=i;break;}}
if(typeof yearSelect.onchange==='function'){yearSelect.onchange();}}
break;case Personalize.VARIABLE_TYPE_TIME:var codeField=document.getElementById(variableDomPrefix+'_code');var code=codeField.value;var codeValue=this.templateCodeValues[code];if(codeValue){var hourSelect=document.getElementById(variableDomPrefix+'_hour');var minuteSelect=document.getElementById(variableDomPrefix+'_minute');var meridiemSelect=document.getElementById(variableDomPrefix+'_meridiem');var hour=parseFloat(codeValue.hour);var minute=parseFloat(codeValue.minute);if(hour==12){var meridiem='pm';}else if(hour>12){hour-=12;var meridiem='pm';}else{var meridiem='am';}
if(hour==0){hour=12;}
for(var i=0;i<hourSelect.options.length;i++){var currentHourOption=hourSelect.options[i];if(parseFloat(currentHourOption.value)==hour){hourSelect.selectedIndex=i;break;}}
for(var i=0;i<minuteSelect.options.length;i++){var currentMinuteOption=minuteSelect.options[i];if(parseFloat(currentMinuteOption.value)==minute){minuteSelect.selectedIndex=i;break;}}
for(var i=0;i<meridiemSelect.options.length;i++){var currentMeridiemOption=meridiemSelect.options[i];if(currentMeridiemOption.value.toLowerCase()==meridiem){meridiemSelect.selectedIndex=i;break;}}}
break;case Personalize.VARIABLE_TYPE_WEIGHT:var codeField=document.getElementById(variableDomPrefix+'_code');var code=codeField.value;var codeValue=this.templateCodeValues[code];if(codeValue){var majorField=document.getElementById(variableDomPrefix+'_major');var majorUnitSelect=document.getElementById(variableDomPrefix+'_majorUnit');var minorField=document.getElementById(variableDomPrefix+'_minor');var minorUnitSelect=document.getElementById(variableDomPrefix+'_minorUnit');majorField.value=codeValue.weightMajor;minorField.value=codeValue.weightMinor;var majorUnit=codeValue.weightMajorUnit.toLowerCase();var minorUnit=codeValue.weightMinorUnit.toLowerCase();for(var i=0;i<majorUnitSelect.options.length;i++){var currentMajorUnitOption=majorUnitSelect.options[i];if(currentMajorUnitOption.value.toLowerCase()==majorUnit){majorUnitSelect.selectedIndex=i;break;}}
for(var i=0;i<minorUnitSelect.options.length;i++){var currentMinorUnitOption=minorUnitSelect.options[i];if(currentMinorUnitOption.value.toLowerCase()==minorUnit){minorUnitSelect.selectedIndex=i;break;}}}
break;case Personalize.VARIABLE_TYPE_LENGTH:try{var codeField=document.getElementById(variableDomPrefix+'_code');var code=codeField.value;var lengthField=document.getElementById(variableDomPrefix+'_length');var unitSelect=document.getElementById(variableDomPrefix+'_unit');var codeValue=this.templateCodeValues[code];if(codeValue){var unit=codeValue.unit.toLowerCase();lengthField.value=codeValue.length;for(var i=0;i<unitSelect.options.length;i++){var currentUnitOption=unitSelect.options[i];if(currentUnitOption.value.toLowerCase()==unit){unitSelect.selectedIndex=i;break;}}}
break;}catch(e){}}}}}},loadTemplateCodeValuesFromForm:function(){var wizard=this.getWizard();for(var stepIndex in wizard.steps){var step=this.wizard.steps[stepIndex];for(var elementIndex in step.elements){var element=step.elements[elementIndex];if(element.question){var question=element.question;var questionCode=question.code;var questionDomPrefix='wizardStepQuestion_'+variable.id;var questionCodeValue=this.templateCodeValues[questionCode];}else if(element.variable){var variable=element.variable;var variableCode=variable.code;var variableDomPrefix='wizardStepVariable_'+variable.id;var variableCodeValue=this.templateCodeValues[variableCode];switch(parseFloat(variable.type)){case Personalize.VARIABLE_TYPE_TEXT:case Personalize.VARIABLE_TYPE_TEXTBOX:var codeField=document.getElementById(variableDomPrefix+'_code');var typeField=document.getElementById(variableDomPrefix+'_type');var textField=document.getElementById(variableDomPrefix);var code=codeField.value;var type=typeField.value;var text=textField.value;this.templateCodeValues[code]={text:text,type:type};break;case Personalize.VARIABLE_TYPE_NAME:var codeField=document.getElementById(variableDomPrefix+'_code');var typeField=document.getElementById(variableDomPrefix+'_type');var nameField=document.getElementById(variableDomPrefix);var code=codeField.value;var type=typeField.value;var name=nameField.value;this.templateCodeValues[code]={name:name,type:type};break;case Personalize.VARIABLE_TYPE_AGE:var codeField=document.getElementById(variableDomPrefix+'_code');var typeField=document.getElementById(variableDomPrefix+'_type');var ageField=document.getElementById(variableDomPrefix);var code=codeField.value;var type=typeField.value;var age=ageField.value;this.templateCodeValues[code]={age:age,type:type};break;case Personalize.VARIABLE_TYPE_DATE:var codeField=document.getElementById(variableDomPrefix+'_code');var typeField=document.getElementById(variableDomPrefix+'_type');var monthSelect=document.getElementById(variableDomPrefix+'_month');var dateSelect=document.getElementById(variableDomPrefix+'_date');var yearSelect=document.getElementById(variableDomPrefix+'_year');var code=codeField.value;var type=typeField.value;var month=monthSelect.options[monthSelect.selectedIndex].value;var date=dateSelect.options[dateSelect.selectedIndex].value;var year=yearSelect.options[yearSelect.selectedIndex].value;this.templateCodeValues[code]={year:year,month:month,date:date,type:type};break;case Personalize.VARIABLE_TYPE_TIME:var codeField=document.getElementById(variableDomPrefix+'_code');var typeField=document.getElementById(variableDomPrefix+'_type');var hourSelect=document.getElementById(variableDomPrefix+'_hour');var minuteSelect=document.getElementById(variableDomPrefix+'_minute');var meridiemSelect=document.getElementById(variableDomPrefix+'_meridiem');var code=codeField.value;var type=typeField.value;var hour=parseFloat(hourSelect.options[hourSelect.selectedIndex].value);var minute=parseFloat(minuteSelect.options[minuteSelect.selectedIndex].value);var meridiem=meridiemSelect.options[meridiemSelect.selectedIndex].value.toLowerCase();if(meridiem=='pm'){if(hour!=12){hour+=12;}}else{if(hour==12){hour='0';}}
this.templateCodeValues[code]={hour:hour,minute:minute,second:0,type:type};break;case Personalize.VARIABLE_TYPE_WEIGHT:var codeField=document.getElementById(variableDomPrefix+'_code');var typeField=document.getElementById(variableDomPrefix+'_type');var majorField=document.getElementById(variableDomPrefix+'_major');var majorUnitSelect=document.getElementById(variableDomPrefix+'_majorUnit');var minorField=document.getElementById(variableDomPrefix+'_minor');var minorUnitSelect=document.getElementById(variableDomPrefix+'_minorUnit');var code=codeField.value;var type=typeField.value;var majorValue=majorField.value;var majorUnitValue=majorUnitSelect.options[majorUnitSelect.selectedIndex].value;var minorValue=minorField.value;var minorUnitValue=minorUnitSelect.options[minorUnitSelect.selectedIndex].value;this.templateCodeValues[code]={weightMajor:majorValue,weightMajorUnit:majorUnitValue,weightMinor:minorValue,weightMinorUnit:minorUnitValue,type:type};break;case Personalize.VARIABLE_TYPE_LENGTH:var codeField=document.getElementById(variableDomPrefix+'_code');var typeField=document.getElementById(variableDomPrefix+'_type');var lengthField=document.getElementById(variableDomPrefix+'_length');var unitSelect=document.getElementById(variableDomPrefix+'_unit');var code=codeField.value;var type=typeField.value;if(lengthField)var lengthValue=lengthField.value;if(unitSelect)var unitValue=unitSelect.options[unitSelect.selectedIndex].value;this.templateCodeValues[code]={length:lengthValue,unit:unitValue,type:type};break;}}}}},showRecentViews:function(){if(!this.recentViewsDlg){this.recentViewsDlg=new PersonalizePopup('Recently Viewed','enterInfoZoom');}
var content=this.recentViewsDlg.getPopupElement();content.setStyle({width:'870px',height:'400px',overflow:'hidden'});var list=$('enterInfo_recentlyViewedContainerList_Popup');content.update(list.show());this.recentViewsDlg.showPopup();}});

var personalizePersonalize=new Step('personalizeStep','Personalize');TP.extendObject(personalizePersonalize,{init:function(){this.styleEditors=[];this.name='Personalize';this.description='Personalize your card by editing the text, font or color options to make your perfect card.  <br /><b>Please keep in mind that this is only a preview.</b> A professional designer will adjust for layout, sizing, and spacing and send you a proof for approval before any printing begins.';this.textboxEditors=[];this.photos=[];this.overlays=[];this.textboxes=[];this.separators=[];this.available=true;this.currentPanel=null;this.styleEditorElementId=this.element.id+'_textStyles';this.textEditorElementId=this.element.id+'_textBoxes';this.imageViewElementId=this.element.id+'_imageView';this.verseStep=Personalize.getStepByName('personalizeVerseSelect');this.photoTrayElementId=this.element.id+'_photoTray';this.panelSwitcherElementId=this.element.id+'_panelSwitcher';this.colorSwitcherElementId=this.element.id+'_colorSwitcher';this.editorInformationElementId=this.element.id+'_editorInfo';this.resolution=0;this.imageScaling=0;this.maxPreviewWidth=550;this.maxPreviewHeight=500;if(Personalize.ie6)this.maxPreviewWidth=549;this.panelSwitcher=new PersonalizePanelSwitcher();this.colorSwitcher=new PersonalizeColorSwitcher();this.panelSwitcher.clickCallback=this.changePanel.bind(this);this.colorSwitcher.clickCallback=this.changeColor.bind(this);this.photoTray=new PersonalizePhotoTray();this.photoTray.requestPhotos();this.photoUploader=new PersonalizePhotoUploader();this.panelNameElement=$('panelNameElement');this.error=false;this.saveDialog=null;this.photoTrayRendered=false;this.rendered=false;this.errorViewer=$('personalizeErrorViewer');this.errorViewer.hide();this.specialInstructions=$('personalizeSpecialInstructions');this.specialInstructions.observe('change',this.saveSpecialInstructions.bind(this));this.tabIndex=3000;},getTemplateCodeValues:function(){return Personalize.getStepByName('personalizeEnterInfo').templateCodeValues;},loadPersonalizationTemplateCodeValues:function(){Personalize.getStepByName('personalizeEnterInfo').loadPersonalizationTemplateCodeValues();},getTemplateConditionals:function(){return Personalize.getStepByName('personalizeEnterInfo').templateConditionals;},getTemplateVariables:function(){return Personalize.getStepByName('personalizeEnterInfo').templateVariables;},save:function(){if(this.saveDialog){this.saveDialog.destroy();this.saveDialog=null;}
if(!this.saveDialog){this.saveDialog=new PersonalizePopup('Save Project','saveProject');var content=this.saveDialog.getPopupElement();content.setStyle({padding:'12px',textAlign:'left',width:'320px',fontSize:'12px',fontFamily:'Helvetica'});var currentInputElement=null;var textelem=new Element('input',{type:'text',style:'width:200px; border: 1px solid #d9d9d9'});var textElemId=textelem.identify();if(Personalize.personalization.id){currentInputElement=new Element('input',{type:'radio',name:'saveTo',id:'saveToExisting'});this.saveDialog.currentInputElement=currentInputElement;setTimeout(function(){currentInputElement.checked=true;},1);var currentLabelElement=new Element('label',{"for":'saveToExisting'}).update('Save changes to current project:<br /><div style="padding-left: 25px;">'+Personalize.getProjectDisplayName()+'</div>');var newInputElement=new Element('input',{type:'radio',name:'saveTo',id:'saveToNew',value:'1'});newInputElement.onchange=function(){if(this.checked){$(textElemId).focus();}else{$(textElemId).blur();}};var newLabelElement=new Element('label',{"for":'saveToNew'}).update('Save changes as a new project:');textelem.onfocus=function(){if(!$('saveToNew').checked){$('saveToNew').checked=true;}};content.update(currentInputElement);content.insert(currentLabelElement);content.insert(new Element('div',{style:'clear:both'}));content.insert(newInputElement);content.insert(newLabelElement);content.insert('<br />');}else{content.insert(new Element('div',{style:'font-family: Helvetica; font-size:12px; margin:10px;'}).update('What would you like to name your project?'));}
content.insert(textelem);var apply=new Element('div',{'class':'projectSave cmdApply clickable',style:'float:right; margin-left:8px;margin-bottom:10px;'}).update('<div class="sprite-btn-accept"></div>');apply.onclick=this.doSave.bindAsEventListener(this,textelem,currentInputElement);this.saveDialog.apply=apply;var cancel=new Element('div',{'class':'projectSave cmdCancel clickable',style:'float:right;margin-bottom:10px;'}).update('<div class="sprite-btn-cancel"></div>');cancel.onclick=this.cancelSave.bind(this);buttoncont=new Element('div',{style:'padding:6px;margin-top:8px;margin-bottom:10px;'});buttoncont.insert(apply);buttoncont.insert(cancel);content.insert(new Element('div',{style:'clear:both'}));content.insert(buttoncont);}
this.saveDialog.showPopup();return true;},doSave:function(ev,elem,createNewElem){var createNew=(createNewElem!=null)?!createNewElem.checked:true;Personalize.personalization.primaryProxy.project=1;if(createNew){var name=elem.getValue();if(name.length==0){alert('Please enter a name');return;}}else{var name=Personalize.getProjectDisplayName();}
elem.replace(new Element('img',{src:Personalize.hosts['static']+'image/wpd/loading-bar.gif'}));if(!Personalize.member){this.login(true,name);return;}else{Personalize.services.savePersonalization(name,this.saveComplete.bind(this),createNew);}},cancelSave:function(){if(this.saveDialog)
this.saveDialog.hidePopup();},login:function(showSave,title){Personalize.services.savePersonalization(title,function(){var savedUrl='personalize/'+Personalize.product.id+Personalize.product.color.number+'/'+Personalize.product.displayName.replace('/ /g','-')+'/saved/'+Personalize.personalization.primaryProxy.id+'.html'+((showSave)?'?saveLogin=1':'');var loginUrl='/signin.php?ref='+encodeURIComponent(savedUrl);window.location=loginUrl;});},saveComplete:function(){Personalize.setStepUrl();var content=this.saveDialog.getPopupElement();content.update('');content.insert(new Element('div',{style:'margin-bottom:25px;'}).update('Project "'+Personalize.getProjectDisplayName()+'" saved. <br>You can access your projects through <a href="/account.php">your account</a>.'));var accept=new Element('div',{'class':'sprite-btn_close clickable'});content.insert(new Element('div',{align:'right'}).update(accept));accept.observe('click',this.closeSavePopup.bind(this));if(this.dlgTimeout){clearTimeout(this.dlgTimeout);this.dlgTimeout=null;}
this.dlgTimeout=setTimeout(this.closeSavePopup.bind(this),10000);},closeSavePopup:function(){if(this.dlgTimeout){clearTimeout(this.dlgTimeout);this.dlgTimeout=null;}
this.saveDialog.hidePopup();this.saveDialog.destroy();this.saveDialog=null;},renderPanelSelect:function(){this.panelSwitcher.render($(this.panelSwitcherElementId));},renderColorSwitcher:function(){this.colorSwitcher.render($(this.colorSwitcherElementId));},renderEditPanel:function(){$(this.styleEditorElementId).update('');$(this.textEditorElementId).update('');if(!Personalize.ie6){$(this.styleEditorElementId).style.position='relative';$(this.textEditorElementId).style.position='relative';}
this.styleEditors.sort(function(a,b){return(parseFloat(a.styleClass.styleClassId)-parseFloat(b.styleClass.styleClassId));});this.textboxEditors.sort(function(a,b){var dY=(parseFloat(a.textbox.y)-parseFloat(b.textbox.y));if(dY!=0)return dY;var dX=(parseFloat(a.textbox.x)-parseFloat(b.textbox.x));return dX;});if(this.styleEditors.length==this.textboxEditors.length){$(this.editorInformationElementId).update('Click on the text areas of the card to open the text boxes below, or click directly into the boxes below to make changes');for(var i=0;i<this.styleEditors.length;i++){var textEditor=this.textboxEditors[i];var styleEditor=textEditor.myStyleEditor;styleEditor.title='Text Style '+(i+1);textEditor.title=textEditor.title+' '+(i+1);$(this.styleEditorElementId).insert(textEditor.render(styleEditor.render(true)));}}else{$(this.editorInformationElementId).update('Click directly into the boxes below to make changes. Please note that text styles match certain text boxes. Mouse over each text style to see the corresponding text areas on the card light up.');for(var i=0;i<this.styleEditors.length;i++){var editor=this.styleEditors[i];editor.title='Text Style '+(i+1);try{$(this.styleEditorElementId).insert(editor.render());}catch(e){}}
for(var i=0;i<this.textboxEditors.length;i++){try{var editor=this.textboxEditors[i];editor.title=editor.title+' '+(i+1);$(this.textEditorElementId).insert(editor.render());}catch(e){}}}},getPreviewImageInfo:function(){var productPanel=Personalize.product.panels[this.currentPanel.panelId];var previewImageInfo=productPanel.color.personalizeImage;var setByHeight=true;var newHeight=this.maxPreviewHeight;var imageScaling=newHeight/previewImageInfo.height;var newWidth=previewImageInfo.width*imageScaling;if(newWidth>this.maxPreviewWidth){setByHeight=false;newWidth=this.maxPreviewWidth;imageScaling=newWidth/previewImageInfo.width;newHeight=previewImageInfo.height*imageScaling;}
if(newWidth>previewImageInfo.width||newHeight>previewImageInfo.height){newWidth=previewImageInfo.width;newHeight=previewImageInfo.height;imageScaling=newWidth/newHeight;}
this.resolution=(previewImageInfo.resolution*newWidth)/previewImageInfo.width;if(setByHeight){var sizeString='/height/'+newHeight;var shadowSizeString='/height/'+(parseFloat(newHeight)+11);}else{var sizeString='/width/'+newWidth;var shadowSizeString='/width/'+(parseFloat(newWidth)+11);}
var personalizeImageUrl=Personalize.hosts.images+'product/'+Personalize.product.id+'/color/'+Personalize.product.color.number+'/panel/'+productPanel.number+'/type/personalize'+sizeString+'.png';var personalizeShadowUrl=Personalize.hosts.images+'product/'+Personalize.product.id+'/color/'+Personalize.product.color.number+'/panel/'+productPanel.number+'/type/shadow'+shadowSizeString+'.png';var result=new Object();;result.width=newWidth;result.height=newHeight;result.personalizeImageUrl=personalizeImageUrl;result.personalizeShadowUrl=personalizeShadowUrl;return result;},changePreviewImage:function(){var imageInfo=this.getPreviewImageInfo();var tmpImg=new Image();tmpImg.onload=this.previewImageLoaded.bindAsEventListener(this,imageInfo.personalizeImageUrl,tmpImg);tmpImg.src=imageInfo.personalizeImageUrl;},previewImageLoaded:function(ev,url,tmpImage){this.previewImageHandle.setStyle({background:'url('+url+')',backgroundRepeat:'no-repeat'});delete tmpImage;},renderPreviewPanel:function(){var previewPaneContainer=$(this.imageViewElementId);previewPaneContainer.setStyle({position:'relative'});var previewPane=new Element('div',{id:'personalizeImagePreviewPane',style:'position:absolute; top:4px; left:4px;'});previewPaneContainer.update(previewPane);var productPanel=Personalize.product.panels[this.currentPanel.panelId];var imageInfo=this.getPreviewImageInfo();previewPane.setStyle({width:imageInfo.width+'px',height:imageInfo.height+'px',position:'absolute',overflow:'hidden'});previewPaneContainer.setStyle({width:(parseFloat(imageInfo.width)+11)+'px',height:(parseFloat(imageInfo.height)+11)+'px',position:'relative',overflow:'hidden'});if(!(Personalize.product.isMintTin||parseFloat(productPanel.noShadow)==1)){previewPaneContainer.setStyle({background:'url('+imageInfo.personalizeShadowUrl+')',backgroundRepeat:'no-repeat'});}
previewPane.setStyle({background:'url('+imageInfo.personalizeImageUrl+')',backgroundRepeat:'no-repeat'});this.previewImageHandle=previewPane;for(var textboxId in this.currentPanel.textboxes){var textbox=this.currentPanel.textboxes[textboxId];var productTextbox=Personalize.product.panels[this.currentPanel.panelId].textboxes[textboxId];var panelId=this.currentPanel.panelId;if(panelId){var layoutId=Personalize.personalization.panels[this.currentPanel.panelId].layoutId;if(layoutId){try{var productLayoutTextboxes=Personalize.product.panels[panelId].templateLayouts[layoutId].textboxes;}catch(e){var productLayoutTextboxes=[];}}}
if(productTextbox.layoutTextboxId){if(productLayoutTextboxes[productTextbox.layoutTextboxId]){try{delete this.currentPanel.layoutTextboxes[productTextbox.layoutTextboxId];}catch(e){}}else{delete this.currentPanel.textboxes[textboxId];continue;}}
var panelTextbox=new PersonalizeTextbox(textbox,this.resolution);panelTextbox.findEditorAndAttach();panelTextbox.render(previewPane);this.textboxes.push(panelTextbox);}
for(var textboxId in this.currentPanel.layoutTextboxes){var textbox=this.currentPanel.layoutTextboxes[textboxId];var panelTextbox=new PersonalizeTextbox(textbox,this.resolution);panelTextbox.findEditorAndAttach();panelTextbox.render(previewPane);this.textboxes.push(panelTextbox);}
for(var photoId in this.currentPanel.photos){var photo=this.currentPanel.photos[photoId];var productPhoto=Personalize.product.panels[this.currentPanel.panelId].photos[photo.photoId];var panelPhoto=new PersonalizePhoto(photo,productPhoto,this.resolution);panelPhoto.render(previewPane);this.photos.push(panelPhoto);}
for(var overlayId in this.currentPanel.overlays){var overlay=this.currentPanel.overlays[overlayId];var panelOverlay=new PersonalizeOverlay(overlay,this.resolution);panelOverlay.render(previewPane);this.overlays.push(panelOverlay);}
for(var separatorId in this.currentPanel.separators){var separator=this.currentPanel.separators[separatorId];var panelSeparator=new PersonalizeSeparator(separator,this.resolution);panelSeparator.render(previewPane);this.separators.push(panelSeparator);}},renderPhotoTray:function(){if(!this.hasPhotos())return;if(this.photoTrayRendered)return;this.photoTrayRendered=true;var container=$(this.photoTrayElementId);this.photoTray.render(container);},getFirstPanel:function(){for(var i in Personalize.personalization.panels){var panel=Personalize.personalization.panels[i];return panel;if(panel.templateLayouts){}}
return false;},renderPhotoPreview:function(){},createEditors:function(){var requiringNormalization=[];var maxStyleClassId=0;var allTextboxes=[];var productPanel=Personalize.personalization.panels[this.currentPanel.panelId];for(var i in productPanel.textboxes){var textbox=productPanel.textboxes[i];var productTextbox=Personalize.product.panels[this.currentPanel.panelId].textboxes[textbox.textboxId];var panelId=this.currentPanel.panelId;if(panelId){var layoutId=Personalize.personalization.panels[this.currentPanel.panelId].layoutId;if(layoutId){try{var productLayoutTextboxes=Personalize.product.panels[panelId].templateLayouts[layoutId].textboxes;}catch(e){var productLayoutTextboxes=[];}}}
if(productTextbox.layoutTextboxId){if(productLayoutTextboxes[productTextbox.layoutTextboxId]){try{productPanel.layoutTextboxes[productTextbox.layoutTextboxId].disable=true;}catch(e){}
textbox.styleClassId=productTextbox.styleClassId;allTextboxes.push(textbox);}}else{allTextboxes.push(textbox);}}
for(var i in productPanel.layoutTextboxes){var textbox=productPanel.layoutTextboxes[i];if(!textbox.disable){allTextboxes.push(textbox);}}
for(var i=0;i<allTextboxes.length;i++){var textbox=allTextboxes[i];var editor=new PersonalizeTextboxEditor();editor.textbox=textbox;editor.productTextbox=Personalize.product.panels[this.currentPanel.panelId].textboxes[textbox.textboxId];if(!editor.productTextbox){var panelId=this.currentPanel.panelId;if(panelId){var layoutId=Personalize.personalization.panels[this.currentPanel.panelId].layoutId;if(layoutId){try{editor.productTextbox=Personalize.product.panels[panelId].templateLayouts[layoutId].textboxes[textbox.textboxId];}catch(e){}}}}
if(editor.hasLocalStyle()){requiringNormalization.push(editor);}else{var styleClassId=editor.getStyleClassId();if(styleClassId>maxStyleClassId){maxStyleClassId=styleClassId;}
siblingEditor=this.findEditorForStyleClassId(styleClassId);styleEditor=null;var styleEditor=new PersonalizeStyleEditor('Text Style');if(siblingEditor){styleEditor.addSibling(siblingEditor);siblingEditor.addSibling(styleEditor);}
styleEditor.setStyleClass(Personalize.product.styleClasses[styleClassId]);this.styleEditors.push(styleEditor);styleEditor.attachTextEditor(editor);this.textboxEditors.push(editor);}}
for(var j=0;j<requiringNormalization.length;j++){var currentEditor=requiringNormalization[j];maxStyleClassId++;var styleEditor=new PersonalizeStyleEditor();var style=currentEditor.getStyleObject();style.styleClassId=maxStyleClassId;currentEditor.setStyleClassId(style.styleClassId);styleEditor.setStyleClass(style);styleEditor.attachTextEditor(currentEditor);this.styleEditors.push(styleEditor);this.textboxEditors.push(currentEditor);}},cleanupEditors:function(){for(var i=0;i<this.styleEditors.length;i++){try{delete this.styleEditors[i];}catch(e){}}
for(var i=0;i<this.textboxEditors.length;i++){try{delete this.textboxEditors[i];}catch(e){}}
this.styleEditors=[];this.textboxEditors=[];},findEditorForStyleClassId:function(styleClassId){for(var i=0;i<this.styleEditors.length;i++){if(this.styleEditors[i].isStyleClass(styleClassId)){return this.styleEditors[i];}}
return false;},blurUnfocusedEditors:function(){for(var i=0;i<this.textboxEditors.length;i++){var editor=this.textboxEditors[i];if(!editor.hasFocus){editor.realBlur();}}},deactivate:function(){$(this.element.id).hide();return true;},activate:function(fromNext){if(fromNext){this.rendered=false;this.cleanupEditors();}
$('saveButton').show();$('saveButton').observe('click',this.save.bind(this));$('saveButton_bottom').show();$('saveButton_bottom').observe('click',this.save.bind(this));if(!fromNext){this.completeActivation(fromNext);}else{this.findLayoutTextboxes();Personalize.services.populateTextFromTemplate(this.completeActivation.bind(this));}
var val=Personalize.personalization.instructions;if(val==null)val='';this.specialInstructions.setValue(val);},hasPhotos:function(){for(var panelId in Personalize.product.panels){var panel=Personalize.product.panels[panelId];for(var photoId in panel.photos){return true;}}
return false;},completeActivation:function(fromNext){if(!this.rendered){this.currentPanel=this.getFirstPanel();}
try{var productPanel=Personalize.product.panels[this.currentPanel.panelId];this.currentLayout=(this.verseStep)?this.verseStep.getSelectedVerse():this.currentLayout=null
this.panelNameElement.update('Personalize Your Card');if(!this.rendered){this.createEditors();this.renderPanelSelect();this.renderColorSwitcher();this.renderEditPanel();this.renderPreviewPanel();this.renderPhotoTray();this.clearError();this.photoTray.updateUsedThumbs();this.rendered=true;}else{}}catch(e){}
$(this.element.id).show();if(Personalize.saveLogin){setTimeout(function(){if(Personalize.activeStep.save()){Personalize.activeStep.saveComplete();}},1000);}},next:function(){if(this.isLastPanel()){return true;}else{var nextPanel=this.getNextPanel();this.changePanel(nextPanel);this.panelSwitcher.setActivePanel(nextPanel);return false;}},back:function(){if(this.isFirstPanel()){return true;}else{var prevPanel=this.getPrevPanel();this.changePanel(prevPanel);this.panelSwitcher.setActivePanel(prevPanel);return false;}},isFirstPanel:function(){for(var panelId in Personalize.personalization.panels){if(Personalize.personalization.panels[panelId]==this.currentPanel){return true;}
return false;}},isLastPanel:function(){var panel=null;for(var panelId in Personalize.personalization.panels){panel=Personalize.personalization.panels[panelId];}
if(Personalize.personalization.panels[panelId]==this.currentPanel){return true;}
return false;},getNextPanel:function(){var getNext=false;for(var panelId in Personalize.personalization.panels){if(getNext){return Personalize.personalization.panels[panelId];}
if(Personalize.personalization.panels[panelId]==this.currentPanel){getNext=true;}}
return false;},getPrevPanel:function(){var prev=null;for(var panelId in Personalize.personalization.panels){if(Personalize.personalization.panels[panelId]==this.currentPanel){return prev;}
prev=Personalize.personalization.panels[panelId];}},changePanel:function(newPanel){this.cleanupEditors();this.currentPanel=newPanel;var productPanel=Personalize.product.panels[this.currentPanel.panelId];this.panelNameElement.update('Personalize Your Card');this.createEditors();this.renderEditPanel();this.renderPreviewPanel();},changeColor:function(newColor){try{var color=Personalize.product.colors[newColor];Personalize.product.color=color;Personalize.personalization.productColorId=newColor;this.changePreviewImage();this.panelSwitcher.changeColor();for(var i=0;i<this.styleEditors.length;i++){this.styleEditors[i].changeColor(newColor);}
for(var i=0;i<this.photos.length;i++){this.photos[i].changeColor(newColor);}
for(var i=0;i<this.overlays.length;i++){this.overlays[i].changeColor(newColor);}
Personalize.personalization.colorCyan=null;Personalize.personalization.colorMagenta=null;Personalize.personalization.colorYellow=null;Personalize.personalization.colorBlack=null;}catch(e){}},uploadPhotos:function(opener){this.photoUploader.popup(opener);},addPhotoToTray:function(photoId){this.photoTray.addPhoto(photoId);this.photoTray.scrollToEnd();},getUserPhotos:function(){return this.photoTray.getPhotoList();},popupFontPreview:function(){},setError:function(){if(!this.error){this.error=true;Effect.BlindDown(this.errorViewer,{duration:0.30});}},clearError:function(){if(this.error){for(var i=0;i<this.textboxes.length;i++){if(this.textboxes[i].hasError())return;}
for(var i=0;i<this.photos.length;i++){if(this.photos[i].hasError())return;}
Effect.BlindUp(this.errorViewer,{duration:0.30});this.error=false;}},findLayoutTextboxes:function(){for(var panelId in Personalize.personalization.panels){var myLayoutId=Personalize.personalization.panels[panelId].layoutId;if(myLayoutId){for(var groupId in Personalize.product.templates.groups){var group=Personalize.product.templates.groups[groupId];for(var templateId in group.templates){var template=group.templates[templateId];for(var layoutId in template.layouts){if(layoutId==myLayoutId){this.layoutTextboxesToPersonalization(template.layouts[layoutId].textboxes,layoutId);return;}}}}}}},layoutTextboxesToPersonalization:function(textboxes,theLayoutId){for(var panelId in Personalize.personalization.panels){var panel=Personalize.personalization.panels[panelId];panel.layoutTextboxes={};}
for(panelId in Personalize.product.panels){var panel=Personalize.product.panels[panelId];for(layoutId in panel.templateLayouts){if(layoutId==theLayoutId){for(var textboxId in textboxes){Personalize.services.addLayoutTextbox(Personalize.personalization.panels[panelId],textboxes[textboxId]);}
return true;}}}
return false;},saveSpecialInstructions:function(){Personalize.personalization.instructions=this.specialInstructions.getValue();},photoUploaderAddPhoto:function(photo){this.photoUploader.addPhoto(photo);},photoUploaderCheckAddToOpener:function(photo){this.photoUploader.checkAddToOpener(photo);}});var PersonalizeColorSwitcher=function(){this.currentSelector=null;this.customColorHelpDlg=null;}
PersonalizeColorSwitcher.prototype={hasCustomColors:function(){for(var i in Personalize.product.customColors){return true;}
return false;},render:function(parent){var title=new Element('div',{align:'left','class':'panelSwitchTitle'}).update('<span style="font-weight:bold">Color Options</span> <span style="font-size:11px">(click to change color)</span>');if(this.hasCustomColors()){var ccEl=new Element('span',{'class':'clickable',style:'color:#3c95b4; font-size:11px;'}).update('&nbsp;&nbsp;&nbsp;&nbsp;Custom Colors');ccEl.observe('click',this.showCustomColors.bind(this));title.insert(ccEl);}
this.container=new Element('div');parent.update(title);for(var colorId in Personalize.product.colors){var color=Personalize.product.colors[colorId].color;var colorElementSelector=new Element('div',{'class':'colorElementSelector'});if(colorId==Personalize.product.color.id){colorElementSelector.addClassName('selectedColorElementSelector');this.currentSelector=colorElementSelector;}
var colorName=(color.displayName.length>0)?color.displayName:color.name;var colorElement=new Element('img',{title:colorName,src:Personalize.hosts.static+'image/blank.gif','class':'colorElement clickable',style:'background-color:#'+color.rgb});this.container.insert(colorElementSelector.insert(colorElement));colorElement.observe('click',this.handleColorSwitch.bindAsEventListener(this,colorId,colorElement));}
this.customColorWarning=new Element('div',{'class':'customColorWarning',align:'left'}).update(this.getCustomColorWarningText());this.customColorWarning.observe('click',this.showCustomColorHelp.bind(this));this.container.insert(new Element('div',{style:'clear:both'}));this.container.insert(this.customColorWarning);if(!this.hasCustomColor()){this.customColorWarning.hide();}
parent.insert(this.container);},handleColorSwitch:function(ev,colorId,colorElement){if(this.currentSelector){this.currentSelector.removeClassName('selectedColorElementSelector');}
var selector=colorElement.up();selector.addClassName('selectedColorElementSelector');this.currentSelector=selector;Personalize.personalization.colorCyan=null;Personalize.personalization.colorMagenta=null;Personalize.personalization.colorYellow=null;Personalize.personalization.colorBlack=null;this.customColorWarning.hide();if(typeof this.clickCallback==='function'){this.clickCallback(colorId);}},customColorSelected:function(){Personalize.personalization.colorCyan=this.customColorSelector.cyan;Personalize.personalization.colorMagenta=this.customColorSelector.magenta;Personalize.personalization.colorYellow=this.customColorSelector.yellow;Personalize.personalization.colorBlack=this.customColorSelector.black;this.customColorWarning.update(this.getCustomColorWarningText());this.customColorWarning.show();},showCustomColors:function(){if(!this.customColorSelector){this.customColorSelector=new PersonalizeCustomColors(this.getCustomColor());}
this.customColorSelector.show(this.customColorSelected.bind(this));},hasCustomColor:function(){return((Personalize.personalization.colorCyan!=null)&&(Personalize.personalization.colorMagenta!=null)&&(Personalize.personalization.colorYellow!=null)&&(Personalize.personalization.colorBlack!=null));},getCustomColorWarningText:function(){var customColor=this.getCustomColor();var colorName='custom CMYK';if(customColor){if(customColor.displayName.length>0){colorName=customColor.displayName;}else{colorName=customColor.name;}}
return'<div style="margin:2px;background-color:#EFF9FE; border:1px solid #1688AA;font-size:10px;"><div class="sprite-btn-help clickable" style="float:left; margin:4px;"></div>The <b>'+colorName+'</b> color you\'ve selected will not preview. Please continue to personalize your card.</div>';},getCustomColor:function(){for(var colorId in Personalize.product.customColors){var customColor=Personalize.product.customColors[colorId];if(Personalize.personalization.colorCyan==customColor.cyan&&Personalize.personalization.colorMagenta==customColor.magenta&&Personalize.personalization.colorYellow==customColor.yellow&&Personalize.personalization.colorBlack==customColor.black)
{return customColor;}}
return false;},showCustomColorHelp:function(){if(!this.customColorHelpDlg){this.customColorHelpDlg=new PersonalizePopup('Custom Color Help','customColorHelp');}
var customColor=this.getCustomColor();this.ccDlgElem=this.customColorHelpDlg.getPopupElement();if(customColor){var colorName=customColor.name;if(customColor.displayName.length>0)colorName=customColor.displayName;}else{var colorName='CMYK';}
var textElem=new Element('div',{style:'margin:16px;width:340px;font-family:helvetica; font-size:12px; ',align:'left'}).update('The <b>'+colorName+'</b> custom color you\'ve selected will not instantly preview on the personalization page. Please continue to personalize the card as usual, and complete your order. One of our professional designers will contact you to discuss your customization needs after you have placed your order, and we will send you a complimentary digital proof so you can see your customized cards before we print them. Please use the Special Instructions box to specify any special requests, and our Design Specialists will contact you if they have any questions or concerns about your order.');var buttonElem=new Element('div',{align:'right',style:'margin:8px;'}).update(new Element('div',{'class':'sprite-btn_close clickable'}));buttonElem.observe('click',this.customColorHelpDlg.hidePopup.bind(this.customColorHelpDlg));this.ccDlgElem.update(textElem);this.ccDlgElem.insert(buttonElem);this.ccDlgElem.setStyle({width:'356px'});this.customColorHelpDlg.showPopup();}}
var PersonalizePanelSwitcher=function(){this.domElement=null;this.clickCallback=null;this.selectedBorderColor='#55381a';this.selectedThumb=null;this.thumbs=[];}
PersonalizePanelSwitcher.prototype={render:function(container){container.update('');var title=new Element('div',{align:'left','class':'panelSwitchTitle'}).update('<span style="font-weight:bold">Panel</span> <span style="font-size:11px">(click to preview)</span>');var thumber=new Element('div',{align:'left','class':'panelSwitchThumbContainer'});for(var panelId in Personalize.personalization.panels){var panel=Personalize.personalization.panels[panelId];var productPanel=Personalize.product.panels[panelId];var thumb=new Element('div',{'class':'panelThumbnail clickable'});var thumbContainer=new Element('div',{'class':'panelThumbnailContainer'});var thumbUrl=this.getPanelThumbUrl(panel,productPanel);var img=new Element('img',{'src':thumbUrl});var thumbTitle=new Element('div',{'align':'center'}).update(productPanel.name);thumb.identify();thumb.panelId=panelId;thumb.insert(img);thumb.img=img;thumbContainer.update(thumb);thumbContainer.insert(new Element('div',{style:'clear: both'}));thumbContainer.insert(thumbTitle);thumber.insert(thumbContainer);thumb.stopObserving('click');thumb.observe('click',this.handleClick.bindAsEventListener(this,panel,thumb));this.thumbs.push(thumb);if(panel==Personalize.activeStep.currentPanel){this.selectedThumb=thumb;thumb.setStyle({border:'2px solid '+this.selectedBorderColor});}}
container.insert(title);container.insert(thumber);container.insert(new Element('div',{style:'clear:both'}));},changeColor:function(){for(var i=0;i<this.thumbs.length;i++){var thumb=this.thumbs[i];var panel=Personalize.personalization.panels[thumb.panelId];var productPanel=Personalize.product.panels[thumb.panelId];var thumbUrl=this.getPanelThumbUrl(panel,productPanel);var img=new Element('img',{'src':thumbUrl});thumb.update(img);}},setActivePanel:function(panel,instantaneous){if(!instantaneous){var duration=0.5;}else{var duration=0.001;}
if(thumb==this.selectedThumb)return;for(var i=0;i<this.thumbs.length;i++){var thumb=this.thumbs[i];if(panel.panelId==thumb.panelId){try{new Effect.Morph(this.selectedThumb,{style:'border: 2px solid #FFF',duration:duration});}catch(e){}
this.selectedThumb=thumb;new Effect.Morph(thumb,{style:'border: 2px solid '+this.selectedBorderColor,duration:duration});}}},handleClick:function(ev,panel,thumb){if(thumb==this.selectedThumb)return;try{new Effect.Morph(this.selectedThumb,{style:'border: 2px solid #FFF',duration:0.5});}catch(e){}
this.selectedThumb=thumb;new Effect.Morph(thumb,{style:'border: 2px solid '+this.selectedBorderColor,duration:0.5});if(this.clickCallback){this.clickCallback(panel);}},getPanelThumbUrl:function(panel,productPanel){return Personalize.hosts.images+'product/'+Personalize.product.id+'/color/'+Personalize.product.color.number+'/panel/'+productPanel.number+'/type/sample/height/36/shadow/1.png';}}
var PersonalizeStyleEditor=function(title){this.styleClass=null;this.title=title;this.attachedTextEditors=[];this.siblings=[];this.domElement=null;this.timeouts=[];this.fontSelect=null;this.fontColorSelect=null;this.fontSizeselect=null;this.trickySpacer=null;this.fontPopup=null;}
PersonalizeStyleEditor.prototype={getSelections:function(){var defaults=new Object();defaults.fontId=this.attachedTextEditors[0].textbox.fontId;defaults.fontColorId=this.attachedTextEditors[0].textbox.fontColorId;defaults.fontSize=this.attachedTextEditors[0].textbox.fontSize;return defaults;},setStyleClass:function(styleClass){this.styleClass=styleClass;},attachTextEditor:function(editor){this.attachedTextEditors.push(editor);editor.setStyleEditor(this);},isStyleClass:function(styleClassId){if(typeof this.styleClass==='undefined')return true;return(this.styleClass.styleClassId==styleClassId);},getSelectedFont:function(){try{return Personalize.masterFontList[this.fontSelect.getValue()].name;}catch(e){return false}},getSelectedFontId:function(){return this.fontSelect.getValue();},getSelectedFontSize:function(){return this.fontSizeSelect.getValue();},getSelectedFontColor:function(){try{return Personalize.product.fontColors[this.colorValue].rgb;}catch(e){return false}},changeColor:function(){var first=true;var selectedElement=null;var hasSelection=false;var currentColorId=this.attachedTextEditors[0].textbox.fontColorId;this.fontColorSelect.update('');try{delete this.fontColorSelect.swatches;}catch(e){}
this.fontColorSelect.swatches=[];for(var fontColorId in this.styleClass.style.fontColors[Personalize.product.color.id]){var color=Personalize.product.fontColors[fontColorId];var styleColor=this.styleClass.style.fontColors[Personalize.product.color.id][fontColorId];try{if(hasSelection){var selected=(color.id==this.attachedTextEditors[0].textbox.fontColorId);}else{var selected=(styleColor['default']==1)||(color.id==this.attachedTextEditors[0].textbox.fontColorId);if(selected){hasSelection=true};}
var fontColorElement=new Element('div',{'class':'clickable '+((first)?' selectedColor':'nonSelectedColor'),style:'float: left; padding:1px; background-color: #'+color.rgb});if(selected){this.colorValue=color.id;selectedElement=fontColorElement;}
fontColorElement.observe('click',this.fontColorSelect.setValue.bindAsEventListener(this,color.id));fontColorElement.identify();fontColorElement.colorId=color.id;this.fontColorSelect.swatches.push(fontColorElement);fontColorElement.observe('click',this.fontColorSelect.changeSelection.bindAsEventListener(this.fontColorSelect,fontColorElement));this.fontColorSelect.insert(fontColorElement);}catch(e){}}
this.fontColorSelect.changeSelection(null,selectedElement);for(var i=0;i<this.attachedTextEditors.length;i++){this.attachedTextEditors[i].updatePreview();}},getSelectedFontColorId:function(){return this.colorValue;},render:function(small){var postfix='_textbox_'+this.attachedTextEditors[0].textbox.textboxId;if(small){var fontWidth=180;var sizeWidth=46;var colorWidth=110;var elemMargin=0;}else{var fontWidth=191;if(Personalize.ie6){var fontWidth=180;}
var sizeWidth=46;var colorWidth=119;var elemMargin=8;}
var mainElement=new Element('div',{id:'StyleContainer_'+this.styleClass.styleClassId+postfix,style:'margin-left:'+elemMargin+'px;'});var defaults=this.getSelections();this.fontSelect=new Element('select',{style:'width : '+fontWidth+'px',id:'FontSelect_Style_'+this.styleClass.styleClassId+postfix});var recommendedFontListIds=[];var optionGroup=new Element('optgroup',{label:'Recommended',id:'RecoGroup_'+this.styleClass.styleClassId});optionGroup.identify();this.fontSelect.insert(optionGroup);var recommendedFontListForPreview=[];for(var fontId in this.styleClass.style.fonts){var font=Personalize.product.fonts[fontId];var styleFont=this.styleClass.style.fonts[fontId];if(font!==undefined){recommendedFontListForPreview.push(font.id);var fontOptionElement=new Element('option',{value:font.id}).update(font.displayName);fontOptionElement.identify();if(!defaults.fontId&&styleFont['default']==1){fontOptionElement.selected=true;}
if(styleFont['default']==1){fontOptionElement.update(font.displayName+' (default)');}
if(defaults.fontId==font.id){fontOptionElement.selected=true;}
this.fontSelect.insert(fontOptionElement);recommendedFontListIds.push(font.id);}}
this.fontSelect.observe('change',this.styleChangeHandler.bindAsEventListener(this,this.fontSelect));var otherFontListForPreview=[];if(parseFloat(Personalize.product.fulfillmentItemType.limitedFonts)==0){var optionGroup=new Element('optgroup',{label:'Other',id:'OtherGroup_'+this.styleClass.styleClassId});this.fontSelect.insert(optionGroup);for(var fontId in Personalize.masterFontList){var font=Personalize.masterFontList[fontId];try{if(typeof font=='undefined'){continue;}
if(typeof font!=='undefined'&&font.displayName&&recommendedFontListIds.indexOf(font.id)==-1){otherFontListForPreview.push(fontId);var fontOptionElement=new Element('option',{value:font.id}).update(font.displayName);fontOptionElement.identify();if(defaults.fontId==font.id){fontOptionElement.selected=true;}
this.fontSelect.insert(fontOptionElement);}}catch(e){}}}
this.fontPopup=new PersonalizeFontPreview(recommendedFontListForPreview,otherFontListForPreview);this.fontSizeSelect=new Element('select',{style:'width : '+sizeWidth+'px',id:'FontSizeSelect_Style_'+this.styleClass.styleClassId+postfix});for(var fontSizeId in this.styleClass.style.fontSizes){var fontOptionElement=new Element('option',{value:fontSizeId}).update(fontSizeId);var styleFontSize=this.styleClass.style.fontSizes[fontSizeId]
fontOptionElement.identify();if(!defaults.fontSize&&styleFontSize['default']==1){fontOptionElement.selected=true;}
if(defaults.fontSize==fontSizeId){fontOptionElement.selected=true;}
this.fontSizeSelect.insert(fontOptionElement);}
this.fontSizeSelect.observe('change',this.styleChangeHandler.bindAsEventListener(this,this.fontSizeSelect));this.fontColorSelect=new Element('div',{style:'width : '+colorWidth+'px',id:'FontColorSelect_Style_'+this.styleClass.styleClassId+postfix});this.fontColorSelect.swatches=[];this.fontColorSelect.getValue=function(ev){return this.colorValue;}
this.fontColorSelect.setValue=function(ev,value){this.colorValue=value;this.styleChangeHandler(null,this.fontColorSelect);}
this.fontColorSelect.changeSelection=function(ev,elem){for(var i=0;i<this.swatches.length;i++){var sw=this.swatches[i];if(sw==elem){sw.addClassName('selectedColor');sw.removeClassName('nonSelectedColor');}else{sw.addClassName('nonSelectedColor');sw.removeClassName('selectedColor');}}}
var hasSelection=false;var selectedElement=null;for(var fontColorId in this.styleClass.style.fontColors[Personalize.product.color.id]){var color=Personalize.product.fontColors[fontColorId];var styleColor=this.styleClass.style.fontColors[Personalize.product.color.id][fontColorId];try{if(hasSelection){var selected=(color.id==this.attachedTextEditors[0].textbox.fontColorId);}else{var selected=(styleColor['default']==1)||(color.id==this.attachedTextEditors[0].textbox.fontColorId);if(selected){hasSelection=true};}
var fontColorElement=new Element('div',{'class':'clickable '+((selected)?' selectedColor':'nonSelectedColor'),style:'float: left; padding:1px; background-color: #'+color.rgb});fontColorElement.colorId=color.id;if(selected){this.colorValue=color.id;selectedElement=fontColorElement;}
fontColorElement.observe('click',this.fontColorSelect.setValue.bindAsEventListener(this,color.id));fontColorElement.identify();this.fontColorSelect.swatches.push(fontColorElement);fontColorElement.observe('click',this.fontColorSelect.changeSelection.bindAsEventListener(this.fontColorSelect,fontColorElement));this.fontColorSelect.insert(fontColorElement);}catch(e){}}
this.fontColorSelect.changeSelection(null,selectedElement);var fontViewText='&nbsp;(View)';if(!small)fontViewText='&nbsp;(View Fonts)';var popupFonts=new Element('a',{'class':'clickable previewFontsLink'}).update(fontViewText);popupFonts.identify();popupFonts.observe('click',this.showFontPopup.bindAsEventListener(this));var fontTitleText='Font ';if(!small)fontTitleText=this.title;var titleDiv=new Element('div',{style:"float:left; width:"+fontWidth+"px",'class':'styleTitle'}).update(fontTitleText);titleDiv.insert(popupFonts);var fontSizeTitleDiv=new Element('div',{style:"float:left; width:"+sizeWidth+"px",'class':'styleTitle'}).update('Size');var fontColorTitleDiv=new Element('div',{style:"float:left; width:"+colorWidth+"px",'class':'styleTitle'}).update('Color');titleDiv.identify();fontSizeTitleDiv.identify();fontColorTitleDiv.identify();var handle=new Element('div',{id:'Handle_Style_'+this.styleClass.styleClassId});handle.insert(titleDiv);handle.insert(fontSizeTitleDiv);handle.insert(fontColorTitleDiv);mainElement.insert(handle);var elem=null;mainElement.insert(new Element('div',{style:'width : '+fontWidth+'px; float : left;',id:'FontSelectCont_Style_'+this.styleClass.styleClassId}).update(this.fontSelect));mainElement.insert(new Element('div',{style:'width : '+sizeWidth+'px; float : left;',id:'FontSizeSelectCont_Style_'+this.styleClass.styleClassId}).update(this.fontSizeSelect));mainElement.insert(new Element('div',{style:'width : '+colorWidth+'px; float : left;',id:'FontColorSelectCont_Style_'+this.styleClass.styleClassId}).update(this.fontColorSelect));elem=new Element('div',{style:'clear : both; height:4px;'});elem.identify();mainElement.insert(elem);mainElement.observe('mouseover',this.mouseOver.bindAsEventListener(this,mainElement))
mainElement.observe('mouseout',this.mouseOut.bindAsEventListener(this,mainElement))
this.domElement=mainElement;if(this.siblings.length>0){try{this.tooltip=new TPBalloon({anchor:mainElement.identify(),width:200,height:40,fadeTime:0.3,imageBase:Personalize.hosts['static']+'/image/balloon/',stemPosition:'rightMiddle',content:'<b>Changing this text style will affect all highlighted text boxes</b>',contentClass:'toolTipContent',animator:new TPBalloonPointerAnimator({repetitions:2,distance:5,delay:0})});}catch(e){}}
return this.domElement;},showFontPopup:function(ev){Event.stop(ev);this.fontPopup.show();},styleChangeHandler:function(event,element,colorId){if(colorId){this.fontColorSelect.colorValue=colorId;}
for(var i=0;i<this.attachedTextEditors.length;i++){this.attachedTextEditors[i].updatePreview();}
for(var i=0;i<this.siblings.length;i++){this.siblings[i].updateFromSibling(this);}},mouseOver:function(ev){try{if($(ev.target.id).descendantOf(this.domElement)||(ev.target==this.domElement)){for(var i=0;i<this.timeouts.length;i++){clearTimeout(this.timeouts[i]);}
this.timeouts=[];}}catch(e){}
for(var i=0;i<this.siblings.length;i++){this.siblings[i].attachedTextEditors[0].lightUp();}
if(this.tooltip)this.tooltip.show();},mouseOut:function(ev){var timeout=setTimeout(this.outHandler.bind(this),50);this.timeouts.push(timeout);},outHandler:function(i){if(this.tooltip)this.tooltip.hide();for(var i=0;i<this.siblings.length;i++){this.siblings[i].attachedTextEditors[0].lightDown();}},addSibling:function(styleEditor){this.siblings.push(styleEditor);},updateFromSibling:function(sibling){var values=sibling.getSelections();for(var i=0;i<this.fontSelect.options.length;i++){var opt=this.fontSelect.options[i];if(opt.value==values.fontId){opt.selected=true;}}
for(var i=0;i<this.fontSizeSelect.options.length;i++){var opt=this.fontSizeSelect.options[i];if(opt.value==values.fontSize){opt.selected=true;}}
for(var i=0;i<this.fontColorSelect.swatches.length;i++){var swatch=this.fontColorSelect.swatches[i];if(swatch.colorId==sibling.getSelectedFontColorId()){this.colorValue=sibling.getSelectedFontColorId();this.fontColorSelect.changeSelection(null,swatch);}}
for(var i=0;i<this.attachedTextEditors.length;i++){this.attachedTextEditors[i].updatePreview();}}}
var PersonalizeTextbox=function(textbox,resolution){this.textbox=textbox;this.domElement=null;this.stripeElement=null;this.image=null;this.resolution=resolution;this.editor=null;this.error=false;this.lit=false;this.realX=0;this.realY=0;this.width=0;this.height=0;this.errorString='<span style="font-weight: bold">Warning: </span>Your text does not fit in the text area. Please remove some text or reduce the size. To edit or add text, click on the text box below.';}
PersonalizeTextbox.prototype={findEditorAndAttach:function(){for(var i=0;i<Personalize.activeStep.textboxEditors.length;i++){candidateEditor=Personalize.activeStep.textboxEditors[i];if(candidateEditor.textbox===this.textbox){candidateEditor.attachTextbox(this);this.editor=candidateEditor;return true;}}
return false;},getBounds:function(){var bounds=Object();if(this.textbox.controlX){bounds.top=Personalize.resolutionConvert(this.textbox.controlY,144,this.resolution);bounds.left=Personalize.resolutionConvert(this.textbox.controlX,144,this.resolution);bounds.width=Personalize.resolutionConvert(this.textbox.controlWidth,144,this.resolution);bounds.height=Personalize.resolutionConvert(this.textbox.controlHeight,144,this.resolution);}else{bounds.top=Personalize.resolutionConvert(this.textbox.y,144,this.resolution);bounds.left=Personalize.resolutionConvert(this.textbox.x,144,this.resolution);bounds.width=Personalize.resolutionConvert(this.textbox.width,144,this.resolution);bounds.height=Personalize.resolutionConvert(this.textbox.height,144,this.resolution);}
return bounds;},getMargins:function(){var margins=Object();if(this.textbox.controlX){margins.top=Personalize.resolutionConvert(parseFloat(this.textbox.y)-parseFloat(this.textbox.controlY),144,this.resolution);margins.left=Personalize.resolutionConvert(parseFloat(this.textbox.x)-parseFloat(this.textbox.controlX),144,this.resolution);margins.right=Personalize.resolutionConvert((parseFloat(this.textbox.controlX)+parseFloat(this.textbox.controlWidth))-(parseFloat(this.textbox.x)+parseFloat(this.textbox.width)),144,this.resolution);margins.bottom=Personalize.resolutionConvert((parseFloat(this.textbox.controlY)+parseFloat(this.textbox.controlHeight))-(parseFloat(this.textbox.y)+parseFloat(this.textbox.height)),144,this.resolution);}else{return false;}
return margins;},render:function(parentElement){var firstRender=false;var bounds=this.getBounds();this.realY=Personalize.roundForRendering(bounds.top);this.realX=Personalize.roundForRendering(bounds.left);this.width=Personalize.roundForRendering(bounds.width);this.height=Personalize.roundForRendering(bounds.height);if(!this.domElement){firstRender=true;this.domElement=new Element('div',{id:'panel_Textbox_'+this.textbox.textboxId,'class':'clickable'});this.domElement.setStyle({border:'0px solid #000',padding:'0px',overflow:'hidden',position:'absolute',zIndex:parseFloat(Personalize.textboxZIndex)+parseFloat(this.textbox.z),top:this.realY+'px',left:this.realX+'px',width:this.width+'px',height:this.height+'px'});parentElement.insert(this.domElement);var top=this.realY+8;var height=Math.max(this.height-16,5);this.stripeElementOfs=0;this.stripeElement=new Element('div',{id:'panel_Textbox_'+this.textbox.textboxId+'_Stripes'});this.stripeElement.setStyle({border:'0px solid #000',padding:'0px',overflow:'hidden',position:'absolute',zIndex:parseFloat(Personalize.textboxZIndex)+parseFloat(this.textbox.z)-1,backgroundImage:'url('+Personalize.hosts['static']+'image/wpd/stripe-tile-green.png)',top:top+'px',left:this.realX+'px',width:this.width+'px',height:height+'px'});this.stripeElement.setOpacity(0);parentElement.insert(this.stripeElement);}
this.domElement.update('');var uri=this.getTextboxUrl(this.textbox);if(this.image)delete this.image;this.image=new Image();this.image.onload=this.imgLoadCheck.bind(this);this.domElement.insert(this.loader);if(firstRender){this.domElement.observe('mouseover',this.overHandler.bind(this));this.domElement.observe('mouseout',this.outHandler.bind(this));this.domElement.observe('click',this.clickHandler.bind(this));}
this.image.src=uri;if(!firstRender&&this.stripeElement){if(!this.loadingTimer)
this.loadingTimer=setInterval(this.scrollStripes.bind(this),100);this.stripeElement.fade({duration:0.3,from:this.stripeElement.getOpacity(),to:0.2});var fooDate=new Date();this.loadingTimerStartTime=parseInt(fooDate.getTime());}
return;},scrollStripes:function(){this.stripeElementOfs=(this.stripeElementOfs+2)%64;this.stripeElement.setStyle({backgroundPosition:this.stripeElementOfs+'px'});},clickHandler:function(){this.lightUp();this.editor.setFocus();},overHandler:function(){this.lightUp();this.editor.lightUp();},outHandler:function(){this.lightDown();this.editor.lightDown();},imgLoadCheck:function(ev,el,loader){try{var fooDate=new Date();var removeIn=2000-Math.max(0,(fooDate.getTime()-this.loadingTimerStartTime));setTimeout(this.removeLoader.bind(this),removeIn);}catch(e){}},removeLoader:function(){if(this.stripeElement)this.stripeElement.fade({duration:0.3,from:this.stripeElement.getOpacity(),to:0.01});clearInterval(this.loadingTimer);this.loadingTimer=null;if(this.height!=0&&this.width!=0){if(this.image.height>this.height||this.image.width>this.width){this.setError(this.errorString);}else{this.clearError();}}
if(Personalize.ie6){this.domElement.setStyle({background:'',filter:'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="'+encodeURI(this.image.src).replace(/\)/g,'%29')+'",sizingMethod="crop")'});}else{this.domElement.setStyle({background:'transparent url("'+this.image.src+'") no-repeat top left'});}},getTextboxUrl:function(textbox){this.textbox.content=this.editor.textArea.getValue();this.textbox.fontId=this.editor.myStyleEditor.getSelectedFontId();this.textbox.fontColorId=this.editor.myStyleEditor.getSelectedFontColorId();this.textbox.fontSize=this.editor.myStyleEditor.getSelectedFontSize();;var bounds=this.getBounds();var parameters={width:bounds.width,height:bounds.height,resolution:this.resolution,fontName:this.editor.myStyleEditor.getSelectedFont(),fontSize:this.editor.myStyleEditor.getSelectedFontSize(),fontColor:this.editor.myStyleEditor.getSelectedFontColor(),stroke:this.textbox.stroke,tracking:this.textbox.tracking,verticalAlignment:'center',horizontalAlignment:'center',text:encodeURIComponent(encodeURIComponent(JSON.stringify(this.textbox.content)))};switch(parseFloat(this.textbox.horizontalAlignmentId)){case 1:parameters.horizontalAlignment='left';break;case 2:parameters.horizontalAlignment='center';break;case 3:parameters.horizontalAlignment='right';break;}
switch(parseFloat(this.textbox.verticalAlignmentId)){case 2:parameters.verticalAlignment='top';break;case 3:parameters.verticalAlignment='center';break;case 4:parameters.verticalAlignment='bottom';break;case 5:parameters.verticalAlignment='illustrator';break;}
if(this.textbox.leading)parameters.leading=this.textbox.leading;var margins=this.getMargins();if(margins){parameters.marginTop=margins.top;parameters.marginLeft=margins.left;parameters.marginRight=margins.right;parameters.marginBottom=margins.bottom;}
var url=Personalize.hosts.images+'personalize/textbox/restrictSize/0';for(var key in parameters){url+='/'+key+'/'+parameters[key];}
return url+'.png';},setError:function(text){this.error=true;this.editor.setError(text);Personalize.activeStep.setError();this.domElement.setStyle({border:'2px solid #F00',padding:'0px'});},clearError:function(text){if(this.error){this.editor.clearError(text);this.error=false;Personalize.activeStep.clearError();if(this.lit){this.lightUp();}else{this.lightDown();}}},hasError:function(){return this.error;},lightUp:function(){this.lit=true;if(this.error)return;this.tempY=this.realY-2;this.tempX=this.realX-2;this.domElement.setStyle({border:'2px solid #b8b8b8',top:this.tempY+'px',left:this.tempX+'px',padding:'0px'});},lightDown:function(){this.lit=false;if(this.error)return;this.domElement.setStyle({border:'0px solid #b8b8b8',top:this.realY+'px',left:this.realX+'px',padding:'0px'});}}
var PersonalizeTextboxEditor=function(){this.textbox=null;this.productTextbox=null;this.domElement=null;this.previewDomElement=null;this.panelTextbox=null;this.fontId=null;this.fontSize=null;this.errorElement=null;this.errorText=null;this.myStyleEditor=null;this.fontColor=null;this.textArea=null;this.textAreaSmallHeight=20;this.textAreaLargeHeight=80;this.title='Text Box';this.lit=false;this.error=false;this.hasFocus=false;this.titleElement=null;this.inlineStyle=false;this.internalBlur=false;this.expanded=false;}
PersonalizeTextboxEditor.prototype={attachTextbox:function(panelTextbox){this.panelTextbox=panelTextbox;},hasLocalStyle:function(){var colors=false;var sizes=false;var fonts=false;if(typeof this.textbox!=='undefined'){for(var i in this.textbox.fontColors){colors=true;continue;}
for(var i in this.textbox.fontSizes){sizes=true;continue;}
for(var i in this.textbox.fonts){fonts=true;continue;}}
return(colors&&sizes&&fonts);},getStyleObject:function(){var obj={};obj.style={};obj.style.fontColors=this.textbox.fontColors;obj.style.fontSizes=this.textbox.fontSizes;obj.style.fonts=this.textbox.fonts;return obj;},setStyleClassId:function(styleClassId){return this.textbox.styleClassId=styleClassId;},getStyleClassId:function(){return this.textbox.styleClassId;},setStyleEditor:function(styleEditor){this.myStyleEditor=styleEditor;},doLeftAlign:function(){this.textbox.horizontalAlignmentId=1;this.panelTextbox.render();},doRightAlign:function(){this.textbox.horizontalAlignmentId=3;this.panelTextbox.render();},doCenterAlign:function(){this.textbox.horizontalAlignmentId=2;this.panelTextbox.render();},render:function(styleElement){var idPostfix=this.title.replace(/ /g,'_');if(styleElement){this.inlineStyle=true;this.inlineStyleElement=styleElement;}
var mainElement=new Element('div',{style:'padding:4px; margin:4px;'});this.titleElement=new Element('div',{align:'right'});var titleString='<div align="left" class="personalizeTextEditorHeader" id="title_'+idPostfix+'"><div id="titleText_'+idPostfix+'" style="width:50%; float:left; position: relative;" class="personalizeTextEditorHeaderTitle">'+this.title+'</div>';if(!this.inlineStyle){titleString+='<div align="right" style="width:50%; float:left; font-size:10px">'+this.myStyleEditor.title+'</div>'}
titleString+='<div style="clear:both" id="titleDivider_'+idPostfix+'"></div></div>';this.titleElement.update(titleString);this.titleElement.insert(new Element('div',{id:'moreDivison_'+idPostfix,style:'clear:  both'}));if(this.inlineStyle){this.titleElement.insert(new Element('div',{align:"left"}).update(styleElement));styleElement.style.border='1px solid #b8b8b8';styleElement.hide();}
this.bottomElement=new Element('div',{id:'error_'+idPostfix,align:'right',style:'height:22px; position:relative;'});var leftAlign=new Element('div',{id:'leftAlign_'+idPostfix,style:'float: left','class':'sprite-btn-align-left clickable'});var centerAlign=new Element('div',{id:'centerAlign_'+idPostfix,style:'float: left','class':'sprite-btn-align-center clickable'});var rightAlign=new Element('div',{id:'rightAlign_'+idPostfix,style:'float: left','class':'sprite-btn-align-right clickable'});var applyButton=new Element('div',{id:'applyButton_'+idPostfix,'class':'sprite-btn-apply clickable'});leftAlign.observe('click',this.doLeftAlign.bind(this));centerAlign.observe('click',this.doCenterAlign.bind(this));rightAlign.observe('click',this.doRightAlign.bind(this));this.errorElement=new Element('div',{id:'error_'+idPostfix,'class':'textErrorWarning',style:'position:relative'});var errorIcon=new Element('div',{id:'errorIcon_'+idPostfix,'class':'sprite-icon-warning-small-red',style:'float: left; margin-right:8px;'});this.errorText=new Element('div',{id:'errorText_'+idPostfix,'class':'textErrorWarningText'}).update('(Error: 42)');this.errorElement.insert(errorIcon);this.errorElement.insert(this.errorText);this.errorElement.hide();var alignable=false;if(this.productTextbox){if(this.productTextbox.horizontalAlignmentEnabled==null){if(parseFloat(Personalize.product.fulfillmentItemType.limitedFonts)){alignable=false;}else{alignable=true;}}else if(parseFloat(this.productTextbox.horizontalAlignmentEnabled)==0){alignable=false;}else{alignable=true;}}
if(alignable){this.bottomElement.insert(leftAlign);this.bottomElement.insert(centerAlign);this.bottomElement.insert(rightAlign);}
this.bottomElement.insert(applyButton);this.bottomElement.insert(new Element('div',{style:'clear:both'}));this.bottomElement.hide();this.textArea=new Element('textarea',{id:'textArea_'+idPostfix,'class':'textEditorArea'}).update('');this.textArea.value=this.textbox.content;this.textArea.identify();this.setHeightByLines(null,true);this.textArea.observe('change',this.textChange.bindAsEventListener(this));this.textArea.observe('keyup',this.setHeightByLines.bind(this));this.textArea.observe('focus',this.getFocus.bindAsEventListener(this));this.textArea.observe('blur',this.loseFocus.bindAsEventListener(this));mainElement.insert(this.titleElement);mainElement.insert(this.errorElement);mainElement.insert(this.textArea);mainElement.insert(new Element('div',{style:'position:relative'}).update(this.bottomElement));mainElement.insert(new Element('div',{style:'display:none'}));this.domElement=mainElement;return this.domElement;},setHeightByLines:function(ev,instantaneous){var text=this.textArea.value;var split=text.split("\n");var lines=Math.min(6,split.length);var newHeight=((lines)*16)+6;if(instantaneous!=null){this.textAreaSmallHeight=this.textAreaLargeHeight=newHeight;this.textArea.setStyle({height:newHeight+'px'});}else{if(newHeight!=this.textAreaSmallHeight){this.textAreaSmallHeight=this.textAreaLargeHeight=newHeight;new Effect.Morph(this.textArea,{style:{height:newHeight+'px'},duration:0.2});}}},textChange:function(){this.textbox.content=this.textArea.getValue();this.setHeightByLines();this.updatePreview();},getFocus:function(){this.hasFocus=true;if(!this.lit)
this.lightUp();if(!this.expanded)
this.expand();Personalize.activeStep.blurUnfocusedEditors();},setFocus:function(){this.textArea.focus();},loseFocus:function(ev){this.hasFocus=false;if(!ev){return;}
if(Personalize.safari){return;}else{var target=ev.explicitOriginalTarget||document.activeElement;}
if(target){if(target.id){if($(target).hasClassName('sprite-btn-next')||$(target).hasClassName('sprite-btn-back')||target.id==this.textArea.id||$(target.id).descendantOf(this.domElement)||target.id==this.panelTextbox.domElement.id||$(target.id).descendantOf(this.panelTextbox.domElement)){if(this.focusLoserCache){$(document).stopObserving('click',this.focusLoserCache);}
this.focusLoserCache=this.focusLoser.bindAsEventListener(this);$(document).observe('click',this.focusLoserCache);return;}}else{if($(target).hasClassName('sprite-btn-next')||$(target).hasClassName('sprite-btn-back')){return;}}}
this.realBlur();},focusLoser:function(ev){if(ev.target){if(ev.target.id){if(ev.target.id==this.textArea.id||$(ev.target.id).descendantOf(this.domElement)||$(ev.target.id).descendantOf(this.panelTextbox.domElement)||ev.target.id==this.panelTextbox.domElement.id){return;}}}
$(document).stopObserving('click',this.focusLoserCache);this.focusLoserCache=null;this.internalBlur=true;this.loseFocus();},realBlur:function(){this.lightDown();this.shrink();},shrink:function(){if(this.expanded){if(Personalize.isIe()){if(this.inlineStyle){this.inlineStyleElement.hide();}
new Effect.SlideUp(this.bottomElement,{duration:0.3});this.textArea.style.height=this.textAreaSmallHeight+'px';}else{if(this.inlineStyle){new Effect.SlideUp(this.inlineStyleElement,{duration:0.3});}
new Effect.SlideUp(this.bottomElement,{duration:0.3});new Effect.Morph(this.textArea,{style:'height: '+this.textAreaSmallHeight+'px',duration:0.3});}
this.expanded=false;}},expand:function(){if(!this.expanded){if(Personalize.isIe()){if(this.inlineStyle){this.inlineStyleElement.show();}
new Effect.SlideDown(this.bottomElement,{duration:0.3});this.textArea.style.height=this.textAreaLargeHeight+'px';}else{if(this.inlineStyle){new Effect.SlideDown(this.inlineStyleElement,{duration:0.3});}
new Effect.SlideDown(this.bottomElement,{duration:0.3});new Effect.Morph(this.textArea,{style:'height: '+this.textAreaLargeHeight+'px',duration:0.3});}
this.expanded=true;}},updatePreview:function(){this.panelTextbox.render();},setError:function(text){this.error=true;this.errorElement.show();this.errorText.update(text);this.domElement.setStyle({background:'#FF0000'});if(this.inlineStyle){this.inlineStyleElement.style.border='1px solid #ff0000';}},clearError:function(text){this.error=false;this.errorElement.hide();this.titleElement.setStyle({color:'#533519'});if(this.lit){this.lightUp(true);}else{this.lightDown(true);}
if(this.inlineStyle){this.inlineStyleElement.style.border='1px solid #b8b8b8';}},hasError:function(){return this.error;},lightUp:function(force){if(typeof force==='udefined')force=false;if(!force){if(this.lit)return;if(this.error)return;}
this.lit=true;if(Personalize.isIe()){this.domElement.setStyle({backgroundColor:'#b8b8b8'});}else{new Effect.Morph(this.domElement,{style:'background: #b8b8b8',duration:0.5});}
this.panelTextbox.lightUp();},lightDown:function(force){if(typeof force==='udefined')force=false;if(!force){if(!this.lit)return;if(this.error)return;}
this.lit=false;if(this.hasFocus)return;if(Personalize.isIe()){this.domElement.setStyle({backgroundColor:'#EFF9FE'});}else{this.currentEffect=new Effect.Morph(this.domElement,{style:'background: #EFF9FE',duration:0.5});}
this.panelTextbox.lightDown();}}
var PersonalizePhotoTray=function(){this.domElement=null;this.photos=null;this.photoElements=[];this.mainElement=null;this.trayArea=null;this.trayAreaContainer=null;this.trayWidth=0;this.trayPosition=0;this.width=576;this.loading=false;this.loaded=false;this.populateOnLoad=false;this.containerElement=null;this.headerElement=null;this.footerElement=null;this.countElement=null;this.addElement=null;this.reflections=false;this.height=(this.reflections)?100:70;}
PersonalizePhotoTray.prototype={removePhoto:function(photo){for(var i=0;i<this.photos.length;i++){if(photo==this.photos[i]){var photoId=this.photos[i].id;var thumbId=this.photos[i].thumbId;$(thumbId).fade({duration:0.5,afterFinish:function(){this.trayWidth-=80;this.trayArea.setStyle({width:this.trayWidth+'px'});this.scrollToEnd();}.bind(this)});this.photos.splice(i,1);this.countElement.update('<b>Photo Tray</b> | '+this.photos.length+' photo'+((this.photos.length>1||this.photos.length==0)?'s':'')+' uploaded');for(var i=0;i<Personalize.activeStep.photos.length;i++){var persPhoto=Personalize.activeStep.photos[i];if(persPhoto.photo.contentPhotoId==photoId){persPhoto.swapPhoto(null);}}
new Ajax.Request(Personalize.hosts.imagesProxy+'personalize/photo/'+photoId,{method:'post',parameters:{'delete':1},onSuccess:function(transport){}.bind(this),onFailure:function(){}.bind(this),onException:function(){}.bind(this)});return;}}},render:function(parentElement){parentElement.update('');this.containerElement=new Element('div',{'class':'photoTrayContainer',style:'width : '+this.width+'px;'});this.mainElement=new Element('div',{style:'width: '+this.width+'px; height: '+this.height+'px; position: relative;'});this.leftButton=new Element('div',{style:'float:left;margin-left:3px;margin-right:10px;margin-top:33px;','class':'sprite-btn-scroll-left clickable'}).update('');this.rightButton=new Element('div',{style:'float:left;margin-left:10px;margin-right:3px;margin-top:33px;','class':'sprite-btn-scroll-right clickable'}).update('');this.leftButton.observe('click',this.scrollRight.bindAsEventListener(this));this.rightButton.observe('click',this.scrollLeft.bindAsEventListener(this));var shim=76;if(Personalize.ie6)shim=82;this.trayAreaContainer=new Element('div',{style:'overflow: hidden; width: '+(this.width-shim)+'px; height: '+this.height+'px; float:left; position:relative;'});this.trayArea=new Element('div',{id:'PhotoTrayArea',style:'height: '+this.height+'px; position:relative; width:0px'});this.trayAreaContainer.insert(this.trayArea);this.mainElement.insert(this.leftButton);this.mainElement.insert(this.trayAreaContainer);this.mainElement.insert(this.rightButton);this.headerElement=new Element('div',{'class':'photoTrayHeader',align:'left'});this.countElement=new Element('div',{'class':'photoTrayCounter'}).update('<b>Photo Tray</b> | Loading photos..');this.addElement=new Element('div',{'class':'clickable wpdBlueFont'});var addButton=new Element('div',{'class':'sprite-btn-plus',style:'float:left; margin-right:4px;'});this.addElement.observe('click',this.uploadPhoto.bind(this));var addText=new Element('div').update('Add or Remove Photos');this.addElement.insert(addButton);this.addElement.insert(addText);this.headerElement.insert(this.countElement);this.headerElement.insert(this.addElement);this.countElement.setStyle({width:(this.width-160)+'px'});this.footerElement=new Element('div',{'class':'photoTrayFooter'});this.containerElement.insert(this.headerElement);this.containerElement.insert(this.mainElement);this.containerElement.insert(this.footerElement);this.populate();parentElement.insert(this.containerElement);},uploadPhoto:function(){Personalize.activeStep.uploadPhotos();},addPhoto:function(photo){this.photos.push(photo);this.addThumb(photo);},renderThumbs:function(){this.countElement.update('<b>Photo Tray</b>');this.trayArea.update('');for(var i=0;i<this.photos.length;i++){var photo=this.photos[i];this.addThumb(photo);}},requestPhotos:function(){if(this.loading||this.loaded)return;this.loading=true;new Ajax.Request(Personalize.hosts.imagesProxy+'personalize/photos.json',{method:'get',onSuccess:function(transport){this.loading=false;this.loaded=true;this.photos=transport.responseJSON;if(this.populateOnLoad){this.populate();}else{this.preloadThumbs();}}.bind(this)});},addThumb:function(photo){var thumbImg=new Image();thumbImg.onload=function(){try{$(this).up().setStyle({'top':(60-this.getHeight())+'px','position':'relative'});$(this).next().setStyle({'top':this.getHeight()-20+'px','left':this.getWidth()-24+'px'});$(this).setStyle({'left':((60-this.getWidth())/2)+'px','position':'relative'});if(this.reflections){var reflectImg=Personalize.activeStep.photoTray.getReflectedElement(this);}else{this.style.display='block';}
$(this).addClassName('imageDraggable');$(this).photo=photo;Effect.Appear(this.up().identify(),{duration:0.5});new SuperDraggable(this,{ghosting:true,revert:true,scroll:window,reverteffect:Personalize.effects.reverts.instantRevert});}catch(e){}};thumbImg.style.display='none';thumbImg.reflections=this.reflections;thumbImg.src=this.getPhotoThumbUrl(photo);var innerThumb=new Element('div',{style:'height: 140px; position:relative; width: 60px;'}).update(thumbImg);var checkBox=new Element('div',{style:'position: absolute; left:0px; top:0px;','class':'sprite-photo-checkmark'});checkBox.hide();innerThumb.insert(checkBox);var thumb=new Element('div',{'class':'imageDraggable moveable',style:'margin:10px; float:left; '}).update(innerThumb);var id=thumb.identify();photo.thumbId=id;photo.thumbCheckId=checkBox.identify();this.trayWidth+=80;this.trayArea.setStyle({width:this.trayWidth+'px'});this.countElement.update('<b>Photo Tray</b> | '+this.photos.length+' photo'+((this.photos.length>1)?'s':'')+' uploaded');this.trayArea.insert(thumb);},getReflectedElement:function(image){var d=document.createElement('div');var p=image;var options={"height":0.5,"opacity":0.5}
var classes=p.className.split(' ');var newClasses='';for(j=0;j<classes.length;j++){if(classes[j]!="reflect"){if(newClasses){newClasses+=' '}
newClasses+=classes[j];}}
var reflectionHeight=Math.floor(p.height*options['height']);var divHeight=Math.floor(p.height*(1+options['height']));var reflectionWidth=p.width;if(document.all&&!window.opera){d.className=newClasses;p.className='reflected';d.style.cssText=p.style.cssText;p.style.cssText='vertical-align: bottom';var reflection=document.createElement('img');reflection.src=p.src;reflection.style.width=reflectionWidth+'px';reflection.style.display='block';reflection.style.height=p.height+"px";reflection.style.marginBottom="-"+(p.height-reflectionHeight)+'px';reflection.style.filter='flipv progid:DXImageTransform.Microsoft.Alpha(opacity='+(options['opacity']*100)+', style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy='+(options['height']*100)+')';d.style.width=reflectionWidth+'px';d.style.height=divHeight+'px';p.parentNode.replaceChild(d,p);d.appendChild(p);d.appendChild(reflection);}else{var canvas=document.createElement('canvas');if(canvas.getContext){d.className=newClasses;p.className='reflected';d.style.cssText=p.style.cssText;p.style.cssText='vertical-align: bottom';var context=canvas.getContext("2d");canvas.style.height=reflectionHeight+'px';canvas.style.width=reflectionWidth+'px';canvas.height=reflectionHeight;canvas.width=reflectionWidth;d.style.width=reflectionWidth+'px';d.style.height=divHeight+'px';p.parentNode.replaceChild(d,p);d.appendChild(p);d.appendChild(canvas);context.save();context.translate(0,image.height-1);context.scale(1,-1);context.drawImage(image,0,0,reflectionWidth,image.height);context.restore();context.globalCompositeOperation="destination-out";var gradient=context.createLinearGradient(0,0,0,reflectionHeight);gradient.addColorStop(1,"rgba(255, 255, 255, 1.0)");gradient.addColorStop(0,"rgba(255, 255, 255, "+(1-options['opacity'])+")");context.fillStyle=gradient;context.rect(0,0,reflectionWidth,reflectionHeight*2);context.fill();}}
return d;},getPhotoThumbUrl:function(photo){return Personalize.hosts.images+'personalize/photo/'+photo.id+'/width/70/height/70.jpg';},getPhotoList:function(){return this.photos;},scrollLeft:function(){var trayRightSide=this.trayPosition+this.trayWidth;var availableWidth=this.width-40;if(trayRightSide>availableWidth){this.trayPosition-=80;var needed=this.trayAreaContainer.getWidth()-this.trayWidth;if(this.trayPosition<needed)this.trayPosition=needed;new Effect.Morph(this.trayArea,{style:'left:'+this.trayPosition+'px',duration:0.2});}},scrollRight:function(){if(this.trayPosition<0){this.trayPosition+=80;if(this.trayPosition>0)this.trayPosition=0;new Effect.Morph(this.trayArea,{style:'left:'+this.trayPosition+'px',duration:0.2});}},scrollToStart:function(){new Effect.Morph(this.trayArea,{style:'left:0px',duration:0.2});},scrollToEnd:function(){var availableWidth=this.trayAreaContainer.getWidth();if((availableWidth-this.trayWidth)>0){return;}
this.trayPosition=(availableWidth-this.trayWidth);new Effect.Morph(this.trayArea,{style:'left:'+this.trayPosition+'px',duration:0.5});},populate:function(){if(!this.loaded){this.requestPhotos();}
if(this.loading){this.populateOnLoad=true;return;}
this.renderThumbs();},preloadThumbs:function(){for(var i=0;i<this.photos.length;i++){var photo=this.photos[i];var thumb=new Image();thumb.src=this.getPhotoThumbUrl(photo);}},getPhotoCount:function(){return this.photos.length;},updateUsedThumbs:function(){for(var j=0;j<this.photos.length;j++){$(this.photos[j].thumbCheckId).hide();}
for(var i in Personalize.activeStep.photos){var photo=Personalize.activeStep.photos[i].photo;if(photo){if(photo.contentPhotoId){for(var j in this.photos){if(photo.contentPhotoId==this.photos[j].id){$(this.photos[j].thumbCheckId).show();}}}}}}}
var PersonalizePhoto=function(photo,productPhoto,resolution){this.photo=photo;this.handle=null;this.error=false;this.productPhoto=productPhoto;this.userPhoto=null
this.resolution=resolution;this.domElement=null;this.savedPhoto=null;this.editor=null;this.displayWidth=null;this.displayHeight=null;this.displayX=null;this.displayY=null;this.errorView=null;this.errorFader=null;this.orientation=null;this.imgElement=null;this.errorString='<div class="sprite-icon-warning-small-red" style="float:left"></div> This photo is low resolution and may not print well for this product.';}
PersonalizePhoto.prototype={render:function(parentElement){this.displayX=Personalize.roundForRendering(Personalize.resolutionConvert(this.photo.x,144,this.resolution));this.displayY=Personalize.roundForRendering(Personalize.resolutionConvert(this.photo.y,144,this.resolution));this.displayWidth=Personalize.roundForRendering(Personalize.resolutionConvert(this.photo.width,144,this.resolution));this.displayHeight=Personalize.roundForRendering(Personalize.resolutionConvert(this.photo.height,144,this.resolution));if(typeof this.photo.scaledWidth==='undefined'&&typeof this.photo.scaledHeight==='undefined'){this.photo.scaledWidth=this.displayWidth;this.photo.scaledHeight=this.displayHeight;}
if(this.photo.rotation==90||this.photo.rotation==270){var t=this.photo.scaledWidth;this.photo.scaledWidth=this.photo.scaledHeight;this.photo.scaledHeight=t;}
var borderSize=0;if(this.photo.frameColorId){var border='border:'+Personalize.roundForRendering(Personalize.resolutionConvert(this.photo.frameWidth,144,this.resolution))+'px '+this.photo.frameStyle+' #'+Personalize.product.fontColors[this.photo.frameColorId].rgb;var borderSize=Personalize.roundForRendering(Personalize.resolutionConvert(this.photo.frameWidth,144,this.resolution));}
this.domElement=new Element('div',{style:'z-index: '+((++Personalize.photoZIndex)+parseFloat(this.photo.z))+'; background:#FFF; overflow:hidden; position: absolute; top: '+this.displayY+'px; left: '+this.displayX+'px; width:'+this.displayWidth+'px; height: '+this.displayHeight+'px;'});this.borderX=this.displayX-(borderSize/2);this.borderY=this.displayY-(borderSize/2);this.borderWidth=this.displayWidth-borderSize;this.borderHeight=this.displayHeight-borderSize;this.borderElement=new Element('div',{style:'z-index: '+((++Personalize.photoZIndex)+parseFloat(this.photo.z))+'; '+border+' ; overflow:hidden; position: absolute; top: '+this.borderY+'px; left: '+this.borderX+'px; width:'+this.borderWidth+'px; height: '+this.borderHeight+'px;'});this.handleX=(this.displayX<0)?0:this.displayX;this.handleY=(this.displayY<0)?0:this.displayY;this.handleWidth=(this.displayX<0)?this.displayWidth+this.displayX:this.displayWidth+1;this.handleHeight=(this.displayY<0)?this.displayHeight+this.displayY:this.displayHeight+1;var handleId='handle_'+(++Personalize.handleZIndex);this.handleElement=new Element('div',{id:handleId,style:'background: url('+Personalize.hosts['static']+'image/blank.gif) repeat; overflow:hidden; z-index: '+(++Personalize.handleZIndex)+'; position: absolute; top: '+this.handleY+'px; left: '+this.handleX+'px; width:'+this.handleWidth+'px; height: '+this.handleHeight+'px;','class':'clickable'});this.errorView=new Element('div',{style:'position: absolute; top:0px;left:0px;border:2px solid red; width:'+Math.floor(this.handleWidth-4)+'px; height:'+Math.floor(this.handleHeight-4)+'px'});this.errorView.identify();this.errorFader=new Element('div',{style:'padding-left:3px; padding-right:3px; position:absolute;top:0px;left:0px;width:'+Math.floor(this.handleWidth-8)+'px;height:45px;background-color:red;font-family:Helvetica;font-size:12px;font-weight:bold;color:white'}).update(this.errorString);this.errorFader.identify();this.errorFader.hide();this.errorView.hide();this.errorView.insert(this.errorFader);this.hintButton=new Element('div',{align:'center'}).update('<div class="sprite-btn-click-edit"></div>');this.hintButton.setStyle({position:'relative',top:(this.handleHeight-40)+'px',left:'0px',width:'100%'});this.hintButton.hide();this.handleElement.observe('mouseover',this.errorOverlayOn.bindAsEventListener(this));this.handleElement.observe('mouseout',this.errorOverlayOff.bindAsEventListener(this));this.orientation=(this.displayWidth/this.displayHeight);this.checkErrors();this.renderPhoto();Droppables.add(this.handleElement,{accept:'imageDraggable',hoverClass:'dropTarget',onDrop:function(element){this.swapPhoto(element.photo);}.bind(this)});parentElement.insert(this.domElement);parentElement.insert(this.borderElement);parentElement.insert(this.handleElement);},changeColor:function(newColor){try{this.productPhoto.color=this.productPhoto.colors[newColor];this.photo.frameColorId=this.productPhoto.color.frameColorId;this.photo.overlayImageId=this.productPhoto.color.overlayImageId;if(this.photo.frameColorId){var border=Personalize.roundForRendering(Personalize.resolutionConvert(this.photo.frameWidth,144,this.resolution))+'px '+this.photo.frameStyle+' #'+Personalize.product.fontColors[this.photo.frameColorId].rgb;var borderSize=Personalize.roundForRendering(Personalize.resolutionConvert(this.photo.frameWidth,144,this.resolution));this.borderElement.setStyle({'border':border});}}catch(e){}},errorOverlayOn:function(ev){if(this.photo.contentPhotoId)
this.hintButton.show();if(this.error){this.errorFader.setStyle({display:'block'});this.errorFader.update(this.errorString);}},errorOverlayOff:function(ev){if(this.photo.contentPhotoId)
this.hintButton.hide();if(this.error){this.errorFader.setStyle({display:'none'});}},renderPhoto:function(){this.domElement.update('');this.handleElement.insert(this.hintButton);this.handleElement.insert(this.errorFader);this.handleElement.insert(this.errorView);if(this.photo.contentPhotoId){this.imgElement=new Element('img',{width:this.domElement.getWidth(),height:this.domElement.getHeight(),src:this.getPhotoUrl()});this.handleElement.stopObserving('click');this.handleElement.observe('click',this.openEditor.bindAsEventListener(this));}else{var numPhotos=0;try{numPhotos=Personalize.activeStep.photoTray.getPhotoCount()}catch(e){}
var text=(numPhotos>0)?"Drag and drop photos here":"Click here to add photos";this.imgElement=new Element('img',{src:this.getNoPhotoUrl(text)});this.handleElement.stopObserving('click');this.handleElement.observe('click',this.requestUpload.bindAsEventListener(this));this.clearError();}
this.imgElement.observe('load',this.imgLoad.bind(this));this.domElement.insert(this.imgElement);},imgLoad:function(){},swapPhoto:function(photo){if(!photo){this.photo.contentPhotoId=null;this.photo.scaledHeight=null;this.photo.scaledWidth=null;this.photo.cropX=null;this.photo.cropY=null;this.photo.cropWidth=null;this.photo.cropHeight=null;this.photo.effectId=null;this.photo.rotation=null;this.checkErrors();this.renderPhoto();Personalize.activeStep.photoTray.updateUsedThumbs();return;}
this.userPhoto=photo;this.photo.contentPhotoId=photo.id;var photoOrientation=photo.width/photo.height;if(this.orientation>photoOrientation){this.photo.scaledWidth=this.displayWidth;this.photo.scaledHeight=0;var photoScaling=this.userPhoto.width/this.photo.scaledWidth;this.photo.cropHeight=this.displayHeight*(photoScaling);this.photo.cropY=(this.userPhoto.height-this.photo.cropHeight)/2;this.photo.cropX=0;this.photo.cropWidth=this.displayWidth*(photoScaling);this.photo.effectId=null;this.photo.rotation=null;}else{this.photo.scaledHeight=(this.displayHeight);this.photo.scaledWidth=0;var photoScaling=this.userPhoto.height/this.photo.scaledHeight;this.photo.cropWidth=this.displayWidth*(photoScaling);this.photo.cropX=(this.userPhoto.width-this.photo.cropWidth)/2;this.photo.cropY=0;this.photo.cropHeight=this.displayHeight*(photoScaling);this.photo.effectId=null;this.photo.rotation=null;}
this.checkErrors();this.renderPhoto();Personalize.activeStep.photoTray.updateUsedThumbs();},openEditor:function(){if(this.editor){delete this.editor;}
if(!this.userPhoto){try{if(this.photo.contentPhotoId){var photos=Personalize.activeStep.photoTray.getPhotoList();for(var i=0;i<photos.length;i++){if(photos[i].id==this.photo.contentPhotoId){this.userPhoto=photos[i];}}}}catch(e){}}
this.editor=new PersonalizePhotoEditor(this.photo,this.productPhoto,this.userPhoto,this.resolution,this);this.editor.callback=this.editorDone.bind(this);this.editor.popupEditor();},editorDone:function(){this.renderPhoto();},requestUpload:function(){Personalize.activeStep.uploadPhotos(this);},getPhotoUrl:function(){var url=Personalize.hosts.images+'personalize';var parameters={photo:this.photo.contentPhotoId};if(this.photo.cropX)parameters.cropX=this.photo.cropX;if(this.photo.cropY)parameters.cropY=this.photo.cropY;if(this.photo.cropWidth)parameters.cropWidth=this.photo.cropWidth;if(this.photo.cropHeight)parameters.cropHeight=this.photo.cropHeight;if(this.photo.scaledWidth!=null)parameters.scaledWidth=this.photo.scaledWidth;if(this.photo.scaledHeight!=null)parameters.scaledHeight=this.photo.scaledHeight;if(this.photo.effectId==Personalize.IMAGE_EFFECT_GRAYSCALE){parameters.effects='grayscale';}
if(this.photo.effectId==Personalize.IMAGE_EFFECT_SEPIA){parameters.effects='sepia';}
if(this.photo.rotation){parameters.rotate=this.photo.rotation;}
for(var key in parameters){url+='/'+key+'/'+parameters[key];}
return url+'.jpg';},getNoPhotoUrl:function(text){var fontSize=14;if(this.displayWidth<100||this.displayHeight<100){fontSize=5;}else if(this.displayWidth<200||this.displayHeight<200){fontSize=12;}
var parameters={width:this.displayWidth,height:this.displayHeight,resolution:this.resolution,fontName:'NeutraText',fontSize:fontSize,fontColor:'000',stroke:0,tracking:0,leading:0,verticalAlignment:'center',horizontalAlignment:'center',text:encodeURIComponent(text)};var url=Personalize.hosts.images+'personalize/textbox/restrictSize/0';for(var key in parameters){url+='/'+key+'/'+parameters[key];}
return url+'.png';},hasError:function(){return this.error;},checkErrors:function(){if(this.userPhoto===null){this.clearError();return;}
if((parseFloat(this.userPhoto.width)<parseFloat(this.productPhoto.minimumWidth))||(parseFloat(this.userPhoto.height)<parseFloat(this.productPhoto.minimumHeight))){this.setError();}else{this.clearError();}},setError:function(){this.error=true;this.errorView.show();Personalize.activeStep.setError();},clearError:function(){if(this.error){this.errorOverlayOff();this.error=false;this.errorView.hide();Personalize.activeStep.clearError();}}}
var PersonalizeOverlay=function(overlay,resolution){this.overlay=overlay;this.productOverlay=Personalize.product.panels[Personalize.activeStep.currentPanel.panelId].overlays[overlay.overlayId];this.domElement=null;this.resolution=resolution;}
PersonalizeOverlay.prototype={changeColor:function(newColor){try{this.overlay.imageId=this.productOverlay.colors[newColor].imageId;this.setOverlayImage();}catch(e){}},render:function(parentElement){this.width=Personalize.roundForRendering(Personalize.resolutionConvert(parseFloat(this.overlay.width),144,this.resolution))-1;this.height=Personalize.roundForRendering(Personalize.resolutionConvert(parseFloat(this.overlay.height),144,this.resolution))-1;this.domElement=new Element('div',{'class':'personalizeOverlay'});this.domElement.setStyle({position:'absolute',top:Personalize.roundForRendering(Personalize.resolutionConvert(this.overlay.y,144,this.resolution))+1+'px',left:Personalize.roundForRendering(Personalize.resolutionConvert(this.overlay.x,144,this.resolution))+'px',width:this.width+'px',height:this.height+'px',zIndex:(++Personalize.overlayZIndex)});this.setOverlayImage();parentElement.insert(this.domElement);},setOverlayImage:function(){var overlayImageUrl=Personalize.hosts.images+'image/overlay/'+this.overlay.imageId+'/resolution/'+this.resolution+'/width/'+this.width+'/height/'+this.height+'.png';if(Personalize.ie6){this.domElement.setStyle({background:'',filter:'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="'+encodeURI(overlayImageUrl)+'", sizingMethod="crop")'});}else{this.domElement.setStyle({background:'transparent url('+overlayImageUrl+') no-repeat left top'});}}}
var PersonalizeSeparator=function(separator,resolution){this.separator=separator;this.domElement=null;this.resolution=resolution;}
PersonalizeSeparator.prototype={render:function(parentElement){var top=Personalize.roundForRendering(Personalize.resolutionConvert(parseFloat(this.separator.y),144,this.resolution));var left=Personalize.roundForRendering(Personalize.resolutionConvert(parseFloat(this.separator.x),144,this.resolution));var width=Personalize.roundForRendering(Personalize.resolutionConvert(parseFloat(this.separator.width),144,this.resolution));var height=Personalize.roundForRendering(Personalize.resolutionConvert(parseFloat(this.separator.height),144,this.resolution));if(typeof top=='undefined')top=0;if(typeof left=='undefined')left=0;if(width>height){height=1;}else{width=1;}
this.domElement=new Element('div');this.domElement.identify();this.domElement.setStyle({'position':'absolute','top':top+'px','left':left+'px','width':width+'px','height':height+'px',backgroundColor:'#EAEAEA'});parentElement.insert(this.domElement);}}
var PersonalizePhotoEditor=function(photo,productPhoto,userPhoto,resolution,panelPhoto){this.panelPhoto=panelPhoto;this.productPhoto=productPhoto;this.userPhoto=userPhoto;this.photo=photo;this.savedPhoto=Object.clone(this.photo);this.resolution=resolution;this.dialog=null;this.photoPane=null;this.zoomLevel=0;this.moveStep=5;this.zoomStep=0.1;this.zoomSmallStep=0.01;this.photoStartWidth=null;this.photoStartHeight=null;this.photoStartX=null;this.photoStartY=null;this.commandButtonsContainer=null;this.loader=null;this.displayWidth=Personalize.resolutionConvert(this.photo.width,144,this.resolution);this.displayHeight=Personalize.resolutionConvert(this.photo.height,144,this.resolution);this.maxPhotoWidth=(userPhoto.width*this.displayWidth)/productPhoto.minimumWidth;this.maxPhotoHeight=(userPhoto.height*this.displayHeight)/productPhoto.minimumHeight;this.rotation=0;}
PersonalizePhotoEditor.prototype={popupEditor:function(){if(!this.dialog){this.dialog=new PersonalizePopup('Photo Editor','photoEditor');}
this.dialog.callback=this.closeCallback.bind(this);this.dialogElement=this.dialog.getPopupElement();this.dialogElement.setStyle({position:'relative'});this.controlPane=new Element('div',{'class':'photoEditorControls'});this.photoPane=new Element('div',{'class':'photoEditorPhotoArea'});this.photoContainer=new Element('div');this.photoElement=new Element('img');var zoomIn=new Element('div',{'class':'photoEditorButton zoomIn clickable'}).update('<div class="sprite-btn-zoom-in photoEditorButtonIcon"></div>zoom in');zoomIn.onclick=this.photoZoomIn.bind(this);var zoomOut=new Element('div',{'class':'photoEditorButton zoomOut clickable'}).update('<div class="sprite-btn-zoom-out photoEditorButtonIcon"></div>zoom out');zoomOut.onclick=this.photoZoomOut.bind(this);var zoomButtons=new Element('div',{'class':'photoEditorZoomContainer'});zoomButtons.insert(new Element('div',{align:"center"}).insert(zoomIn));zoomButtons.insert(new Element('div',{align:"center"}).insert(zoomOut));var moveUp=new Element('div',{'class':'moveUp clickable'}).update('<div class="sprite-btn-move-up"></div>');moveUp.onclick=this.photoMoveUp.bind(this);var moveDown=new Element('div',{'class':'moveDown clickable'}).update('<div class="sprite-btn-move-down"></div>');moveDown.onclick=this.photoMoveDown.bind(this);var moveLeft=new Element('div',{'class':'moveLeft clickable'}).update('<div class="sprite-btn-move-left"></div>');moveLeft.onclick=this.photoMoveLeft.bind(this);var moveRight=new Element('div',{'class':'moveRight clickable'}).update('<div class="sprite-btn-move-right"></div>');moveRight.onclick=this.photoMoveRight.bind(this);var moveText=new Element('div',{'class':'moveText'}).update('move');var moveButtons=new Element('div',{'class':'photoEditorMoveContainer'});moveButtons.insert(moveUp);moveButtons.insert(moveDown);moveButtons.insert(moveLeft);moveButtons.insert(moveRight);var rotateLeft=new Element('div',{'class':'photoEditorButton rotateLeft clickable'}).update('<div class="sprite-btn-rotate-left photoEditorButtonIcon"></div>rotate left');rotateLeft.onclick=this.photoRotateLeft.bind(this);var rotateRight=new Element('div',{'class':'photoEditorButton rotateRight clickable'}).update('<div class="sprite-btn-rotate-right photoEditorButtonIcon"></div>rotate right');rotateRight.onclick=this.photoRotateRight.bind(this);var rotateButtons=new Element('div',{'class':'photoEditorRotateContainer'});rotateButtons.insert(new Element('div',{align:"center"}).insert(rotateLeft));rotateButtons.insert(new Element('div',{align:"center"}).insert(rotateRight));var fxSepia=new Element('div',{'class':'photoEditorButton fxSepia clickable'}).update('<div class="sprite-btn-effect-sepia photoEditorLgButtonIcon"></div>sepia');fxSepia.onclick=this.photoFxSepia.bind(this);var fxGray=new Element('div',{'class':'photoEditorButton fxGrayscale clickable'}).update('<div class="sprite-btn-effect-grayscale photoEditorLgButtonIcon"></div>b&amp;w');fxGray.onclick=this.photoFxGray.bind(this);var fxNone=new Element('div',{'class':'photoEditorButton fxOriginal clickable'}).update('<div class="sprite-btn-effect-original photoEditorLgButtonIcon"></div>original');fxNone.onclick=this.photoFxNone.bind(this);var fxButtons=new Element('div',{'class':'photoEditorFxContainer'});fxButtons.insert(new Element('div',{align:"center"}).insert(fxNone));fxButtons.insert(new Element('div',{align:"center"}).insert(fxGray));fxButtons.insert(new Element('div',{align:"center"}).insert(fxSepia));var apply=new Element('div',{'class':'photoEditorCmdButton cmdApply clickable'}).update('<div class="sprite-btn-accept photoEditorButtonIcon"></div>');apply.onclick=this.applyEdits.bind(this);var cancel=new Element('div',{'class':'photoEditorCmdButton cmdCancel clickable'}).update('<div class="sprite-btn-cancel photoEditorButtonIcon"></div>');cancel.onclick=this.cancelEdits.bind(this);var remove=new Element('div',{'class':'photoEditorCmdButton cmdRemove clickable',style:'margin-top:6px;margin-right:10px;width:120px;'}).update('<div style="float:right; font-family:helvetica; font-size:11px;">&nbsp; Remove Photo</div><div class="sprite-icon-remove-photo photoEditorButtonIcon" style="float:right; margin-top: -10px;"></div>');;remove.onclick=this.removePhotoAndClose.bind(this);var cmdButtons=new Element('div',{'align':'right','class':'photoEditorCmdContainer'});cmdButtons.setStyle({width:'320px'});cmdButtons.insert(apply);cmdButtons.insert(cancel);cmdButtons.insert(remove);cmdButtons.insert(new Element('div',{style:'clear:both'}));this.commandButtonsContainer=cmdButtons;this.photoContainer.insert(this.photoElement);this.photoPane.insert(this.photoContainer);this.controlPane.insert(zoomButtons);this.controlPane.insert(new Element('div',{align:"center"}).insert(moveButtons));this.controlPane.insert(rotateButtons);this.controlPane.insert(fxButtons);this.photoPane.insert(cmdButtons);this.photoPane.insert(new Element('div',{style:'clear:both'}));this.dialogElement.insert(this.controlPane);this.dialogElement.insert(this.photoPane);this.dialogElement.insert(new Element('div',{style:'clear:both'}));this.initPhotoPane();this.dialogElement.setStyle({width:(this.controlPane.getWidth()+this.photoPane.getWidth())+'px'});this.dialog.showPopup();Event.observe(document,"mousewheel",this.handleWheel.bind(this),false);Event.observe(document,"DOMMouseScroll",this.handleWheel.bind(this),false);},handleWheel:function(event){if(Event.wheel(event)>0){this.photoZoomIn();}else{this.photoZoomOut();}
Event.stop(event);},closeCallback:function(){this.cancelEdits();this.dialog.destroy();Event.stopObserving(document,"mousewheel");Event.stopObserving(document,"DOMMouseScroll");},getPhotoUrl:function(){var url=Personalize.hosts.images+'personalize';var parameters={photo:this.photo.contentPhotoId};if(this.photo.effectId){if(this.photo.effectId==Personalize.IMAGE_EFFECT_GRAYSCALE){parameters.effects='grayscale';}
if(this.photo.effectId==Personalize.IMAGE_EFFECT_SEPIA){parameters.effects='sepia';}}
if(this.photo.rotation){parameters.rotate=this.photo.rotation;}
for(var key in parameters){url+='/'+key+'/'+parameters[key];}
return url+'.jpg';},reloadPhoto:function(){this.photoElement.src=this.getPhotoUrl();if(this.rotation!=this.photo.rotation){this.rotation=this.photo.rotation;var curWidth=this.photoElement.getWidth();var curHeight=this.photoElement.getHeight();this.photoElement.setStyle({width:curHeight+'px',height:curWidth+'px'});}},initPhotoPane:function(){this.photoContainer.setStyle({width:this.displayWidth+'px',height:this.displayHeight+'px',overflow:'hidden',position:'relative'});this.photoElement.src=this.getPhotoUrl();if(!this.photo.rotation){this.photo.rotation=0;}
this.photoStartRotation=this.photo.rotation;if(this.photo.rotation==90||this.photo.rotation==270){if(this.photo.cropHeight){var elemScaling=this.displayHeight/this.photo.cropWidth;}else{var elemScaling=this.displayWidth/this.photo.cropHeight;}}else{if(this.photo.cropHeight){var elemScaling=this.displayHeight/this.photo.cropHeight;}else{var elemScaling=this.displayWidth/this.photo.cropWidth;}}
switch(this.photo.rotation){case 0:this.photoStartHeight=this.userPhoto.height*elemScaling;this.photoStartWidth=this.userPhoto.width*elemScaling;this.photoStartX=(this.photo.cropX)?(-1)*this.photo.cropX*elemScaling:0;this.photoStartY=(this.photo.cropY)?(-1)*this.photo.cropY*elemScaling:0;break;case 90:this.photoStartWidth=this.userPhoto.height*elemScaling;this.photoStartHeight=this.userPhoto.width*elemScaling;this.photoStartX=(-1)*(this.photoStartWidth-this.displayWidth-(this.photo.cropY*elemScaling));this.photoStartY=(-1)*this.photo.cropX*elemScaling;break;case 180:this.photoStartHeight=this.userPhoto.height*elemScaling;this.photoStartWidth=this.userPhoto.width*elemScaling;this.photoStartX=(-1)*(this.photoStartWidth-this.displayWidth-(this.photo.cropX*elemScaling));this.photoStartY=(-1)*(this.photoStartHeight-this.displayHeight-(this.photo.cropY*elemScaling));break;case 270:this.photoStartWidth=this.userPhoto.height*elemScaling;this.photoStartHeight=this.userPhoto.width*elemScaling;this.photoStartX=(-1)*this.photo.cropY*elemScaling;this.photoStartY=(-1)*(this.photoStartHeight-this.displayHeight-(this.photo.cropX*elemScaling));break;}
this.photoElement.setStyle({width:this.photoStartWidth+'px',height:this.photoStartHeight+'px',left:this.photoStartX+'px',top:this.photoStartY+'px'});this.photoElement.observe('load',this.photoLoaded.bind(this));new Draggable(this.photoElement,{starteffect:null,endeffect:null,snap:this.photoDragValidate.bind(this),onEnd:this.photoSetValues.bind(this)});var bestHeight=Math.max((this.displayHeight+80),320);var bestWidth=Math.max((this.displayWidth+80),340);var leftOfs=Math.floor((bestWidth-this.displayWidth)/2);this.photoPane.setStyle({width:bestWidth+'px',height:bestHeight+'px'});this.controlPane.setStyle({position:'relative',height:bestHeight+'px'});this.photoContainer.setStyle({position:'relative',top:'30px',left:leftOfs+'px'})
var cmdPosX=(bestWidth)-this.commandButtonsContainer.getWidth()-5;var cmdPosY=bestHeight-this.commandButtonsContainer.getHeight()-5;this.commandButtonsContainer.setStyle({top:cmdPosY+'px',left:cmdPosX+'px'});},photoLoaded:function(){if(this.loader)this.loader.remove();},photoSetValues:function(){this.photoSnap();var offset=this.photoElement.positionedOffset();var top=offset.top;var left=offset.left;var width=this.photoElement.getWidth();var height=this.photoElement.getHeight();var scaleToOriginal=width/this.userPhoto.width;if(this.photo.rotation==90||this.photo.rotation==270){scaleToOriginal=height/this.userPhoto.width;}
this.photo.cropWidth=this.displayWidth/scaleToOriginal;this.photo.cropHeight=this.displayHeight/scaleToOriginal;this.photo.cropX=((-1)*left)/scaleToOriginal;this.photo.cropY=((-1)*top)/scaleToOriginal;if(this.photo.rotation){if(this.photo.rotation==90){var t=this.photo.cropWidth;this.photo.cropWidth=this.photo.cropHeight;this.photo.cropHeight=t;this.photo.cropX=((-1)*top)/scaleToOriginal;this.photo.cropY=(width-this.displayWidth+left)/scaleToOriginal;}
if(this.photo.rotation==180){this.photo.cropY=(height-this.displayHeight+top)/scaleToOriginal;this.photo.cropX=(width-this.displayWidth+left)/scaleToOriginal;}
if(this.photo.rotation==270){var t=this.photo.cropWidth;this.photo.cropWidth=this.photo.cropHeight;this.photo.cropHeight=t;this.photo.cropY=((-1)*left)/scaleToOriginal;this.photo.cropX=(height-this.displayHeight+top)/scaleToOriginal;}}},photoDragValidate:function(x,y,draggable){var loX=this.displayWidth-this.photoElement.getWidth();var hiX=0;var loY=this.displayHeight-this.photoElement.getHeight();var hiY=0;if(x>hiX)x=hiX;if(x<loX)x=loX;if(y>hiY)y=hiY;if(y<loY)y=loY;return[x,y];},photoSnap:function(){var offset=this.photoElement.positionedOffset();var newLeft=(offset.left>0)?0:offset.left;var newTop=(offset.top>0)?0:(offset.top);var safeGuard=0;while(this.photoElement.getWidth()<Personalize.roundForRendering(this.displayWidth)){this.zoomLevel+=this.zoomSmallStep;this.photoZoom(true);safeGuard++;if(safeGuard>100)return;}
safeGuard=0;while(this.photoElement.getHeight()<Personalize.roundForRendering(this.displayHeight)){this.zoomLevel+=this.zoomSmallStep;this.photoZoom(true);safeGuard++;if(safeGuard>100)return;}
if(((this.photoElement.getWidth()+offset.left)<this.displayWidth)){newLeft=-(this.photoElement.getWidth()-this.displayWidth);}
if(((this.photoElement.getHeight()+offset.top)<this.displayHeight)){newTop=-(this.photoElement.getHeight()-this.displayHeight);}
this.photoElement.setStyle({left:newLeft+'px',top:newTop+'px'});},photoZoom:function(force){var multiplier=Math.exp(this.zoomLevel);var origWidth=this.photoStartWidth;var origHeight=this.photoStartHeight;if(this.photo.rotation){if((this.photo.rotation-this.photoStartRotation)%180==90){var t=origHeight;origHeight=origWidth;origWidth=t;}}
var newWidth=origWidth*multiplier;var newHeight=origHeight*multiplier;if(!force&&newWidth>this.maxPhotoWidth)return;if(!force&&newHeight>this.maxPhotoHeight)return;if(!force&&(newWidth<this.displayWidth||newHeight<this.displayHeight))return false;var currentWidth=this.photoElement.getWidth();var currentHeight=this.photoElement.getHeight();var deltaX=newWidth-currentWidth;var deltaY=newHeight-currentHeight;var offset=this.photoElement.positionedOffset();var deltaXMulti=((-offset.left)+(this.displayWidth/2))/currentWidth;var deltaYMulti=((-offset.top)+(this.displayHeight/2))/currentHeight;var newTop=(offset.top-((deltaY)*deltaYMulti));var newLeft=(offset.left-((deltaX)*deltaXMulti));this.photoElement.setStyle({top:newTop+'px',left:newLeft+'px',width:newWidth+'px',height:newHeight+'px'});this.photoSetValues();return true;},photoZoomIn:function(){this.zoomLevel+=this.zoomStep;if(!this.photoZoom())this.zoomLevel-=this.zoomStep;},photoZoomOut:function(){this.zoomLevel-=this.zoomStep;if(!this.photoZoom())this.zoomLevel+=this.zoomStep;},photoMoveUp:function(){var offset=this.photoElement.positionedOffset();offset.top-=this.moveStep;var res=this.photoDragValidate(offset.left,offset.top);this.photoElement.setStyle({top:res[1]+'px'});this.photoSetValues();},photoMoveDown:function(){var offset=this.photoElement.positionedOffset();offset.top+=this.moveStep;var res=this.photoDragValidate(offset.left,offset.top);this.photoElement.setStyle({top:res[1]+'px'});this.photoSetValues();},photoMoveLeft:function(){var offset=this.photoElement.positionedOffset();offset.left-=this.moveStep;var res=this.photoDragValidate(offset.left,offset.top);this.photoElement.setStyle({left:res[0]+'px'});this.photoSetValues();},photoMoveRight:function(){var offset=this.photoElement.positionedOffset();offset.left+=this.moveStep;var res=this.photoDragValidate(offset.left,offset.top);this.photoElement.setStyle({left:res[0]+'px'});this.photoSetValues();},photoRotateLeft:function(){this.photoRotate(-90);},photoRotateRight:function(){this.photoRotate(90);},photoRotate:function(val){this.photo.rotation+=val;this.photo.rotation%=360;if(this.photo.rotation==-90)this.photo.rotation=270;if(this.photo.rotation==-270)this.photo.rotation=90;var t=this.photo.scaledWidth;this.photo.scaledWidth=this.photo.scaledHeight;this.photo.scaledHeight=t;this.loader=new Element('div');this.loader.setStyle({backgroundColor:'#FFF',position:'absolute',top:'0px',left:'0px',border:'1px solid #000',width:(this.displayWidth-2)+'px',height:(this.displayHeight-2)+'px'});var img=new Element('img',{src:Personalize.hosts['static']+'image/wpd/loading-bar-small.gif'});img.setStyle({position:'absolute',top:((this.displayHeight-16)/2)+'px',left:((this.displayWidth-16)/2)+'px'});this.loader.insert(img);this.photoContainer.insert(this.loader);this.reloadPhoto();this.photoSetValues();},photoFxGray:function(){this.photo.effectId=Personalize.IMAGE_EFFECT_GRAYSCALE;this.reloadPhoto();},photoFxSepia:function(){this.photo.effectId=Personalize.IMAGE_EFFECT_SEPIA;this.reloadPhoto();},photoFxNone:function(){this.photo.effectId=Personalize.IMAGE_EFFECT_NONE;this.reloadPhoto();},cancelEdits:function(){for(var prop in this.savedPhoto){this.photo[prop]=this.savedPhoto[prop];}
this.dialog.hidePopup();Event.stopObserving(document,"mousewheel");Event.stopObserving(document,"DOMMouseScroll");},applyEdits:function(){this.dialog.hidePopup();Event.stopObserving(document,"mousewheel");Event.stopObserving(document,"DOMMouseScroll");this.callback();},removePhotoAndClose:function(){this.cancelEdits();this.panelPhoto.swapPhoto();}}
var PersonalizePhotoUploader=function(){this.dialog=null;this.fileElement=null;this.formElement=null;this.containerElement=null;this.uploading=0;this.opener=null;}
PersonalizePhotoUploader.prototype={popup:function(opener){if(opener){this.opener=opener;}else{this.opener=false;}
if(!this.dialog){this.dialog=new PersonalizePopup('Photo Upload','photoUpload');this.dialog.callback=this.closeCallback.bind(this);var dialogElement=this.dialog.getPopupElement();this.containerElement=new Element('div',{align:'left',style:'width:400px; height:500px;font-family: Helvetica; font-size:12px;'});this.containerElement.insert(new Element('div',{style:'padding:6px'}).update('<b>Add photos from your computer</b><br>Find the photos you want on your computer.'));this.fileElement=new Element('input',{type:'file',name:'file'});this.formElement=new Element('form',{style:'padding:6px; margin:0px;',enctype:'multipart/form-data',encoding:'multipart/form-data',method:'post',action:Personalize.hosts.imagesProxy+'personalize/photo/'});Personalize.flexUploadApi=new FlexUploadApi();if(Personalize.flexUploadApi.isSupported()){this.formElement.insert(Personalize.flexUploadApi.getFlexUploadDom().show());}else{this.formElement.insert(this.fileElement);}
this.contentArea=new Element('div',{style:'height: 370px; overflow-y:scroll;'});var button=new Element('div',{'class':'sprite-btn_close clickable'});button.observe('click',this.dialog.hidePopup.bind(this.dialog));this.closeButton=new Element('div',{align:'right','style':'padding:8px'}).update(button);this.fileElement.observe('change',this.startUpload.bind(this));this.containerElement.insert(this.formElement);this.containerElement.insert(this.contentArea);this.containerElement.insert(this.closeButton);dialogElement.insert(this.containerElement);dialogElement.setStyle({width:'400px'});}
this.contentArea.update('');this.populate();this.dialog.showPopup();},populate:function(){var photos=Personalize.activeStep.getUserPhotos();if(photos===null)return;for(var i=0;i<photos.length;i++){var photo=photos[i];this.addPhoto(photo);}},addPhoto:function(photo){var photoElement=new Element('div',{'class':'photoUploadPhotoElem'});var photoThumb=new Element('div',{style:'width:70px; float:left',align:'center'}).update(new Element('img',{src:this.getThumbUrl(photo)}));var photoDescr=new Element('div',{align:'left',style:'float:left','class':'photoUploadPhotoDescrElem'});try{var nameLabel=new Element('div',{style:"width:90px;float:left;font-weight:bold"}).update('Name : ');var uploadedLabel=new Element('div',{style:"width:90px;float:left;font-weight:bold"}).update('Uploaded : ');var sizeLabel=new Element('div',{style:"width:90px;float:left;font-weight:bold"}).update('Size : ');var nameEl=new Element('div',{style:"width:150px;float:left;overflow:hidden;"}).update(photo.name.truncate(23));var uploadedEl=new Element('div',{style:"width:150px;float:left;overflow:hidden;"}).update(photo.uploaded);var sizeEl=new Element('div',{style:"width:150px;float:left;overflow:hidden;"}).update(photo.width+' x '+photo.height);var nameCont=new Element('div').update(nameLabel);var uploadedCont=new Element('div').update(uploadedLabel);var sizeCont=new Element('div').update(sizeLabel);nameCont.insert(nameEl);uploadedCont.insert(uploadedEl);sizeCont.insert(sizeEl);photoDescr.insert(nameCont);photoDescr.insert(uploadedCont);photoDescr.insert(sizeCont);}catch(e){}
var removeIcon=new Element('div',{align:'center','class':'sprite-btn-delete-whitebg',style:'margin-left:12px;float:left'});var removeText=new Element('div',{style:'font-size:11px;'}).update('<br>Remove');var photoRemove=new Element('div',{'class':'clickable'}).update(removeIcon);photoRemove.insert(removeText);photoRemove.observe('click',this.removePhoto.bindAsEventListener(this,photo,photoElement));photoElement.insert(photoThumb);photoElement.insert(photoDescr);photoElement.insert(photoRemove);photoElement.insert(new Element('div',{style:'clear:both'}));this.contentArea.insert({top:photoElement});},checkAddToOpener:function(photo){try{if(this.opener){if(!this.opener.photo.contentPhotoId){this.opener.swapPhoto(photo);}}}catch(e){}},removePhoto:function(ev,photo,element){element.remove();Personalize.activeStep.photoTray.removePhoto(photo);},getThumbUrl:function(photo){return Personalize.hosts.images+'personalize/photo/'+photo.id+'/width/60/height/60/shadow/1.jpg';},startUpload:function(){if(this.fileElement.value.length==0){alert('Select a file first!');return;}
if(this.maxPhotosReached()){alert('Unable to upload photo, maximum number of photos already uploaded. Please remove one or more photos if you\'d like to upload more.');return;}
var form=this.formElement;var iframeId='PhotoUploadIFrame_'+Math.round(new Date().getTime()/1000.0);var iframeElement=new Element('iframe',{id:iframeId,name:iframeId,style:'margin:0px;height:1px; width:1px; border: 0px; background-color:#FFF'});$(this.containerElement).insert(iframeElement);form.target=iframeId;var photoElement=new Element('div').update(new Element('img',{src:Personalize.hosts['static']+'image/wpd/loading-bar.gif'}));this.contentArea.insert({top:photoElement});var photoUploadedCallback=function(event,elem){try{elem.remove();var iframeContent=iframeElement.contentWindow.document.body.innerHTML;var responseComponents=iframeContent.split('/');var photoId=parseFloat(responseComponents.pop());if(photoId){new Ajax.Request(Personalize.hosts.imagesProxy+'personalize/photo/'+photoId+'.json',{method:'get',onSuccess:function(transport){var photo=transport.responseJSON;Personalize.activeStep.addPhotoToTray(photo);this.addPhoto(photo);this.checkAddToOpener(photo);}.bind(this)});}else{alert('There was an error uploading your image.'+iframeContent);}}catch(e){alert('Upload failed.');}
this.uploading--;this.photoUploadedCallback=null;setTimeout(function(){iframeElement.remove();},100);}.bindAsEventListener(this,photoElement);iframeElement.observe('load',photoUploadedCallback);form.submit();this.uploading++;form.reset();return false;},maxPhotosReached:function(){var photos=Personalize.activeStep.getUserPhotos();if(photos){var count=photos.length;}else{var count=0;}
count+=this.uploading;return(count>=20);},closeCallback:function(){this.dialog.hidePopup();}}
var PersonalizeFontPreview=function(recFontList,otherFontList){this.dialog=new PersonalizePopup('Font Choices','fontPreview');var dlgElem=this.dialog.getPopupElement();this.domElement=new Element('div',{style:'padding: 16px; width:500px; position:relative;'});dlgElem.insert(this.domElement);this.dialog.hidePopup();this.recommendedFontsElement=new Element('div');this.recommendedFontsElement.insert(new Element('div',{align:'left',style:'margin-bottom:8px;font-family: Helvetica; font-weight:bold; font-size:12px; color: #533519;'}).update('Recommended fonts for this design'));this.makeList(recFontList,this.recommendedFontsElement,1);this.otherFontsElement=new Element('div');this.makeList(otherFontList,this.otherFontsElement,3);this.domElement.insert(this.recommendedFontsElement);if(otherFontList.length>0){this.domElement.insert(new Element('div',{style:'clear: both; border-bottom:1px solid #ddd;'}));this.domElement.insert(new Element('div',{align:'left',style:'margin-bottom:8px;margin-top:4px;font-family: Helvetica; font-weight:bold; font-size:12px; color: #533519;'}).update('Other Font Options'));this.domElement.insert(new Element('div',{style:'clear: both'}));this.domElement.insert(this.otherFontsElement);}else{this.domElement.insert(new Element('div',{style:'clear: both'}));}
this.domElement.setStyle({width:'500px'});dlgElem.setStyle({width:'500px'});}
PersonalizeFontPreview.prototype={show:function(){this.dialog.showPopup();this.dialog.recenter();},makeList:function(fontIdList,element,columns){var numPerCol=Math.ceil(fontIdList.length/columns);for(var i=0;i<fontIdList.length;i++){if(i%numPerCol==0){var colElement=new Element('div',{style:'float:left; width:165px'});element.insert(colElement);}
var fontId=fontIdList[i];var font=Personalize.masterFontList[fontId];if(typeof font!=='undefined'){var fontImageUrl=Personalize.hosts.images+'personalize/textbox/restrictSize/1';var parameters={width:165,height:24,resolution:72,fontName:font.name,fontSize:13,fontColor:'000',verticalAlignment:'center',horizontalAlignment:'left',text:font.displayName}}
for(var key in parameters){fontImageUrl+='/'+key+'/'+parameters[key];}
fontImageUrl+='.png';var elem=new Element('img',{src:fontImageUrl,alt:font.displayName});colElement.insert(elem);colElement.insert('<br>');}},hide:function(){this.dialog.hidePopup();}}
var PersonalizeCustomColors=function(initialSelected){this.dialog=new PersonalizePopup('Custom Color','customColor');this.dlgElem=this.dialog.getPopupElement();this.dialog.hidePopup();this.callback=null;this.initialSelected=initialSelected;this.selectedColorElement=null;this.selectedColor=null;this.cyan=Personalize.personalization.colorCyan;this.magenta=Personalize.personalization.colorMagenta;this.yellow=Personalize.personalization.colorYellow;this.black=Personalize.personalization.colorBlack;this.swatchSize=35;this.swatchContainerSize=70;this.columns=9;this.width=this.swatchContainerSize*this.columns;this.renderColorPanel();}
PersonalizeCustomColors.prototype={show:function(callback){this.dialog.showPopup();this.dialog.recenter();this.callback=callback;},getSampleLink:function(){switch(parseFloat(Personalize.product.paperId)){case 9:case 10:case 11:case 12:case 13:return'<a href="/custom-color-options-card.php?pid=2139" target="_blank">Custom Color Palette Card for Signature Textured ECRU Paper</a>';case 14:case 15:case 16:case 17:return'<a href="/custom-color-options-card.php?pid=3684" target="_blank">Custom Color Palette Card for Signature Textured White Paper</a>';default:return'<a href="/custom-color-options-card.php?pid=540" target="_blank">Custom Color Palette Card for Signature Matte White Paper</a>';}},renderColorPanel:function(){var preSelectCustomColor=false;var col=0;var textElem=new Element('div',{align:'left',style:'margin:8px;width:'+this.width+'px;font-family: helvetica; font-size:11px;'});textElem.update('We can change any design to any color on our Custom Color Palette for an additional fee.<br /><br />We strongly recommend ordering a physical sample of our '+this.getSampleLink()+' as colors appear differently on your computer monitor or when printed by a home printer.<br /><br />To request a custom color, please click on your desired color swatch below and then click "Accept." After you personalize your design and complete your order, a Design Specialist will then email you a digital proof of the design in your specified custom color. Please note that you will not be able to see the design in your custom color during the personalization process.<br /><br />To make a special request, please use the Special Instructions box to specify what you would like to see on your card. If the Special Instructions box is blank, or if our designers have questions about your request, we will contact you to help fulfill your specific needs.');this.dlgElem.insert(textElem);this.dlgElem.setStyle({width:(this.width+20)+'px'});for(var colorId in Personalize.product.customColors){var customColor=Personalize.product.customColors[colorId];var colorElement=new Element('div',{align:'center','class':'clickable'});var colorSampleElement=new Element('div',{id:'colorSwatch_'+customColor.id});var colorSampleBorder=new Element('div',{style:'padding:4px',id:'colorSwatchBorder_'+customColor.id});colorSampleBorder.setStyle({width:this.swatchSize+'px',height:this.swatchSize+'px'});colorSampleElement.setStyle({width:this.swatchSize+'px',height:this.swatchSize+'px',backgroundColor:'#'+customColor.rgb});colorElement.setStyle({'float':'left',padding:'0px',width:this.swatchContainerSize+'px',height:this.swatchContainerSize+'px'});var colorName=(customColor.displayName)?customColor.displayName:customColor.name;var colorNameElement=new Element('div',{style:'font-family: helvetica; font-size:10px'}).update(colorName);colorElement.update(colorSampleBorder.update(colorSampleElement));colorElement.insert(colorNameElement);colorSampleElement.observe('click',this.selectColor.bindAsEventListener(this,colorSampleElement,customColor));this.dlgElem.insert(colorElement);col++;if(col%this.columns==0){this.dlgElem.insert(new Element('div',{style:'clear:both'}));}
if(this.initialSelected==customColor){preSelectCustomColor=customColor;var preSelectColorSampleElement=colorSampleElement;}}
this.dlgElem.insert(new Element('div',{style:'clear:both'}));var bottomContainer=new Element('div');this.advancedContainer=new Element('div',{'class':'advancedCustomColorContainer'});this.cyanElem=new Element('input',{type:'text',size:'3'});this.magentaElem=new Element('input',{type:'text',size:'3'});this.yellowElem=new Element('input',{type:'text',size:'3'});this.blackElem=new Element('input',{type:'text',size:'3'});if(Personalize.personalization.colorCyan!=null)this.cyanElem.value=this.pricify(Personalize.personalization.colorCyan);if(Personalize.personalization.colorMagenta!=null)this.magentaElem.value=this.pricify(Personalize.personalization.colorMagenta);if(Personalize.personalization.colorYellow!=null)this.yellowElem.value=this.pricify(Personalize.personalization.colorYellow);if(Personalize.personalization.colorBlack!=null)this.blackElem.value=this.pricify(Personalize.personalization.colorBlack);this.advancedContainer.update('<div align="left" style="margin:8px;font-size:12px; font-weight:normal"><b>Advanced Color Options</b><br/>Please provide us with the CMYK Values for your card color below.<br />We are unable to print using Pantone colors.<br /></div>')
this.advancedContainer.insert('C');this.advancedContainer.insert(this.cyanElem);this.advancedContainer.insert('%  M');this.advancedContainer.insert(this.magentaElem);this.advancedContainer.insert('%  Y');this.advancedContainer.insert(this.yellowElem);this.advancedContainer.insert('%  K');this.advancedContainer.insert(this.blackElem);this.advancedContainer.insert('%');this.cyanElem.observe('keyup',this.checkCmykSelection.bind(this));this.magentaElem.observe('keyup',this.checkCmykSelection.bind(this));this.yellowElem.observe('keyup',this.checkCmykSelection.bind(this));this.blackElem.observe('keyup',this.checkCmykSelection.bind(this));this.advancedSwitch=new Element('div',{align:'left','class':'clickable',style:'color:#3c95b4; font-size:11px; font-family:helvetica;'}).update('advanced color options >> ');var cancelButton=new Element('div',{'class':'sprite-btn-cancel clickable',style:'float:right'});var acceptButton=new Element('div',{'class':'sprite-btn-accept clickable',style:'float:right; margin-left:6px'});var commandContainer=new Element('div',{style:'margin:8px'});var commandLeftContainer=new Element('div',{align:'left',style:'margin-bottom:8px;width:'+Math.floor(this.width/2)+'px; float:left'}).update(this.advancedSwitch);var commandRightContainer=new Element('div',{align:'right',style:'margin-bottom:8px;width:'+Math.floor(this.width/2)+'px; float:left'});commandRightContainer.insert(acceptButton);commandRightContainer.insert(cancelButton);commandContainer.update(commandLeftContainer);commandContainer.insert(commandRightContainer);bottomContainer.update(this.advancedContainer);bottomContainer.insert(commandContainer);cancelButton.observe('click',this.cancel.bind(this));acceptButton.observe('click',this.accept.bind(this));this.advancedSwitch.observe('click',this.toggleAdvanced.bind(this));this.advancedContainer.hide();this.dlgElem.insert(bottomContainer);if(preSelectCustomColor){this.selectColor(null,preSelectColorSampleElement,preSelectCustomColor);}},toggleAdvanced:function(ev,el){Effect.Fade(this.advancedSwitch,{duration:0.30});Effect.BlindDown(this.advancedContainer,{duration:0.3});},selectColor:function(ev,el,color){if(this.selectedColorElement){this.selectedColorElement.up().setStyle({border:'0px solid #a7a7a7',padding:'4px'});}
el.up().setStyle({border:'2px solid #a7a7a7',padding:'2px'});this.selectedColorElement=el;this.selectedColor=color;this.cyan=color.cyan;this.magenta=color.magenta;this.yellow=color.yellow;this.black=color.black;this.cyanElem.value='';this.magentaElem.value='';this.yellowElem.value='';this.blackElem.value='';},cancel:function(){this.dialog.hidePopup();},pricify:function(val){if(val==null){return val;}else{return parseFloat(val).toFixed(2);}},checkCmykSelection:function(){if(this.selectedColorElement){this.selectedColorElement.up().setStyle({border:'0px solid #a7a7a7',padding:'4px'});}
this.cyan=this.pricify(this.cyanElem.value);this.magenta=this.pricify(this.magentaElem.value);this.yellow=this.pricify(this.yellowElem.value);this.black=this.pricify(this.blackElem.value);},selectedCmyk:function(){return(this.cyan!==null&&this.magenta!==null&&this.yellow!==null&&this.black!==null);},accept:function(){if(this.selectedCmyk()){if(this.checkValidCmyk()){this.dialog.hidePopup();if(this.callback)this.callback();}else{alert('The selected CMYK values are invalid. Values must be numeric, between 0 and 100.');}}else{alert('Please select a color');}},checkValidCmyk:function(){return(this.isValidColorValue(this.cyan)&&this.isValidColorValue(this.magenta)&&this.isValidColorValue(this.yellow)&&this.isValidColorValue(this.black));},isValidColorValue:function(val){if(val==parseFloat(val)){c=parseFloat(val);if(c>100.00||c<0.00){return false}
else{return true;}}
else{return false;}}}

var personalizeReview=new Step('reviewStep','Review');TP.extendObject(personalizeReview,{init:function(){this.name='personalizeReview';this.available=true;this.description='Please review the preview image below to make sure all the information is accurate, and that you are satisfied with the layout and design of your card.';this.panelSwitcherElementId=this.element.id+'_panelSwitcher';this.panelSwitcheroo=new PersonalizePanelSwitcher();this.panelSwitcheroo.clickCallback=this.changePanel.bind(this);this.panels=[];this.panelTitleElement=$('reviewPanelTitle');this.panelApprovalTitleElement=$('reviewPanelApproval');this.panelPreviewContainer=$('reviewImageContainer');this.currentPanelId=0;this.initialsBox=$('initials');this.currentPanel=null;this.specialInstructions=$('reviewInstructions');this.specialInstructions.observe('change',this.saveSpecialInstructions.bind(this));this.zoomBtn=$('reviewStep_zoomBtn');if(this.zoomBtn){this.zoomBtn.observe('click',this.showZoom.bind(this));$('reviewStep_zoomBtn_sprite').observe('click',this.showZoom.bind(this));}},initPanels:function(){this.panels=[];for(var i in Personalize.personalization.panels){this.panels.push(Personalize.personalization.panels[i]);if(!this.panels[(this.panels.length-1)].approved)this.panels[(this.panels.length-1)].approved=false;}},setImage:function(){var panel=this.getCurrentPanel();var productPanel=Personalize.product.panels[panel.panelId];this.personalizedPanelUrl=Personalize.hosts.images+'personalization/panel/'+panel.id;this.shadow=(!(Personalize.product.isMintTin||parseFloat(productPanel.noShadow)==1));var uri=this.personalizedPanelUrl+'/width/550/height/500'+(this.shadow?'/shadow/1':'')+'.jpg?at='+(Personalize.personalization.primaryProxy.modified||(new Date().getTime()));this.loader=new Element('div',{style:'width: 550px; height: 200px; padding-top:100px;'});this.loader.update(new Element('img',{src:Personalize.hosts['static']+'image/wpd/loading-bar.gif'}));this.loader.insert(new Element('div',{'style':'font-family:Helvetica; font-size: 12px; color: #3992B4'}).update('Loading Preview Image'));this.panelPreviewContainer.update(this.loader);this.panelPersonalizedImage=new Image();this.panelPersonalizedImage.onload=this.removeLoader.bind(this);this.panelPersonalizedImage.src=uri;},showZoom:function(){var uri=this.personalizedPanelUrl+'/width/900/height/500'+(this.shadow?'/shadow/1':'')+'.jpg?at='+(Personalize.personalization.primaryProxy.modified||(new Date().getTime()));this.zoomBox=new PersonalizeZoomBox("Zoomed Image",uri);this.zoomBox.showZoom();},removeLoader:function(){this.loader.remove();this.panelPreviewContainer.update(this.panelPersonalizedImage);},isLastPanel:function(){return(this.currentPanelId==(this.panels.length-1));},isFirstPanel:function(){return(this.currentPanelId==0);},allApproved:function(){for(var i=0;i<this.panels.length;i++){if(!this.panels[i].approved)return false;}
return true;},checkApproval:function(){if(this.initialsBox.getValue()){this.currentPanel.approvalInitial=this.initialsBox.getValue();this.currentPanel.approvalTimestamp=(new Date().getTime());this.currentPanel.approved=true;}else{this.initialsBox.setStyle({border:'2px solid red'});Effect.Pulsate(this.initialsBox,{pulses:5,duration:1.5});}},getFirstPanel:function(){this.currentPanelId=0;return this.panels[0];},getCurrentPanel:function(){return this.panels[this.currentPanelId];},getNextPanel:function(){if(this.currentPanelId==(this.panels.length-1))return false;this.currentPanelId++;return this.panels[this.currentPanelId];},getPreviousPanel:function(){if(this.currentPanelId==0)return false;this.currentPanelId--;return this.panels[this.currentPanelId];},changePanel:function(newPanel){for(var i=0;i<this.panels.length;i++){if(this.panels[i]==newPanel){this.currentPanelId=i;this.currentPanel=this.panels[i];this.setImage();continue;}}
this.initialsBox.setValue('');},renderBoxes:function(){var productPanel=Personalize.product.panels[this.currentPanel.panelId];this.panelTitleElement.update('Review '+productPanel.name);if(!this.currentPanel.approved){this.panelApprovalTitleElement.update('');this.panelApprovalTitleElement.removeClassName('approvedText');this.panelApprovalTitleElement.addClassName('notApprovedText');this.initialsBox.setValue('');}else{this.panelApprovalTitleElement.update('');this.panelApprovalTitleElement.addClassName('approvedText');this.panelApprovalTitleElement.removeClassName('notApprovedText');this.initialsBox.setValue(this.currentPanel.approvalInitial);}},activate:function(fromNext){$('saveButton').hide();if(fromNext){Personalize.services.savePersonalization(Personalize.personalization.name,this.commonActivate.bind(this,fromNext),false);}else{this.commonActivate(fromNext);}},clearInitials:function(){for(var i=0;i<this.panels.length;i++){this.panels[i].approved=false;this.panels[i].approvalInitials='';}},commonActivate:function(fromNext){if(fromNext){this.clearInitials();}
var val=Personalize.personalization.instructions;if(val==null)val='';this.specialInstructions.setValue(val);this.initialsBox.setStyle({border:'2px inset'});Personalize.setStepUrl();this.initPanels();this.currentPanel=this.getFirstPanel();this.setImage();this.panelSwitcheroo.render($(this.panelSwitcherElementId));this.panelSwitcheroo.setActivePanel(this.currentPanel);this.renderBoxes();$(this.element.id).show();},deactivate:function(){$(this.element.id).hide();return true;},next:function(){this.checkApproval();if(!this.currentPanel.approved)return false;if(!this.isLastPanel()){var panel=this.getNextPanel();this.changePanel(panel);this.panelSwitcheroo.setActivePanel(panel);this.renderBoxes();return false;}else{return true;}},back:function(){if(!this.isFirstPanel()){var panel=this.getPreviousPanel();this.changePanel(panel);this.panelSwitcheroo.setActivePanel(panel);this.renderBoxes();}else{return true;}},setError:function(){},saveSpecialInstructions:function(){Personalize.personalization.instructions=this.specialInstructions.getValue();}});

var personalizeEnvelopes=new Step('envelopesStep','Envelopes');TP.extendObject(personalizeEnvelopes,{init:function(){this.name='personalizeEnvelopes';this.description='Select the envelope type, color and liners to best match your personal style.';Personalize.envelopesCount=0;for(var envelopeId in Personalize.envelopes){Personalize.envelopesCount++;}
this.available=(Personalize.envelopesCount>0&&!Personalize.preShippedEnvelopes)?true:false;this.editors={};this.zoomBoxs={};this.envelopeImages={mailing:{},inner:{},liner:{}};this.selectedEnvelopes={mailing:null,inner:{},liner:{}};this.prettySelects={mailing:{},inner:{},liner:{}};this.visiblePrettySelects={inner:{},liner:{}};this.defaultEnvelopes={selected:{}};this.sampleImageElementId='envelopes_invitationPreview';this.praFontColorSwatches={};this.praColorSelected=false;},loadValuesFromPersonalization:function(){var returnAddress=parseFloat(Personalize.personalization.returnAddress);if(returnAddress==1){$('radioPraOn').checked=true;}else{$('radioPraOff').checked=true;}
if(typeof Personalize.personalization.returnAddressFontColorId!=="undefined"&&Personalize.personalization.returnAddressFontColorId!==null){$('praFontColorId').value=Personalize.personalization.returnAddressFontColorId;this.praColorSelected=Personalize.personalization.returnAddressFontColorId;}
var returnAddressLines=(Personalize.personalization.returnAddressText)?Personalize.personalization.returnAddressText.split('\n'):[];var returnAddressLine1Element=$('praLine1');var returnAddressLine2Element=$('praLine2');var returnAddressLine3Element=$('praLine3');var returnAddressLine4Element=$('praLine4');if(returnAddressLine1Element){returnAddressLine1Element.value=returnAddressLines[0]||'';}
if(returnAddressLine2Element){returnAddressLine2Element.value=returnAddressLines[1]||'';}
if(returnAddressLine3Element){returnAddressLine3Element.value=returnAddressLines[2]||'';}
if(returnAddressLine4Element){returnAddressLine4Element.value=returnAddressLines[3]||'';}
var returnAddressFontSelect=$('selectPraFont');if(returnAddressFontSelect){for(var i=0;i<returnAddressFontSelect.options.length;i++){var option=returnAddressFontSelect.options[i];if(option.value==Personalize.personalization.returnAddressFontId){returnAddressFontSelect.selectedIndex=i;}}}
var envelopeId=Personalize.personalization.envelopeId;var envelopePairId=Personalize.personalization.envelopePairId;var pairLinedEnvelopeId=Personalize.personalization.pairLinedEnvelopeId;var linedEnvelopeId=Personalize.personalization.linedEnvelopeId;if(envelopeId!==null&&typeof envelopeId!=='undefined'){var mailingSelectId=this.prettySelects["mailing"][Personalize.product.color.id].itemPrefix+envelopeId;this.prettySelects["mailing"][Personalize.product.color.id].select($(mailingSelectId));$('mailingEnvelopeId').value=envelopeId.replace(Personalize.product.color.id,"");}
if(envelopePairId!==null&&typeof envelopePairId!=='undefined'){var pair=Personalize.envelopesPairs[envelopePairId];$('outerEnvelopeId').value=pair.outerEnvelopeId;$('innerEnvelopeId').value=pair.innerEnvelopeId;var innerSuffix=Personalize.product.color.id+envelopeId;$('innerSuffix').value=innerSuffix;var innerSelectId=this.prettySelects["inner"][innerSuffix].itemPrefix+innerSuffix+envelopePairId;$(this.prettySelects["inner"][innerSuffix].container).show();this.prettySelects["inner"][innerSuffix].enable();this.prettySelects["inner"][innerSuffix].select($(innerSelectId));if(pairLinedEnvelopeId!==null){var linerSuffix=innerSuffix+envelopePairId;var pairLinerSelectId=this.prettySelects["liner"][linerSuffix].itemPrefix+linerSuffix+pairLinedEnvelopeId;$(this.prettySelects["liner"][linerSuffix].container).show();this.prettySelects["liner"][linerSuffix].enable();this.prettySelects["liner"][linerSuffix].select($(pairLinerSelectId));}}else{if(linedEnvelopeId!==null&&typeof linedEnvelopeId!=='undefined'){$('linerEnvelopeId').value=linedEnvelopeId;var linerSuffix=Personalize.product.color.id+envelopeId;$('linerSuffix').value=linerSuffix;var linerSelectId=this.prettySelects["liner"][linerSuffix].itemPrefix+linerSuffix+linedEnvelopeId;$(this.prettySelects["liner"][linerSuffix].container).show();this.prettySelects["liner"][linerSuffix].enable();this.prettySelects["liner"][linerSuffix].select($(linerSelectId));}}
if(Personalize.personalization.additionalEnvelopes!==null){$('qtyExtraEnvelopes').value=Personalize.personalization.additionalEnvelopes;this.pricemanager.refreshExtra();this.pricemanager.refreshTotals(false);}},getSampleImageSrc:function(height,width){for(var idx in Personalize.personalization.panels){var item=Personalize.personalization.panels[idx];var personalizationPanelId=item.id;break;}
var imgsrc=Personalize.hosts.images+'personalization/panel/'+personalizationPanelId+'/width/'+width+'/height/'+height+'/shadow/1.jpg?at='+Personalize.personalization.timestamp;return imgsrc;},activate:function(){$('radioPraOff').checked=true;$('radioInnerOff').checked=true;$('radioLinerOff').checked=true;if(elementId=="selectPraFont"){var fontId=$F('selectPraFont');var font=Personalize.masterFontList[fontId];var typeface=Personalize.masterTypefaceList[font.typefaceId];if(typeface.typeId!==null){if(typeface.type.name.toLowerCase()=="script"){scope.editors["pra_control"].showScriptWarning();}else{scope.editors["pra_control"].hideScriptWarning();}}else{scope.editors["pra_control"].hideScriptWarning();}}
$(this.sampleImageElementId).update(new Element('img',{src:this.getSampleImageSrc(450,450)}));this.pricemanager=new PriceManager();this.mailingEnvelopeOptions={};var recommendedEnvelope=false;var sortEnvelope=false;for(var colorId in Personalize.productsEnvelopes){var color=Personalize.productsEnvelopes[colorId];for(var envelopeId in color){if(typeof Personalize.envelopes[envelopeId]!=='function'&&typeof Personalize.envelopes[envelopeId]!=='undefined'){var envelope=Personalize.envelopes[envelopeId];var displayName=envelope.name;var price=envelope.price;var praAvailable=(parseFloat(envelope.returnAddress)==1)?true:false;var praSetupPrice=envelope.returnAddressSetupPrice;var praItemPrice=envelope.returnAddressPrice;var additional=(parseFloat(envelope.additional)==1)?true:false;var additionalPrice=envelope.additionalPrice;this.mailingEnvelopeOptions[envelopeId]=envelope;var productsEnvelope=color[envelopeId];if(productsEnvelope.sort=="0"){sortEnvelope=productsEnvelope;}
if(parseFloat(productsEnvelope.recommended)==1){recommendedEnvelope=productsEnvelope;}}}
var selectedEnvelope=false;if(!sortEnvelope&&!recommendedEnvelope){selectedEnvelope=null;}else if(!sortEnvelope){selectedEnvelope=recommendedEnvelope;}else if(!recommendedEnvelope){selectedEnvelope=sortEnvelope;}else{selectedEnvelope=recommendedEnvelope;}
this.defaultEnvelopes["selected"][colorId]=selectedEnvelope;}
var praEnabled=(parseFloat(Personalize.envelopes[selectedEnvelope.envelopeId].returnAddress)==1)?true:false;this.editors.pra_control=new PraEditor(this.pricemanager,{enabled:praEnabled,praWarningDomId:'praWarning',praWarningContainerDomId:'praWarningContainer'});for(var elementId in this.editors){this.editors[elementId].render();}
this.selectedEnvelopes["mailing"]=Personalize.envelopes[this.defaultEnvelopes["selected"][Personalize.personalization.productColorId].envelopeId];$('mailingEnvelopeId').value=this.defaultEnvelopes["selected"][Personalize.personalization.productColorId].envelopeId;$('innerSuffix').value=suffix;$('linerSuffix').value=suffix;var linerAvailable=false;for(var idx in Personalize.envelopes){var envelope=Personalize.envelopes[idx];var isLiner=(parseFloat(envelope.lined)==1)?true:false;if(isLiner){linerAvailable=true;break;}}
var innerAvailable=false;for(var idx in Personalize.envelopesPairs){innerAvailable=true;break;}
if(!linerAvailable){this.disableAllLinerEnvelopes();}
if(!innerAvailable){this.disableAllInnerEnvelopes();}
for(var colorId in Personalize.productsEnvelopes){var productColor=Personalize.productsEnvelopes[colorId];for(var envelopeId in productColor){var defaultEnvelopeId=colorId+this.defaultEnvelopes["selected"][colorId].envelopeId;this.prettySelects["mailing"][colorId]=new PrettySelect({selectionId:defaultEnvelopeId,container:"envelopeSelect_"+colorId,button:"envelopeButton_"+colorId,selected:"envelopeSelected_"+colorId,list:"envelopeList_"+colorId,itemPrefix:"envelopeBox_",input:"mailingEnvelopeId",onselect:this.events.onChangeMailingEnvelope.bind(this)});if(colorId==Personalize.product.color.id){this.prettySelects["mailing"][colorId].container.show();}else{this.prettySelects["mailing"][colorId].container.hide();}
if(innerAvailable){var envelope=productColor[envelopeId];var suffix=colorId+envelopeId;var pairCount=0;for(var pairId in envelope.pairs){pairCount++;}
if(pairCount>0){for(var pairId in envelope.pairs){this.prettySelects["inner"][suffix]=new PrettySelect({selectionId:null,container:"envelopeInnerSelect_"+suffix,button:"envelopeInnerButton_"+suffix,selected:"envelopeInnerSelected_"+suffix,list:"envelopeInnerList_"+suffix,itemPrefix:"envelopeInnerBox_",input:"innerEnvelopeId",enabled:($('radioInnerOn').checked)?true:false,onselect:this.events.onChangeInnerEnvelope.bind(this,suffix)});var compareSuffix=Personalize.product.color.id+this.selectedEnvelopes["mailing"].id;if(compareSuffix==suffix){$(this.prettySelects["inner"][suffix].container).show();this.visiblePrettySelects["inner"][suffix]=1;if($('radioInnerOff').checked||(!$('radioInnerOff').checked&&!$('radioInnerOn').checked)){this.prettySelects["inner"][suffix].disable();}else{this.prettySelects["inner"][suffix].enable();}}else{$(this.prettySelects["inner"][suffix].container).hide();}
for(var pairLinerId in envelope.pairs[pairId].linedEnvelopes){var pairLinedEnvelope=envelope.pairs[pairId].linedEnvelopes[pairLinerId];var pairLinedSuffix=suffix+pairId;this.prettySelects["liner"][pairLinedSuffix]=new PrettySelect({selectionId:null,container:"envelopeLinerSelect_"+pairLinedSuffix,button:"envelopeLinerButton_"+pairLinedSuffix,selected:"envelopeLinerSelected_"+pairLinedSuffix,list:"envelopeLinerList_"+pairLinedSuffix,itemPrefix:"envelopeLinerBox_",input:"linerEnvelopeId",enabled:($('radioLinerOn').checked)?true:false,onselect:this.events.onChangeLinerEnvelope.bind(this,pairLinedSuffix)});}}}else{var compareSuffix=Personalize.product.color.id+this.selectedEnvelopes["mailing"].id;if(compareSuffix==suffix){this.disableInnerEnvelopes();}}}
if(linerAvailable){var linerCount=0;for(var linerId in envelope.linedEnvelopes){linerCount++;}
if(linerCount>0){this.prettySelects["liner"][suffix]=new PrettySelect({selectionId:null,container:"envelopeLinerSelect_"+suffix,button:"envelopeLinerButton_"+suffix,selected:"envelopeLinerSelected_"+suffix,list:"envelopeLinerList_"+suffix,itemPrefix:"envelopeLinerBox_",input:"linerEnvelopeId",enabled:($('radioLinerOn').checked)?true:false,onselect:this.events.onChangeLinerEnvelope.bind(this,suffix)});var compareLinerSuffix=Personalize.product.color.id+this.selectedEnvelopes["mailing"].id;if(compareSuffix==suffix){$(this.prettySelects["liner"][suffix].container).show();this.visiblePrettySelects["liner"][suffix]=1;if($('radioLinerOff').checked||(!$('radioLinerOff').checked&&!$('radioLinerOn').checked)){this.prettySelects["liner"][suffix].disable();}else{this.prettySelects["liner"][suffix].enable();}}else{$(this.prettySelects["liner"][suffix].container).hide();}}else{var compareLinerSuffix=Personalize.product.color.id+this.selectedEnvelopes["mailing"].id;if(compareSuffix==suffix){this.disableLinerEnvelopes();}}}}}
var innerSuffix=Personalize.product.color.id+this.selectedEnvelopes["mailing"].id;$('innerSuffix').value=innerSuffix;if(typeof this.prettySelects["inner"][innerSuffix]!=="undefined"){$(this.prettySelects["inner"][innerSuffix].container).show();this.visiblePrettySelects["inner"][innerSuffix]=1;}
this.pricemanager.updateMailingPrices(this.selectedEnvelopes["mailing"]);this.pricemanager.updateExtraPrices(this.selectedEnvelopes["mailing"],false,false,false);this.pricemanager.render();$('qtyExtraEnvelopes').observe('change',this.events.onChangeExtraEnvelope.bind(this));$('radioInnerOn').observe('click',this.events.onChangeNoInnerEnvelope.bindAsEventListener(this));$('radioInnerOff').observe('click',this.events.onChangeNoInnerEnvelope.bindAsEventListener(this));$('radioLinerOn').observe('click',this.events.onChangeNoLinerEnvelope.bindAsEventListener(this));$('radioLinerOff').observe('click',this.events.onChangeNoLinerEnvelope.bindAsEventListener(this));$('envelopeStep_zoomBtnMailingLabel').observe('click',this.events.zoomMailing.bind(this));$('envelopeStep_zoomBtnMailing').observe('click',this.events.zoomMailing.bind(this));$('envelopeStep_zoomBtnInnerLabel').observe('click',this.events.zoomInner.bind(this));$('envelopeStep_zoomBtnInner').observe('click',this.events.zoomInner.bind(this));$('envelopeStep_zoomBtnInvitationLabel').observe('click',this.events.zoomInvitation.bind(this));$('envelopeStep_zoomBtnInvitation').observe('click',this.events.zoomInvitation.bind(this));this.loadValuesFromPersonalization();var returnAddress=(parseFloat(this.selectedEnvelopes["mailing"].returnAddress)==1)?true:false;if(returnAddress){this.editors["pra_control"].enable();var praControlValues=this.editors["pra_control"].getValues();var lines=praControlValues["praLines[]"];}else{this.editors["pra_control"].disable();var lines=false;}
if($('radioPraOff').checked){lines=false;}
var defaultImage=Personalize.hosts.static+"image/wpd/wedding-paper-divas-logo.gif";this.zoomBoxs["mailing"]=new PersonalizeZoomBox("Mailing Envelope Preview",defaultImage);this.zoomBoxs["inner"]=new PersonalizeZoomBox("Inner Envelope Preview",defaultImage);this.zoomBoxs["invitation"]=new PersonalizeZoomBox("Invitation Preview",this.getSampleImageSrc(550,550));this.updateImages();var selectedFontId=$F('selectPraFont');var selectedFont=Personalize.masterFontList[selectedFontId];if(selectedFont){var selectedFontTypeface=Personalize.masterTypefaceList[selectedFont.typefaceId];if(selectedFontTypeface.typeId!==null){if(selectedFontTypeface.type.name.toLowerCase()=="script"){this.editors["pra_control"].showScriptWarning();}else{this.editors["pra_control"].hideScriptWarning();}}else{this.editors["pra_control"].hideScriptWarning();}}
$(this.element.id).show();},deactivate:function(){$('envelopesStep').hide();},validate:function(){var colorId=Personalize.product.color.id;if(this.editors["pra_control"].enabled){var praValues=this.editors["pra_control"].getValues();}else{var praValues=false;}
var mailingEnvelopeId=$F('mailingEnvelopeId').replace(Personalize.product.color.id,"");var mailingEnvelopePresent=(typeof this.selectedEnvelopes["mailing"]!==null)?true:false;if(mailingEnvelopePresent){var mailingEnvelope=this.selectedEnvelopes["mailing"];}
var innerSuffix=$F('innerSuffix');var innerEnvelopeId=$F('innerEnvelopeId').replace(innerSuffix,"");var innerEnvelopePresent=false;for(var idx in this.selectedEnvelopes["inner"]){if(innerEnvelopeId!==""){innerEnvelopePresent=true;var innerEnvelope=Personalize.envelopes[innerEnvelopeId];break;}}
var linerSuffix=$F('linerSuffix');var linerEnvelopeId=$F('linerEnvelopeId').replace(linerSuffix,"");var linerEnvelopePresent=false;for(var idx in this.selectedEnvelopes["liner"]){if(linerEnvelopeId!==""){linerEnvelopePresent=true;var linerEnvelope=Personalize.envelopes[linerEnvelopeId];break;}}
var outerEnvelopeId=$F('outerEnvelopeId');var outerEnvelopePresent=(typeof Personalize.envelopes[outerEnvelopeId]!==null)?true:false;if(outerEnvelopePresent){var outerEnvelope=Personalize.envelopes[outerEnvelopeId];}
Personalize.personalization.additionalEnvelopes=parseFloat($F('qtyExtraEnvelopes'));if(mailingEnvelopePresent&&innerEnvelopePresent&&linerEnvelopePresent){var foundPairId="";for(var idx in Personalize.envelopesPairs){var pairId=idx;var pair=Personalize.envelopesPairs[idx];if((pair.outerEnvelopeId==outerEnvelopeId)&&(pair.innerEnvelopeId==innerEnvelopeId)){foundPairId=pairId;break;}}
Personalize.personalization.envelopeId=mailingEnvelopeId;Personalize.personalization.linedEnvelopeId=null;Personalize.personalization.envelopePairId=foundPairId;Personalize.personalization.pairLinedEnvelopeId=linerEnvelopeId;}else if(mailingEnvelopePresent&&innerEnvelopePresent&&!linerEnvelopePresent){for(var idx in Personalize.envelopesPairs){var pairId=idx;var pair=Personalize.envelopesPairs[idx];if((pair.outerEnvelopeId==outerEnvelopeId)&&(pair.innerEnvelopeId==innerEnvelopeId)){foundPairId=pairId;break;}}
Personalize.personalization.envelopeId=mailingEnvelopeId;Personalize.personalization.linedEnvelopeId=null;Personalize.personalization.envelopePairId=foundPairId;Personalize.personalization.pairLinedEnvelopeId=null;}else if(mailingEnvelopePresent&&!innerEnvelopePresent&&linerEnvelopePresent){Personalize.personalization.envelopeId=mailingEnvelopeId;Personalize.personalization.linedEnvelopeId=linerEnvelopeId;Personalize.personalization.envelopePairId=null;Personalize.personalization.pairLinedEnvelopeId=null;}else if(mailingEnvelopePresent&&!innerEnvelopePresent&&!linerEnvelopePresent){Personalize.personalization.envelopeId=mailingEnvelopeId;Personalize.personalization.linedEnvelopeId=null;Personalize.personalization.envelopePairId=null;Personalize.personalization.pairLinedEnvelopeId=null;}
var mailingEnvelope=Personalize.envelopes[mailingEnvelopeId];var returnAddress=parseFloat(mailingEnvelope.returnAddress);if(returnAddress&&praValues!==false){var praText=praValues["praLines[]"].join("");var praValid=(praText=="")?false:true;var matches=praText.match(/\w/gi);praValid=(matches!==null)?true:false;praValid=((praValid&&$('radioPraOn').checked)||$('radioPraOff').checked||!$('radioPraOff').checked&&!$('radioPraOn').checked);if(!praValid){var praEditor=this.editors["pra_control"];praEditor.showNoAddressWarning();return false;}else{var praEditor=this.editors["pra_control"];praEditor.hideNoAddressWarning();}
Personalize.personalization.returnAddressFront=parseFloat(Personalize.product.returnAddressFront);if($('radioPraOn').checked){Personalize.personalization.returnAddress=1;var side=(Personalize.personalization.returnAddressFront)?"Front":"Back";Personalize.personalization.returnAddressAlignmentId=mailingEnvelope["returnAddress"+side+"AlignmentId"];Personalize.personalization.returnAddressHeight=mailingEnvelope["returnAddress"+side+"Height"];Personalize.personalization.returnAddressWidth=mailingEnvelope["returnAddress"+side+"Width"];Personalize.personalization.returnAddressX=mailingEnvelope["returnAddress"+side+"X"];Personalize.personalization.returnAddressY=mailingEnvelope["returnAddress"+side+"Y"];Personalize.personalization.returnAddressText=praValues["praLines[]"].join("\n");Personalize.personalization.returnAddressFontId=$F('selectPraFont');Personalize.personalization.returnAddressFontColorId=$F('praFontColorId');Personalize.personalization.returnAddressFontSize=12;Personalize.personalization.returnAddressPrice=mailingEnvelope.returnAddressPrice;Personalize.personalization.returnAddressSetupPrice=mailingEnvelope.returnAddressSetupPrice;if(typeof Personalize.masterFontList[$F('selectPraFont')].returnAddressData[mailingEnvelope.sizeId]!=='undefined'){Personalize.personalization.returnAddressFontSize=Personalize.masterFontList[$F('selectPraFont')].returnAddressData[mailingEnvelope["sizeId"]].fontSize;Personalize.personalization.returnAddressLeading=Personalize.masterFontList[$F('selectPraFont')].returnAddressData[mailingEnvelope["sizeId"]].fontLeading;}else{Personalize.personalization.returnAddressFontSize=12;Personalize.personalization.returnAddressLeading=12;}}else{Personalize.personalization.returnAddress=null;Personalize.personalization.returnAddressAlignmentId=null;Personalize.personalization.returnAddressHeight=null;Personalize.personalization.returnAddressWidth=null;Personalize.personalization.returnAddressX=null;Personalize.personalization.returnAddressY=null;Personalize.personalization.returnAddressText=null;Personalize.personalization.returnAddressFontId=null;Personalize.personalization.returnAddressFontColorId=null;Personalize.personalization.returnAddressFontSize=null;Personalize.personalization.returnAddressPrice=null;Personalize.personalization.returnAddressSetupPrice=null;Personalize.personalization.returnAddressFontSize=null;Personalize.personalization.returnAddressLeading=null;}}else{Personalize.personalization.returnAddress=null;Personalize.personalization.returnAddressAlignmentId=null;Personalize.personalization.returnAddressHeight=null;Personalize.personalization.returnAddressWidth=null;Personalize.personalization.returnAddressX=null;Personalize.personalization.returnAddressY=null;Personalize.personalization.returnAddressText=null;Personalize.personalization.returnAddressFontId=null;Personalize.personalization.returnAddressFontColorId=null;Personalize.personalization.returnAddressFontSize=null;Personalize.personalization.returnAddressPrice=null;Personalize.personalization.returnAddressSetupPrice=null;Personalize.personalization.returnAddressFontSize=null;Personalize.personalization.returnAddressLeading=null;}
return true;},next:function(){var valid=this.validate();if(valid){$(this.element.id).hide();return true;}else{return false;}},prev:function(){return true;},disableAllInnerEnvelopes:function(){$('innerContainer').hide();$('innerContainerHeader').hide();},disableAllLinerEnvelopes:function(){$('linerContainer').hide();$('linerContainerHeader').hide();},disableInnerEnvelopes:function(){$('formInnerEnvelope').disable();$('innerEnvelopesPrettySelectContainer').hide();$('radioInnerOff').checked=true;},enableInnerEnvelopes:function(){$('formInnerEnvelope').enable();$('innerEnvelopesPrettySelectContainer').show();},disableLinerEnvelopes:function(){$('formLinerEnvelope').disable();$('linerEnvelopesPrettySelectContainer').hide();$('radioLinerOff').checked=true;},enableLinerEnvelopes:function(){$('formLinerEnvelope').enable();$('linerEnvelopesPrettySelectContainer').show();},updateImages:function(){var returnAddress=(parseFloat(this.selectedEnvelopes["mailing"].returnAddress)==1)?true:false;if(returnAddress){this.editors["pra_control"].enable();var praControlValues=this.editors["pra_control"].getValues();var lines=praControlValues["praLines[]"];}else{this.editors["pra_control"].disable();var lines=false;}
if($('radioPraOff').checked){lines=false;}
if(typeof this.envelopeImages["mailing"]!=='undefined'){this.envelopeImages["mailing"]=new EnvelopeImage("imgEnvelopeMailing",this.selectedEnvelopes["mailing"],350,450,lines);this.envelopeImages["mailing"].render();}
var praControlValues=this.editors["pra_control"].getValues();var mailingEnvelopeId=$F('mailingEnvelopeId').replace(Personalize.product.color.id,"");var mailingEnvelope=Personalize.envelopes[mailingEnvelopeId];var innerEnvelopeId=$F('innerEnvelopeId');var innerEnvelope=Personalize.envelopes[innerEnvelopeId];var linerEnvelopeId=$F('linerEnvelopeId');var linerEnvelope=Personalize.envelopes[linerEnvelopeId];if(innerEnvelopeId!==""&&$('radioInnerOn').checked){if(linerEnvelopeId!==""&&$('radioLinerOn').checked){praEnvelope=linerEnvelope;}else{praEnvelope=innerEnvelope;}
praEnvelopeImage=this.envelopeImages["inner"];}else{if(linerEnvelopeId!==""&&$('radioLinerOn').checked){praEnvelope=linerEnvelope;}else{praEnvelope=mailingEnvelope;}
praEnvelopeImage=this.envelopeImages["mailing"];}
var praColors=praEnvelope.praColors;var availablePraColors=this.editors["pra_control"].getAvailablePraFontColors();var intersectingColorsCount=0;for(var idx in availablePraColors){if(typeof praEnvelope.praColors[idx]!=='undefined'){intersectingColorsCount++;}}
var selectablePraColors=new Array();var firstDefault=null;var lastColorSelectedAvailable=false;for(var idxPraFontColor in praEnvelope.praColors){var fontColor=praEnvelope.praColors[idxPraFontColor];var alwaysVisible=parseFloat(fontColor.alwaysVisible)?true:false;if(intersectingColorsCount==0&&parseFloat(fontColor.sort)==0){firstDefault=fontColor}
if(typeof availablePraColors[fontColor.fontColorId]!=="undefined"){if(firstDefault==null){firstDefault=fontColor;}else{if(parseFloat(fontColor.sort)<parseFloat(firstDefault.sort)){firstDefault=fontColor;}}}
if(alwaysVisible||typeof availablePraColors[fontColor.fontColorId]!=="undefined"){selectablePraColors.push(fontColor);if(fontColor.fontColorId==this.praColorSelected){lastColorSelectedAvailable=true;}}}
var sortBySortValue=function(a,b){var aSort=parseFloat(a.sort);var bSort=parseFloat(b.sort);if(aSort<bSort){return-1;}else if(aSort>bSort){return 1;}else{return 0;}}
selectablePraColors.sort(sortBySortValue);var elColorSwatchContainer=$('praFontColorSwatches');elColorSwatchContainer.update("");if(lastColorSelectedAvailable){$('praFontColorId').value=this.praColorSelected;}else{this.praColorSelected=false;$('praFontColorId').value=firstDefault.fontColor.id;}
praEnvelopeImage.update(praEnvelope,false,false,lines);for(var idx=0;idx<selectablePraColors.length;idx++){var fontColor=selectablePraColors[idx].fontColor;var elNewColorSwatch=new Element("div",{id:"praFontColorSwatch_"+fontColor.id,title:fontColor.fontColorDisplayName});elNewColorSwatch.addClassName("clickable");if(!this.praColorSelected){if(firstDefault.fontColor.id==fontColor.id){elNewColorSwatch.addClassName("selectedColor");$('fontColorSelectionSwatchName').update(fontColor.fontColorDisplayName);$('fontColorSelection').show();}else{elNewColorSwatch.addClassName("nonSelectedColor");}}else{if(fontColor.id==$F('praFontColorId')){elNewColorSwatch.addClassName("selectedColor");$('fontColorSelectionSwatchName').update(fontColor.fontColorDisplayName);$('fontColorSelection').show();}else{elNewColorSwatch.addClassName("nonSelectedColor");}}
elNewColorSwatch.setStyle({padding:"1px",float:"left",backgroundColor:"#"+fontColor.rgb});elNewColorSwatch.observe("click",this.events.onClickPraFontColor.bindAsEventListener(elNewColorSwatch,this));elColorSwatchContainer.insert(elNewColorSwatch);}
var returnAddress=parseFloat(this.envelopeImages["mailing"].envelope.returnAddress);if(returnAddress){this.editors["pra_control"].enable();}else{this.editors["pra_control"].disable();}
this.pricemanager.refreshPra();this.pricemanager.refreshTotals(false);},events:{onClickPraFontColor:function(event,scope){var targetElement=Event.element(event);var colorIdChunks=targetElement.id.split("_");var colorId=colorIdChunks[1];var elements=$$('.selectedColor');for(var idx=0;idx<elements.length;idx++){var element=elements[idx];element.removeClassName("selectedColor");element.addClassName("nonSelectedColor");}
targetElement.addClassName("selectedColor");var elPraFontColorId=$('praFontColorId');elPraFontColorId.value=colorId;scope.praColorSelected=colorId;scope.updateImages();$('fontColorSelectionSwatchName').update(targetElement.title);},onChangePraLines:function(scope,event){this.editors["pra_control"].events.praLineOnChange(scope,event);var praControlValues=this.editors["pra_control"].getValues();var lines=praControlValues["praLines[]"];var praText="";for(var idx=0;idx<lines.length;idx++){praText+=lines[idx];}
if(praText!==""){this.editors["pra_control"].hideNoAddressWarning();}
this.updateImages();this.pricemanager.refreshPra();this.pricemanager.refreshTotals(false);},onKeyUpPraLines:function(scope,event){if($('radioPraOff').checked){$('radioPraOn').checked=true;this.pricemanager.refreshPra();this.pricemanager.refreshTotals(false);}
this.editors["pra_control"].events.praLineOnChange(scope,event);var praControlValues=this.editors["pra_control"].getValues();var lines=praControlValues["praLines[]"];var praText="";for(var idx=0;idx<lines.length;idx++){praText+=lines[idx];}
if(praText!==""){this.editors["pra_control"].hideNoAddressWarning();}},onChangePraRadios:function(scope,event){this.editors["pra_control"].events.praRadioOnChange(scope,event);this.updateImages();this.pricemanager.refreshPra();this.pricemanager.refreshTotals(false);},onChangeNoInnerEnvelope:function(event){var showInnerEnvelopeImage=$('radioInnerOn').checked;if(!showInnerEnvelopeImage){$("envelopeInner").hide();$("envelopeInnerBreak").hide();$("innerEnvelopeId").value="";}
var element=event.element();var innerSuffix=$F('innerSuffix');if(typeof this.prettySelects["inner"][innerSuffix]!=='undefined'){this.enableInnerEnvelopes();if($F(element)==0){this.prettySelects["inner"][innerSuffix].selected.update("");this.prettySelects["inner"][innerSuffix].disable();var linerSuffix=Personalize.product.color.id+this.selectedEnvelopes["mailing"].id;$('linerSuffix').value=linerSuffix;var innerEnvelope=false;this.pricemanager.updatePricing("inner",parseFloat("0"));}else{this.prettySelects["inner"][innerSuffix].enable();var prettySelectItems=this.prettySelects["inner"][innerSuffix].list.getElementsByClassName('prettySelectItem');var firstElement=prettySelectItems[0];var chunks=firstElement.id.split("_");var linerSuffix=chunks[1];$('linerSuffix').value=linerSuffix;this.prettySelects["inner"][innerSuffix].select(firstElement);var outerEnvelope=Personalize.envelopes[$F('outerEnvelopeId')];var innerEnvelope=Personalize.envelopes[$F('innerEnvelopeId')];this.pricemanager.updateInnerPrices(outerEnvelope,innerEnvelope);this.pricemanager.updateExtraPrices(false,outerEnvelope,innerEnvelope,false);}}else{this.disableInnerEnvelopes();}
$('radioLinerOff').checked=true;$('linerEnvelopeId').value="";for(var idx in this.visiblePrettySelects["liner"]){$(this.prettySelects["liner"][idx].container).hide();delete this.visiblePrettySelects["liner"][idx];}
if(typeof this.prettySelects["liner"][linerSuffix]!=='undefined'){$(this.prettySelects["liner"][linerSuffix].container).show();this.prettySelects["liner"][linerSuffix].disable();this.prettySelects["liner"][linerSuffix].selected.update("");this.visiblePrettySelects["liner"][linerSuffix]=1;this.enableLinerEnvelopes();}else{this.disableLinerEnvelopes();}
if(!innerEnvelope){$('subtotalExtraLabelText').update("Extra Envelopes");$('extraLabelText').update("Extra Envelopes");this.pricemanager.updateExtraPrices(this.selectedEnvelopes["mailing"],false,false,false);}else{$('subtotalExtraLabelText').update("Extra Envelope Sets");$('extraLabelText').update("Extra Envelope Sets");this.pricemanager.updateExtraPrices(false,outerEnvelope,innerEnvelope,false);}
this.pricemanager.updatePricing("liner",parseFloat("0"));this.pricemanager.refreshInner();this.pricemanager.refreshLiner();this.pricemanager.refreshExtra();this.pricemanager.refreshTotals(false);this.updateImages();},onChangeNoLinerEnvelope:function(event){var element=event.element();var linerSuffix=$F('linerSuffix');if($('radioLinerOff').checked==true){$('linerEnvelopeId').value="";}
if(typeof this.prettySelects["liner"][linerSuffix]!=='undefined'){this.enableLinerEnvelopes();if($F(element)==0){this.prettySelects["liner"][linerSuffix].selected.update("");this.prettySelects["liner"][linerSuffix].disable();this.pricemanager.updatePricing("liner",parseFloat("0"));var linerEnvelope=false;}else{this.prettySelects["liner"][linerSuffix].enable();var prettySelectItems=this.prettySelects["liner"][linerSuffix].list.getElementsByClassName('prettySelectItem');var firstElement=prettySelectItems[0];this.prettySelects["liner"][linerSuffix].select(firstElement);var linerEnvelope=Personalize.envelopes[$F('linerEnvelopeId')];this.pricemanager.updateLinerPrices(linerEnvelope);}
this.pricemanager.refreshLiner();this.pricemanager.refreshTotals(false);}else{this.disableLinerEnvelopes();}
var innerEnvelopeId=$F('innerEnvelopeId');var outerEnvelopeId=$F('outerEnvelopeId');if(!linerEnvelope){if(innerEnvelopeId!==""&&outerEnvelopeId!==""){this.pricemanager.updateExtraPrices(false,Personalize.envelopes[outerEnvelopeId],Personalize.envelopes[innerEnvelopeId],false);}else{this.pricemanager.updateExtraPrices(this.selectedEnvelopes["mailing"],false,false,false);}}else{if(innerEnvelopeId!==""&&outerEnvelopeId!==""){this.pricemanager.updateExtraPrices(false,Personalize.envelopes[outerEnvelopeId],false,linerEnvelope);}else{this.pricemanager.updateExtraPrices(false,false,false,linerEnvelope);}}
this.pricemanager.refreshExtra();this.pricemanager.refreshTotals(false);this.updateImages();},onChangeExtraEnvelope:function(){var elQtyExtraEnvelopes=$('qtyExtraEnvelopes');var valQtyExtraEnvelopes=$F('qtyExtraEnvelopes');if(isNaN(valQtyExtraEnvelopes)){elQtyExtraEnvelopes.setStyle({border:'2px solid red'});Effect.Pulsate(elQtyExtraEnvelopes,{pulses:5,duration:1.5});var matches=valQtyExtraEnvelopes.match(/\d/gi);var strMatches=matches.join("");elQtyExtraEnvelopes.value=new Number(strMatches);}else{elQtyExtraEnvelopes.style.border="";}
var innerEnvelopeId=$F('innerEnvelopeId');if(innerEnvelopeId!==""){$('subtotalExtraLabelText').update("Extra Envelope Sets");$('extraLabelText').update("Extra Envelope Sets");}else{$('subtotalExtraLabelText').update("Extra Envelopes");$('extraLabelText').update("Extra Envelope");}
this.pricemanager.refreshExtra();this.pricemanager.refreshTotals(false);},zoomMailing:function(){var innerEnvelopeId=$F('innerEnvelopeId');if(innerEnvelopeId!==""){var zoomEnvelope=this.selectedEnvelopes["mailing"];}else{var linerEnvelopeId=$F('linerEnvelopeId');var linerSuffix=$F('linerSuffix');if(linerEnvelopeId!==""){var zoomEnvelope=this.selectedEnvelopes["liner"][linerSuffix];}else{var zoomEnvelope=this.selectedEnvelopes["mailing"];}}
var praControlValues=this.editors["pra_control"].getValues();if(typeof praControlValues["praLines[]"]!=='undefined'){var lines=praControlValues["praLines[]"];var strLines=lines.join("");var wordMatches=strLines.match(/\w/gi);if(wordMatches==null){lines=false;}}
if($('radioPraOff').checked){lines=false;}
var imageMailingEnvelopeLarge=new EnvelopeImage(false,zoomEnvelope,550,550,lines);this.zoomBoxs["mailing"].uri=imageMailingEnvelopeLarge.render(true);this.zoomBoxs["mailing"].showZoom();$(document.body).scrollTo();},zoomInner:function(){var suffix=Personalize.product.color.id+this.selectedEnvelopes["mailing"].id;var linerSuffix=$F('linerSuffix');var linerEnvelopeId=$F('linerEnvelopeId');if(linerEnvelopeId==""){var zoomEnvelope=this.selectedEnvelopes["inner"][linerSuffix];}else{var zoomEnvelope=this.selectedEnvelopes["liner"][linerSuffix];}
var imageInnerEnvelopeLarge=new EnvelopeImage(false,zoomEnvelope,550,550,false);this.zoomBoxs["inner"].uri=imageInnerEnvelopeLarge.render(true);this.zoomBoxs["inner"].showZoom();$(document.body).scrollTo();},zoomInvitation:function(){this.zoomBoxs["invitation"].showZoom();$(document.body).scrollTo();},onChangeMailingEnvelope:function(id){var prefix=Personalize.product.color.id;var realId=id.replace(prefix,"");this.selectedEnvelopes["mailing"]=Personalize.envelopes[realId];this.selectedEnvelopes["liner"]={};this.selectedEnvelopes["inner"]={};$('radioLinerOff').checked=true;$('radioInnerOff').checked=true;$('outerEnvelopeId').value="";var showInnerEnvelopeImage=$('radioInnerOn').checked;if(!showInnerEnvelopeImage){$("envelopeInner").hide();$("envelopeInnerBreak").hide();$("innerEnvelopeId").value="";}
var returnAddress=(parseFloat(this.selectedEnvelopes["mailing"].returnAddress)==1)?true:false;if(returnAddress){this.editors["pra_control"].enable();var praControlValues=this.editors["pra_control"].getValues();var lines=praControlValues["praLines[]"];}else{this.editors["pra_control"].disable();var lines=false;}
for(var idx in this.visiblePrettySelects["inner"]){$(this.prettySelects["inner"][idx].container).hide();delete this.visiblePrettySelects["inner"][idx];}
var innerSuffix=Personalize.product.color.id+this.selectedEnvelopes["mailing"].id;$('innerSuffix').value=innerSuffix;$('innerEnvelopeId').value="";if(typeof this.prettySelects["inner"][innerSuffix]!=="undefined"){$(this.prettySelects["inner"][innerSuffix].container).show();this.prettySelects["inner"][innerSuffix].disable();this.visiblePrettySelects["inner"][innerSuffix]=1;this.enableInnerEnvelopes();this.pricemanager.updatePricing("inner",parseFloat("0"));this.pricemanager.refreshInner();}else{this.disableInnerEnvelopes();}
for(var idx in this.visiblePrettySelects["liner"]){$(this.prettySelects["liner"][idx].container).hide();delete this.visiblePrettySelects["liner"][idx];}
var linerSuffix=innerSuffix;$('linerSuffix').value=linerSuffix;$('linerEnvelopeId').value="";if(typeof this.prettySelects["liner"][linerSuffix]!=='undefined'){$(this.prettySelects["liner"][linerSuffix].container).show();this.prettySelects["liner"][linerSuffix].disable();this.visiblePrettySelects["liner"][linerSuffix]=1;this.enableLinerEnvelopes();this.pricemanager.updatePricing("liner",parseFloat("0"));this.pricemanager.refreshLiner();}else{this.disableLinerEnvelopes();}
this.pricemanager.updateMailingPrices(this.selectedEnvelopes["mailing"]);this.pricemanager.updateExtraPrices(this.selectedEnvelopes["mailing"],false,false,false);this.pricemanager.refreshMailing();this.pricemanager.refreshExtra();this.pricemanager.refreshTotals(false);this.envelopeImages["mailing"]=new EnvelopeImage("imgEnvelopeMailing",this.selectedEnvelopes["mailing"],350,450,lines);this.envelopeImages["mailing"].render();},onChangeInnerEnvelope:function(suffix,id){var pairId=id.replace(suffix,"");var pair=Personalize.envelopesPairs[pairId];var innerEnvelopeId=pair.innerEnvelopeId;var outerEnvelopeId=pair.outerEnvelopeId;var innerEnvelope=Personalize.envelopes[innerEnvelopeId];var outerEnvleope=Personalize.envelopes[outerEnvelopeId];if(innerEnvelopeId!==""){$('subtotalExtraLabelText').update("Extra Envelope Sets");$('extraLabelText').update("Extra Envelope Sets");}else{$('subtotalExtraLabelText').update("Extra Envelopes");$('extraLabelText').update("Extra Envelope");}
this.selectedEnvelopes["inner"][id]=Personalize.envelopes[innerEnvelopeId];$('innerEnvelopeId').value=innerEnvelopeId;$('outerEnvelopeId').value=outerEnvelopeId;$("envelopeInner").show();$("envelopeInnerBreak").show();$("radioInnerOn").checked=true;this.pricemanager.updateInnerPrices(Personalize.envelopes[outerEnvelopeId],this.selectedEnvelopes["inner"][id]);this.pricemanager.refreshInner();this.pricemanager.updateExtraPrices(false,Personalize.envelopes[outerEnvelopeId],this.selectedEnvelopes["inner"][id],false);this.pricemanager.refreshExtra();this.pricemanager.refreshTotals(false);this.envelopeImages["inner"]=new EnvelopeImage("imgEnvelopeInner",this.selectedEnvelopes["inner"][id],350,450,false);this.envelopeImages["inner"].render();for(var idx in this.visiblePrettySelects["liner"]){$(this.prettySelects["liner"][idx].container).hide();delete this.visiblePrettySelects["liner"][idx];}
this.selectedEnvelopes["liner"]={};$('radioLinerOff').checked=true;var linerSuffix=id;$('linerSuffix').value=id;$('linerEnvelopeId').value="";if(typeof this.prettySelects["liner"][linerSuffix]!=='undefined'){$(this.prettySelects["liner"][linerSuffix].container).show();this.visiblePrettySelects["liner"][linerSuffix]=1;this.enableLinerEnvelopes();}else{this.disableLinerEnvelopes();}
this.updateImages();},onChangeLinerEnvelope:function(suffix,id){var realId=id.replace(suffix,"");this.selectedEnvelopes["liner"][suffix]=Personalize.envelopes[realId];$('linerEnvelopeId').value=realId;$("radioLinerOn").checked=true;this.pricemanager.updateLinerPrices(this.selectedEnvelopes["liner"][suffix]);this.pricemanager.refreshLiner();var innerEnvelopeId=$F('innerEnvelopeId');var outerEnvelopeId=$F('outerEnvelopeId');if(innerEnvelopeId!==""&&outerEnvelopeId!==""){this.pricemanager.updateExtraPrices(false,Personalize.envelopes[outerEnvelopeId],false,this.selectedEnvelopes["liner"][suffix]);}else{this.pricemanager.updateExtraPrices(false,false,false,this.selectedEnvelopes["liner"][suffix]);}
this.pricemanager.refreshExtra();this.pricemanager.refreshTotals(false);this.updateImages();}}});var PriceManager=Class.create({});PriceManager.prototype={pricing:{mailing:0.0,inner:0.0,liner:0.0,extra:0.0,praSetup:0.0,praItem:0.0},envelopes:{mailing:false,inner:false,liner:false,extra:false},totals:{},quantity:0,getQuantity:function(){var qtyKey="q"+Personalize.product.occasionId;var qty=TP.getCookie(qtyKey);if(qty==null){qty=25;}
return qty;},initialize:function(){this.quantity=this.getQuantity();this.render();},updatePricing:function(key,value){this.pricing[key]=parseFloat(value);},updateMailingPrices:function(envelope){this.pricing.mailing=parseFloat(envelope.price);this.pricing.praSetup=parseFloat(envelope.returnAddressSetupPrice);this.pricing.praItem=parseFloat(envelope.returnAddressPrice);},updateInnerPrices:function(outerEnvelope,innerEnvelope){this.pricing.inner=parseFloat(innerEnvelope.price)+parseFloat(outerEnvelope.price);},updateLinerPrices:function(envelope){this.pricing.liner=parseFloat(envelope.price);},updateExtraPrices:function(mailingEnvelope,outerEnvelope,innerEnvelope,linerEnvelope){var extraPrice=parseFloat(0.0);if(mailingEnvelope!==false){extraPrice+=parseFloat(mailingEnvelope.additionalPrice);this.envelopes.mailing=mailingEnvelope;}else{this.envelopes.mailing=false;}
if(outerEnvelope!==false){extraPrice+=parseFloat(outerEnvelope.additionalPrice);this.envelopes.outer=outerEnvelope;}else{this.envelopes.outer=false;}
if(innerEnvelope!==false){extraPrice+=parseFloat(innerEnvelope.additionalPrice);this.envelopes.inner=innerEnvelope;}else{this.envelopes.inner=false;}
if(linerEnvelope!==false){extraPrice+=parseFloat(linerEnvelope.additionalPrice);this.envelopes.liner=linerEnvelope;}else{this.envelopes.liner=false;}
this.pricing.extra=extraPrice;},updatePraPrices:function(envelope){this.pricing.praSetup=parseFloat(envelope.returnAddressSetupPrice);this.pricing.praItem=parseFloat(envelope.returnAddressPrice);},render:function(){this.calculateTotals();this.refreshMailing();this.refreshPra();this.refreshInner();this.refreshLiner();this.refreshExtra();this.refreshTotals(false);},refreshTotals:function(recalc){if(recalc){this.calculateTotals();}
$('totalEnvelopes').update("$"+new Number(this.totals.all).toFixed(2));},refreshMailing:function(){this.calculateTotals();$('subtotalMailingQty').update(this.quantity);$('subtotalMailingItemPrice').update("$"+new Number(this.pricing.mailing).toFixed(2));var total=(this.totals.mailing=="included")?"included":("$"+new Number(this.totals.mailing).toFixed(2));$('subtotalMailing').update(total);},refreshExtra:function(){this.calculateTotals();this.refreshPra();var qtyExtra=this.getExtraQty();$('subtotalExtraQty').update(qtyExtra);$('subtotalExtraItemPrice').update("$"+new Number(this.pricing.extra).toFixed(2));var qtyPrice=(this.totals.extra=="included")?"$0.00":("$"+new Number(this.totals.extra).toFixed(2));$('extraEnvelopesQtyPrice').update(qtyPrice);$('extraEnvelopesItemPrice').update("$"+new Number(this.pricing.extra).toFixed(2));if(qtyExtra==0||qtyExtra==""){$('subtotalExtraLabel').hide();$('subtotalExtra').hide();}else{$('subtotalExtraLabel').show();$('subtotalExtra').show();$('subtotalExtra').update("$"+new Number(this.totals.extra).toFixed(2));}
var hasExtra=(parseFloat(this.pricing.extra)>0)?true:false;if(hasExtra){var hasInner=(parseFloat(this.pricing.inner)>0)?true:false;var hasLiner=(parseFloat(this.pricing.liner)>0)?true:false;var mailingPrice=new Element("span",{id:"verboseExtraMailingPrice"});var outerPrice=new Element("span",{id:'verboseExtraOuterPrice'});var innerPrice=new Element("span",{id:'verboseExtraInnerPrice'});var linerPrice=new Element("span",{id:'verboseExtraLinerPrice'});var verboseTotal=new Element("span",{id:'verboseExtraTotalPrice'});var additionalPrices={};var hasMailing=false;if(this.envelopes.mailing){additionalPrices.mailing=this.envelopes.mailing.additionalPrice;hasMailing=true;}
var hasOuter=false;if(this.envelopes.outer){additionalPrices.outer=this.envelopes.outer.additionalPrice;hasOuter=true;}
var hasInner=false;if(this.envelopes.inner){additionalPrices.inner=this.envelopes.inner.additionalPrice;hasInner=true;}
var hasLiner=false;if(this.envelopes.liner){additionalPrices.liner=this.envelopes.liner.additionalPrice;hasLiner=true;}
$('extraEnvelopesVerbose').update("");if(!hasInner&&hasOuter&&hasLiner){var mailingEnvelopeId=$F('mailingEnvelopeId').replace(Personalize.product.color.id,"");var innerEnvelopeId=$F('innerEnvelopeId');var outerEnvelopeId=$F('outerEnvelopeId');var mailingEnvelope=Personalize.envelopes[mailingEnvelopeId];var innerEnvelope=Personalize.envelopes[innerEnvelopeId];var outerEnvelope=Personalize.envelopes[outerEnvelopeId];var fakeOuterEnvelopePrice=parseFloat(innerEnvelope.price)+parseFloat(outerEnvelope.price)-parseFloat(mailingEnvelope.price);mailingPrice.update("$"+new Number(innerEnvelope.additionalPrice).toFixed(2)+" mailing + ");outerPrice.update("$"+new Number(fakeOuterEnvelopePrice).toFixed(2)+" inner + ");linerPrice.update("$"+new Number(this.envelopes.liner.price).toFixed(2)+" liner = ");$('extraEnvelopesVerbose').insert(mailingPrice);$('extraEnvelopesVerbose').insert(outerPrice);$('extraEnvelopesVerbose').insert(linerPrice);verboseTotal.show();}else if(hasInner&&hasOuter&&!hasLiner){var mailingEnvelopeId=$F('mailingEnvelopeId').replace(Personalize.product.color.id,"");var innerEnvelopeId=$F('innerEnvelopeId');var outerEnvelopeId=$F('outerEnvelopeId');var mailingEnvelope=Personalize.envelopes[mailingEnvelopeId];var innerEnvelope=Personalize.envelopes[innerEnvelopeId];var outerEnvelope=Personalize.envelopes[outerEnvelopeId];var theFakePrice=parseFloat(innerEnvelope.price)+parseFloat(outerEnvelope.price)-parseFloat(mailingEnvelope.price);outerPrice.update("$"+new Number(additionalPrices.inner).toFixed(2)+" mailing + ");innerPrice.update("$"+new Number(theFakePrice).toFixed(2)+" inner = ");$('extraEnvelopesVerbose').insert(outerPrice);$('extraEnvelopesVerbose').insert(innerPrice);verboseTotal.show();}else if(!hasMailing&&hasLiner){var mailingEnvelopeId=$F('mailingEnvelopeId').replace(Personalize.product.color.id,"");var fakeMailingEnvelopePrice=Personalize.envelopes[mailingEnvelopeId].additionalPrice;mailingPrice.update("$"+new Number(fakeMailingEnvelopePrice).toFixed(2)+" mailing + ");linerPrice.update("$"+new Number(this.envelopes.liner.price).toFixed(2)+" liner = ");$('extraEnvelopesVerbose').insert(mailingPrice);$('extraEnvelopesVerbose').insert(linerPrice);verboseTotal.show();}else if(hasMailing&&!hasLiner){$('extraEnvelopesVerbose').update("");verboseTotal.hide();}
verboseTotal.update("$"+new Number(this.pricing.extra).toFixed(2)+" per envelope set");$('extraEnvelopesVerbose').insert(verboseTotal);}else{$('extraEnvelopesVerbose').update("");}},refreshLiner:function(){this.calculateTotals();$('subtotalLinerQty').update(this.quantity);$('qtyLinerEnvelopes').update(this.quantity);$('subtotalLinerItemPrice').update("$"+new Number(this.pricing.liner).toFixed(2));var subtotal=this.pricing.liner*this.quantity;if(subtotal==0){$('noLinerEnvelopesPricing').show();$('linerEnvelopesPricing').hide();}else{var elQtyLinerEnvelopes=$('qtyLinerEnvelopes');elQtyLinerEnvelopes.update(this.quantity);var elLinerEnvelopesQtyPrice=$('linerEnvelopesQtyPrice');elLinerEnvelopesQtyPrice.update("$"+new Number(subtotal).toFixed(2));$('noLinerEnvelopesPricing').hide();$('linerEnvelopesPricing').show();}
if($('radioLinerOff').checked||(!$('radioLinerOff').checked&&!$('radioLinerOn').checked)){$('subtotalLinerLabel').hide();$('subtotalLiner').hide();}else{$('subtotalLinerLabel').show();$('subtotalLiner').show();var total=(this.totals.liner=="included")?"included":("$"+new Number(this.totals.liner).toFixed(2));$('subtotalLiner').update(total);}},refreshInner:function(){this.calculateTotals();$('subtotalInnerQty').update(this.quantity);$('subtotalInnerItemPrice').update("$"+new Number(this.pricing.inner).toFixed(2));var subtotal=this.pricing.inner*this.quantity;if(subtotal==0){$('noInnerEnvelopesPricing').show();$('innerEnvelopesPricing').hide();}else{var elQtyInnerEnvelopes=$('qtyInnerEnvelopes');elQtyInnerEnvelopes.update(this.quantity);var elInnerEnvelopesQtyPrice=$('innerEnvelopesQtyPrice');elInnerEnvelopesQtyPrice.update("$"+new Number(subtotal).toFixed(2));$('noInnerEnvelopesPricing').hide();$('innerEnvelopesPricing').show();}
if($('radioInnerOff').checked||(!$('radioInnerOff').checked&&!$('radioInnerOn').checked)){$('subtotalInnerLabel').hide();$('subtotalInner').hide();}else{$('subtotalInnerLabel').show();$('subtotalInner').show();var total=(this.totals.inner=="included")?"included":("$"+new Number(this.totals.inner).toFixed(2));$('subtotalInner').update(total);}},refreshPra:function(){this.calculateTotals();var praQty=parseFloat(this.quantity)+parseFloat(this.getExtraQty());$('subtotalPraQty').update(praQty);$('praQtyPrice').update("$"+new Number(this.pricing.praItem).toFixed(2));$('subtotalPraItemPrice').update("$"+new Number(this.pricing.praItem).toFixed(2));if(parseFloat(this.pricing.praSetup)>0){$('praSetupText').update("with $"+new Number(this.pricing.praSetup).toFixed(2)+" setup fee");}else{$('praSetupText').update("");}
var showPraSetup=$('radioPraOn').checked;if(!showPraSetup){$('subtotalPrintedReturnAddressSetupLabel').hide();$('subtotalPrintedReturnAddressSetup').hide();}else{if(parseFloat(this.pricing.praSetup)>0){$('subtotalPrintedReturnAddressSetupLabel').show();$('subtotalPrintedReturnAddressSetup').show();}else{$('subtotalPrintedReturnAddressSetupLabel').hide();$('subtotalPrintedReturnAddressSetup').hide();}}
if($('radioPraOff').checked){$('subtotalPrintedReturnAddressLabel').hide();$('subtotalPrintedReturnAddress').hide();}else{$('subtotalPrintedReturnAddressLabel').show();$('subtotalPrintedReturnAddress').show();var itemTotal=(this.totals.praItem=="included")?"included":("$"+new Number(this.totals.praItem).toFixed(2));$('subtotalPrintedReturnAddress').update(itemTotal);var setupTotal=(this.totals.praSetup=="included")?"included":("$"+new Number(this.totals.praSetup).toFixed(2));$('subtotalPrintedReturnAddressSetup').update(setupTotal);}},renderPrice:function(price){var floatnum=parseFloat(price);if(floatnum==0){return"included";}else{return parseFloat(price);}},getExtraQty:function(){return $F('qtyExtraEnvelopes');},calculateTotals:function(){this.totals.inner=this.calculateInnerTotals();this.totals.mailing=this.calculateMailingTotals();this.totals.extra=this.calculateExtraTotals();praTotals=this.calculatePraTotals();this.totals.praItem=praTotals["itemTotal"];this.totals.praSetup=praTotals["setupTotal"];this.totals.liner=this.calculateLinerTotals();this.totals.all=0;for(var idx in this.totals){if(idx!=="all"){var val=this.totals[idx];if(val=="included"){this.totals.all+=0;}else{this.totals.all+=parseFloat(val);}}}},calculateInnerTotals:function(){var price=this.pricing.inner;var qty=this.quantity;var total=($('radioInnerOff').checked||(!$('radioInnerOff').checked&&!$('radioInnerOn').checked))?0:price*qty;return this.renderPrice(total);},calculateMailingTotals:function(){var price=parseFloat(this.pricing.mailing);var qty=this.quantity;var total=price*qty;return this.renderPrice(total);},calculateLinerTotals:function(){var price=this.pricing.liner;var qty=this.quantity;var total=($('radioLinerOff').checked||(!$('radioLinerOff').checked&&!$('radioLinerOn').checked))?0:price*qty;return this.renderPrice(total);},calculateExtraTotals:function(){var price=this.pricing.extra;var qty=this.getExtraQty();var total=price*qty;return this.renderPrice(total);},calculatePraTotals:function(){var total={itemTotal:this.calculatePraItemTotals(),setupTotal:this.calculatePraSetupTotals()}
return total;},calculatePraItemTotals:function(){var itemPrice=parseFloat(this.pricing.praItem);var qty=parseFloat(this.quantity)+parseFloat(this.getExtraQty());var total=($('radioPraOff').checked)?0:itemPrice*qty;return this.renderPrice(total);},calculatePraSetupTotals:function(){var setupPrice=parseFloat(this.pricing.praSetup);var total=($('radioPraOff').checked)?0:setupPrice;return this.renderPrice(total);}};var PraEditor=Class.create({});PraEditor.prototype={availableFonts:null,pricemanager:null,forms:['formMailingEnvelope'],fields:[],fontData:{},praFields:['praLine1','praLine2','praLine3','praLine4','selectPraFont'],praTextFields:['praLine1','praLine2','praLine3','praLine4'],praRadios:['radioPraOff','radioPraOn'],scriptWarningDomId:'scriptWarning',praText:"",praWarningContainer:null,praWarningContainerDomId:"",praWarning:null,praWarningDomId:"",lastBgColor:{},enabled:null,praColorData:{colors:{}},disable:function(){this.enabled=false;$('formMailingEnvelope').disable();$('radioPraOff').checked=true;},enable:function(){this.enabled=true;$('formMailingEnvelope').enable();},showNoAddressWarning:function(){this.lastBgColor[this.praWarningContainerDomId]=this.praWarningContainer.style.backgroundColor;this.praWarningContainer.setStyle({border:"red 2px solid",backgroundColor:"red"});this.praWarning.show();$('radioPraOn').style.color="white";$('radioPraOff').style.color="white";$('pra_text_container').style.color="white";$('praRadios').style.color="white";},hideNoAddressWarning:function(){this.praWarningContainer.setStyle({border:"",backgroundColor:this.lastBgColor[this.praWarningContainerDomId]});this.praWarning.hide();$('radioPraOn').style.color="black";$('radioPraOff').style.color="black";$('pra_text_container').style.color="black";$('praRadios').style.color="black";},showScriptWarning:function(){$(this.scriptWarningDomId).show();},hideScriptWarning:function(){$(this.scriptWarningDomId).hide();},events:{praLineOnChange:function(scope,event){var element=event.element();var elementId=element.id;$('radioPraOn').checked=true;scope.pricemanager.refreshPra();this.praText="";this.praText+=$('praLine1').value;this.praText+=$('praLine2').value;this.praText+=$('praLine3').value;this.praText+=$('praLine4').value;if(this.praText==""){$('radioPraOff').checked=true;scope.pricemanager.refreshPra();}
if(elementId=="selectPraFont"){var fontId=$F('selectPraFont');var font=Personalize.masterFontList[fontId];var typeface=Personalize.masterTypefaceList[font.typefaceId];if(typeface.typeId!==null){if(typeface.type.name.toLowerCase()=="script"){scope.editors["pra_control"].showScriptWarning();}else{scope.editors["pra_control"].hideScriptWarning();}}else{scope.editors["pra_control"].hideScriptWarning();}}},praRadioOnChange:function(scope,event){scope.pricemanager.refreshPra();var element=event.element();var elementId=element.id;if(elementId=="radioPraOn"){this.praText="";this.praText+=$('praLine1').value;this.praText+=$('praLine2').value;this.praText+=$('praLine3').value;this.praText+=$('praLine4').value;$('radioPraOn').checked=true;}else{this.praText="";}}},initialize:function(pricemanager,options){this.fontData.fonts=Personalize.product.fonts;var step=Personalize.getStepByName("personalizeEnvelopes");for(var idx=0;idx<this.praFields.length;idx++){$(this.praFields[idx]).observe('change',step.events.onChangePraLines.bind(step,step));$(this.praFields[idx]).observe('keyup',step.events.onKeyUpPraLines.bind(step,step));}
for(var idx=0;idx<this.praRadios.length;idx++){$(this.praRadios[idx]).observe('change',step.events.onChangePraRadios.bind(step,step));}
TP.extendObject(this,options);this.praWarningContainer=$(this.praWarningContainerDomId);this.praWarning=$(this.praWarningDomId);},render:function(){var selectTextContainer=$("pra_text_container");if(this.availableFonts==null){this.availableFonts=this.getAvailableFonts();}
var elFontSelect=$('selectPraFont');if(elFontSelect.childElements().length>0){var opts=elFontSelect.childElements();for(var childIdx=0;childIdx<opts.length;childIdx++){var elChild=opts[childIdx];elChild.remove();}}
var elFontSelectOptions={};for(var idx=0;idx<this.availableFonts.length;idx++){var font=this.availableFonts[idx];var elOption=new Element("option",{value:font.id});elOption.update(font.displayName);elFontSelect.insert(elOption);}
var selectPraFontColor=$("praFontColorSwatches");},getAvailablePraFontColors:function(){var availablePraFontColors={};for(var idxPanel in Personalize.personalization.panels){var panel=Personalize.personalization.panels[idxPanel];for(var idxLayoutTextbox in panel.layoutTextboxes){var layoutTextbox=panel.layoutTextboxes[idxLayoutTextbox];if(typeof this.praColorData.colors[layoutTextbox.fontColorId]=='undefined'){availablePraFontColors[layoutTextbox.fontColorId]=Personalize.product.fontColors[layoutTextbox.fontColorId];}}
for(var idxTextbox in panel.textboxes){var textbox=panel.textboxes[idxTextbox];if(typeof this.praColorData.colors[textbox.fontColorId]=='undefined'){availablePraFontColors[textbox.fontColorId]=Personalize.product.fontColors[textbox.fontColorId];}}}
return availablePraFontColors;},getAvailableFonts:function(){var personalizedFonts={};var allPersonalizedFonts={};var allPersonalizedScriptFonts={};var fontCount=0;for(var panelId in Personalize.personalization.panels){for(var textboxId in Personalize.personalization.panels[panelId].textboxes){var fontId=Personalize.personalization.panels[panelId].textboxes[textboxId].fontId;var productFont=Personalize.masterFontList[fontId];if(typeof productFont!=='undefined'){allPersonalizedFonts[fontId]=productFont;var typeface=Personalize.masterTypefaceList[productFont.typefaceId];if(typeface.typeId!==null){if(typeface.type.name.toLowerCase()!=="script"){if(typeof personalizedFonts[fontId]=='undefined'){personalizedFonts[fontId]=productFont;fontCount++;}}else{if(typeof allPersonalizedScriptFonts[fontId]=='undefined'){allPersonalizedScriptFonts[fontId]=productFont;}}}else{if(typeof personalizedFonts[fontId]=='undefined'){personalizedFonts[fontId]=productFont;fontCount++;}}}}
for(var layoutTextboxId in Personalize.personalization.panels[panelId].layoutTextboxes){var fontId=Personalize.personalization.panels[panelId].layoutTextboxes[layoutTextboxId].fontId;var productFont=Personalize.masterFontList[fontId];if(typeof productFont!=='undefined'){allPersonalizedFonts[fontId]=productFont;var typeface=Personalize.masterTypefaceList[productFont.typefaceId];if(typeface.typeId!==null){if(typeface.type.name.toLowerCase()!=="script"){if(typeof personalizedFonts[fontId]=='undefined'){personalizedFonts[fontId]=productFont;fontCount++;}}else{if(typeof allPersonalizedScriptFonts[fontId]=='undefined'){allPersonalizedScriptFonts[fontId]=productFont;}}}else{if(typeof personalizedFonts[fontId]=='undefined'){personalizedFonts[fontId]=productFont;fontCount++;}}}}}
var allRecommendedFonts={};if(fontCount==0){for(var styleClassIdx in Personalize.product.styleClasses){var styleClass=Personalize.product.styleClasses[styleClassIdx];for(var fontIdx in styleClass.style.fonts){var font=styleClass.style.fonts[fontIdx];var fontId=font.fontId;personalizedFonts[fontId]=Personalize.masterFontList[fontId];}}
for(var scriptFontIdx in allPersonalizedScriptFonts){var font=allPersonalizedScriptFonts[scriptFontIdx];personalizedFonts[scriptFontIdx]=font;}}
var sortedFonts=new Array();for(var idx in personalizedFonts){sortedFonts.push(personalizedFonts[idx]);}
function deepAlphaSort(a,b){if(a.displayName<b.displayName){return-1;}else{return 1;}}
sortedFonts.sort(deepAlphaSort);return sortedFonts;},getValues:function(){var retval={};for(var id=0;id<this.forms.length;id++){var form=$(this.forms[id]);var vals=form.serialize(true);for(var idx in vals){retval[idx]=vals[idx];}}
return retval;}};var EnvelopeImage=Class.create({});EnvelopeImage.prototype={initialize:function(elementId,envelope,height,width,lines){this.elementId=elementId;this.envelope=envelope;this.height=height;this.width=width;this.showReturnAddress=(lines!==false)?true:false;this.lines=lines;var raFront=parseFloat(Personalize.product.returnAddressFront);this.side=(raFront)?"front":"back";if(this.elementId==false){returnValue=true;}else{returnValue=false;}
this.render(returnValue);},update:function(envelope,height,width,lines){this.envelope=(!envelope)?this.envelope:envelope;this.height=(!height)?this.height:height;this.width=(!width)?this.width:width;this.lines=(!lines)?this.lines:lines;this.showReturnAddress=(lines!==false)?true:false;this.render();},render:function(returnValue){var params={id:this.envelope.id,max_height:this.height,max_width:this.width,side:this.side};var returnAddress=(parseFloat(this.envelope.returnAddress)=="1")?true:false;if(returnAddress&&this.showReturnAddress){var fontId=$F('selectPraFont');var fontColorId=$F('praFontColorId');var fontColor=this.envelope.praColors[fontColorId].fontColor;var praBack={ra_x:this.envelope.returnAddressBackX,ra_y:this.envelope.returnAddressBackY,ra_align:this.envelope.returnAddressBackAlignmentId,ra_height:this.envelope.returnAddressBackHeight,ra_width:this.envelope.returnAddressBackWidth};var praFront={ra_x:this.envelope.returnAddressFrontX,ra_y:this.envelope.returnAddressFrontY,ra_align:this.envelope.returnAddressFrontAlignmentId,ra_height:this.envelope.returnAddressFrontHeight,ra_width:this.envelope.returnAddressFrontWidth};if(this.side=="front"){var ra=praFront;}else{var ra=praBack;}
var showLines=false;for(var idx=0;idx<this.lines.length;idx++){var line=this.lines[idx];if(line!==""){showLines=true;}}
if(showLines){var fontSize=12
var fontLeading=null
if(typeof Personalize.masterFontList[fontId].returnAddressData[this.envelope.sizeId]!=='undefined'){fontSize=Personalize.masterFontList[fontId].returnAddressData[this.envelope.sizeId].fontSize;fontLeading=Personalize.masterFontList[fontId].returnAddressData[this.envelope.sizeId].fontLeading;}
params.ra_x=ra.ra_x;params.ra_y=ra.ra_y;params.ra_width=ra.ra_width;params.ra_height=ra.ra_height;params.ra_align=ra.ra_align;params.font_id=fontId;params.font_size=fontSize;if(fontLeading!==null){params.leading=fontLeading;}
params.font_color=fontColor.rgb;params["lines[]"]=this.lines;}}
var qstr=Object.toQueryString(params);var imgsrc=Personalize.hosts.images+"envelope_image.php?"+qstr;if(returnValue){return imgsrc;}else{var element=$(this.elementId);element.src=imgsrc;}}}

var PersonalizeStringTable={DRAG_PHOTOS_HERE:'Drag and drop photos here',CLICK_ADD_PHOTO:'Click here\nto add photos',TPC_PHOTOCARD_HELP:'<ul class="helpText"><li>To edit or add text, click on the text area(s).\
      </li><li>View our <a href="http://www.tinyprints.com/sample-greetings-verses.htm" target="_blank">suggested verses</a> for sample text.\
      </li><li>You can customize this card with your company logo or photo using our web-based upload system. See our <a href="http://www.tinyprints.com/tiny-prints-personalization-creation-features-faq.htm" target="_blank">FAQ</a> section for more information.\
      </li><li>Our photo tray can hold up to 20 files. If you already have 20 files in your tray, you must remove files before you can add others.\
      </li><li>You can drag and drop photos into any of the logo or photo boxes.\
      </li><li>To edit your photo, click on it on the card preview.\
      </li><li>To add a design accent, expand the design section on the left tool bar and then click and drag the design accent onto the card.\
      </li><li>A professional designer may review and may enhance your photo(s) for the best quality printing\
      </li><li>Visit the <a href="http://www.tinyprints.com/tiny-prints-personalization-creation-features-faq.htm" target="_blank">Frequently Asked Questions</a> section for more information.\
      </li></ul>',TP_PHOTOCARD_HELP:'<ul class="helpText"><li>To edit or add text, click on the text area(s).\
      </li><li>View our <a href="http://www.tinyprints.com/sample-greetings-verses.htm" target="_blank">suggested verses</a> for sample text.\
      </li><li>You can add photos to the tray by clicking "Add Photo" at the bottom of the page.\
      </li><li>The photo tray can hold up to 20 photos. If you already have 20 photos, you must remove photos before you can add others.\
      </li><li>You can drag and drop photos into the photo boxes.\
      </li><li>To edit a photo, click on it on the card.\
      </li><li>To add a design accent, expand the design section on the left tool bar and then click and drag the design accent onto the card.\
      </li><li>A professional designer may review and may enhance your photo(s) for the best quality printing\
      </li><li>Visit the <a href="http://www.tinyprints.com/tiny-prints-personalization-creation-features-faq.htm" target="_blank">Frequently Asked Questions</a> section for more information.\
      </li></ul>',TPC_TEXTCARD_HELP:'<ul class="helpText"><li>To edit or add text, click on the text area(s).\
      </li><li>You can change the font typestyle, color and size of your text.\
      </li><li>View our <a href="http://www.tinyprints.com/sample-greetings-verses.htm" target="_blank">suggested verses</a> for sample text.\
      </li><li>To add a design accent, expand the design section on the left tool bar and then click and drag the design accent onto the card.\
      </li><li>Visit the <a href="http://www.tinyprints.com/tiny-prints-personalization-creation-features-faq.htm" target="_blank">Frequently Asked Questions</a> section for more information.\
      </li></ul>',TP_TEXTCARD_HELP:'<ul class="helpText"><li>To edit or add text, click on the text area(s).\
      </li><li>You can change the font typestyle, color and size of your text.\
      </li><li>View our <a href="http://www.tinyprints.com/sample-greetings-verses.htm" target="_blank">suggested verses</a> for sample text.\
      </li><li>To add a design accent, expand the design section on the left tool bar and then click and drag the design accent onto the card.\
      </li><li>Visit the <a href="http://www.tinyprints.com/tiny-prints-personalization-creation-features-faq.htm" target="_blank">Frequently Asked Questions</a> section for more information.\
      </li></ul>',TPC_LOGOCARD_HELP:'<ul class="helpText"><li>To edit or add text, click on the text area(s).\
      </li><li>View our <a href="http://www.tinyprints.com/sample-greetings-verses.htm" target="_blank">suggested verses</a> for sample text.\
      </li><li>You can add photos or logos to the tray by clicking "Add Photo" at the bottom of the page.\
      </li><li>Our photo tray can hold up to 20 files. If you already have 20 files in your tray, you must remove files before you can add others.\
      </li><li>You can drag and drop photos into any of the logo or photo boxes.\
      </li><li>To edit your photo, click on it on the card preview.\
      </li><li>To add a design accent, expand the design section on the left tool bar and then click and drag the design accent onto the card.\
      </li><li>A professional designer may review and may enhance your photo(s) for the best quality printing\
      </li><li>Visit the <a href="http://www.tinyprints.com/tiny-prints-personalization-creation-features-faq.htm" target="_blank">Frequently Asked Questions</a> section for more information.\
      </li><li>You can customize this card with your company logo or photo using our web-based upload system. See our FAQ section for more <a href="http://www.tinyprints.com/tiny-prints-corporate-holiday-faq.htm#c1" target="_blank">information</a>.\
      </li></ul>',WPD_HELP:'<ul class="helpText"><li>To edit or add text, either click on the text areas on the card or click the text edit boxes on the right hand side of the page.</li><li>To change the font, font size or font color, highlight the text style box you want to edit and then select a font from the highlighted dropdown menu.</li><li>Add photos to your photo tray by clicking "Add/Remove Photos" at the bottom of the page.</li><li>To add photos to your card, drag photos from your photo tray and drop them into the photo boxes.</li><li>A professional designer may review and enhance your personalized order to ensure a high quality finished product.</li><li>If you would like to further customize your card but are unable to do so in the personalization process, please enter your request in the special instructions section. Our designers will do their best to accommodate your request.</li></ul>'};
