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={CHAR_CODE_ENTER:13,PAPER_TYPE_STUDIO_BASIC:18,STORE_NAME_TP:'tp',STORE_NAME_WPD:'wpd',STORE_NAME_TREAT:'gc',STORE_ID_TP:1,STORE_ID_WPD:2,STORE_ID_TREAT:3,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();}}}}},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;},deleteCookie:function(name,path,domain){if(TP.getCookie(name))document.cookie=name+'='+
((path)?';path='+path:'')+
((domain)?';domain='+domain:'')+';expires=Thu, 01-Jan-1970 00:00:01 GMT';},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){try{return string.substring(0,1).toUpperCase()+string.substring(1);}catch(e){return'';}},ucWords:function(string){try{return string.replace(/(^|\s)([a-z])/g,function(m,p1,p2){return p1+p2.toUpperCase();});}catch(e){return'';}},trim:function(string){try{return string.replace(/^\s+|\s+$/g,"");}catch(e){return'';}},sqlTimeStringToDate:function(sqlTimeString){var date_array=sqlTimeString.split(" ");var yyyymmdd_array=date_array[0].split("-");try{var hhmmss_array=date_array[1].split(":");}catch(e){var hhmmss_array=[0,0,0];}
return new Date(yyyymmdd_array[0],yyyymmdd_array[1]-1,yyyymmdd_array[2],hhmmss_array[0],hhmmss_array[1],hhmmss_array[2],0);},Console:{init:function(){this.consoleEnabled=false;},enable:function(){this.consoleEnabled=true;this.setupConsole();},disable:function(){this.consoleEnabled=false;},setupConsole:function(){if(this.consoleEnabled){var id='tpconsole';if($(id)==null){this.spacer='&nbsp;&nbsp;&nbsp;';this.tpConsoleDiv=new Element('div',{'id':id});$(document.body).insert(this.tpConsoleDiv);this.tpConsoleClose=new Element('a').update('X');this.tpConsoleClose.href='javascript: TP.Console.closeConsole()';this.tpConsoleDiv.insert(this.tpConsoleClose);this.tpConsoleClear=new Element('a').update('clear');this.tpConsoleClear.href='javascript: TP.Console.clearConsole()';this.tpConsoleDiv.insert(this.tpConsoleClear);this.tpConsoleToggle=new Element('a').update('hide');this.tpConsoleToggle.href='javascript: TP.Console.toggleConsole()';this.tpConsoleDiv.insert(this.tpConsoleToggle);this.tpConsoleSpan=new Element('span');this.tpConsoleDiv.insert(this.tpConsoleSpan);}}},closeConsole:function(){this.tpConsoleDiv.hide();},showConsole:function(){if(this.consoleEnabled){this.tpConsoleSpan.show();this.tpConsoleDiv.show();}},logObject:function(obj,objKey,level){var cont='';if(objKey){cont+=objKey+' : ';}
for(j=0;j<level;j++){cont+=this.spacer;}
level++;for(key in obj){if(typeof obj[key]==="function"){continue;}
cont+='<br/>';for(j=0;j<level;j++){cont+=this.spacer;}
if(typeof obj[key]==="object"){cont+=this.logObject(obj[key],key,level+1);}else{cont+=key+' : '+obj[key];}}
return cont;},log:function(){if(this.consoleEnabled){var content=this.tpConsoleSpan.innerHTML;content+='<br/>';for(var i=0;i<arguments.length;i++){if(typeof arguments[i]==="object"){content+=this.logObject(arguments[i],null,1)+'<br/>';}else{content+=arguments[i];content+=this.spacer;}}
this.tpConsoleSpan.update(content);this.showConsole();}},clearConsole:function(){this.tpConsoleDiv.remove();this.setupConsole();},toggleConsole:function(){if(this.tpConsoleSpan.visible()){this.tpConsoleSpan.hide();this.tpConsoleToggle.update('show');}else{this.tpConsoleSpan.show();this.tpConsoleToggle.update('hide');}},addLoadEvent:function(func){var oldonload=window.onload;if(typeof window.onload!='function'){window.onload=func;}else{window.onload=function(){if(oldonload){oldonload();}
func();}};}},checkValidDate:function(month,date,year){if(date<=0){return false;}
var isValid=true;month=parseInt(month);if(month==1||month==3||month==5||month==7||month==8||month==10||month==12){if(date>31){isValid=false;}}else if(month==4||month==6||month==9||month==11){if(date>30){isValid=false;}}else{if(((year%4==0)&&(year%100!=0))||(year%400==0)){if(date>29){isValid=false;}}else{if(date>28){isValid=false;}}}
return isValid;},init:function(){this.ie6=(window.external&&typeof window.XMLHttpRequest=='undefined');this.ie7=((navigator.appVersion.indexOf('MSIE 7.')==-1)?false:true);this.ie8=((navigator.appVersion.indexOf('MSIE 8.')==-1)?false:true);this.safari=(/Safari/.test(navigator.userAgent));if(typeof console!=='object'||typeof console.log!=='function'){window.console=TP.Console;window.console.init();}
if(typeof Array.prototype.indexOf==='undefined'){console.log('Needs Array.indexOf');Array.prototype.indexOf=function(obj){for(var i=0;i<this.length;i++){if(this[i]==obj)
return i;}
return-1;}}
TP.Site.EventManager.initEvents();},enableConsole:function(){if(this.isIe()){TP.Console.enable();}},isIe:function(){return(this.ie6||this.ie7||this.ie8);},arrayIntersection:function(array1,array2){var intersectionArray=[];for(var i=0;i<array1.length;i++){if(array2.indexOf(array1[i])!=-1){intersectionArray.push(array1[i]);}}
return intersectionArray;},bin2dec:function(x){if((/[^0-1]/g.test(x))||x==""){return null;}
return parseFloat(x,2);},dec2bin:function(x){if((/[^0-9]/g.test(x))||x==""){return null;}
x=parseFloat(x);return x.toString(2);},arrayMultiIntersection:function(arraySet){var multiIntersection=[];var lookupTable={};var rowCt=arraySet.length;var colCt,pid;for(var i=0;i<rowCt;i++){colCt=arraySet[i].length;for(var j=0;j<colCt;j++){pid=arraySet[i][j];if(!lookupTable[pid]){lookupTable[pid]=[i,1];}else{if(i!=lookupTable[pid][0]){lookupTable[pid][0]=i;lookupTable[pid][1]++;if(lookupTable[pid][1]==rowCt){multiIntersection.push(pid);}}}}}
if(rowCt==1){for(var pId in lookupTable){multiIntersection.push(pId);}}
return multiIntersection;},center:function(element,centerX,centerY){var viewportWidth=document.viewport.getWidth();var viewportHeight=document.viewport.getHeight();if(centerY){if((viewportHeight/2-element.getHeight()/2)<0){element.style.top='0px';}else{element.style.top=viewportHeight/2-element.getHeight()/2+'px';}}
if(centerX){if((viewportWidth/2-element.getWidth()/2)<0){element.style.left='0px';}else{element.style.left=viewportWidth/2-element.getWidth()/2+'px';}}},cookieCheck:function(){var phpSessId=TP.getCookie('PHPSESSID');if(!phpSessId||phpSessId.length<10){alert('Please enable your browser\'s cookies to continue. Need help? Get instructions');window.location='http://answers.tinyprints.com/app/answers/detail/a_id/267/kw/browser';}},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"},{string:navigator.vendor,subString:"Google",identity:"Chrome"},{string:navigator.vendor,subString:"Apple",identity:"Firefox"},{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.5'},{os:'Mac',browser:'Firefox',version:'3.6'},{os:'Mac',browser:'Firefox',version:'4.0'},{os:'Mac',browser:'Firefox',version:'5.0'},{os:'Mac',browser:'Firefox',version:'6.0'},{os:'Mac',browser:'Chrome',version:'5'},{os:'Mac',browser:'Chrome',version:'6'},{os:'Mac',browser:'Chrome',version:'7'},{os:'Mac',browser:'Chrome',version:'8'},{os:'Mac',browser:'Chrome',version:'9'},{os:'Mac',browser:'Chrome',version:'10.0'},{os:'Mac',browser:'Chrome',version:'11.0'},{os:'Mac',browser:'Chrome',version:'12.0'},{os:'Mac',browser:'Chrome',version:'13.0'},{os:'Windows/XP',browser:'Firefox',version:'3.5'},{os:'Windows/XP',browser:'Firefox',version:'3.6'},{os:'Windows/XP',browser:'Firefox',version:'4.0'},{os:'Windows/XP',browser:'Firefox',version:'5.0'},{os:'Windows/XP',browser:'Firefox',version:'6.0'},{os:'Windows/XP',browser:'Chrome',version:'5'},{os:'Windows/XP',browser:'Chrome',version:'6'},{os:'Windows/XP',browser:'Chrome',version:'7'},{os:'Windows/XP',browser:'Chrome',version:'8'},{os:'Windows/XP',browser:'Chrome',version:'9'},{os:'Windows/XP',browser:'Chrome',version:'10.0'},{os:'Windows/XP',browser:'Chrome',version:'11.0'},{os:'Windows/XP',browser:'Chrome',version:'12.0'},{os:'Windows/XP',browser:'Chrome',version:'13.0'},{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.6'},{os:'Windows/Vista',browser:'Firefox',version:'4.0'},{os:'Windows/Vista',browser:'Firefox',version:'5.0'},{os:'Windows/Vista',browser:'Firefox',version:'6.0'},{os:'Windows/Vista',browser:'Chrome',version:'5'},{os:'Windows/Vista',browser:'Chrome',version:'6'},{os:'Windows/Vista',browser:'Chrome',version:'7'},{os:'Windows/Vista',browser:'Chrome',version:'8'},{os:'Windows/Vista',browser:'Chrome',version:'9'},{os:'Windows/Vista',browser:'Chrome',version:'10.0'},{os:'Windows/Vista',browser:'Chrome',version:'11.0'},{os:'Windows/Vista',browser:'Chrome',version:'12.0'},{os:'Windows/Vista',browser:'Chrome',version:'13.0'},{os:'Windows/Vista',browser:'Explorer',version:'7'},{os:'Windows/Vista',browser:'Explorer',version:'8'},{os:'Linux',browser:'Firefox',version:'3.5'},{os:'Linux',browser:'Firefox',version:'3.6'},{os:'Linux',browser:'Firefox',version:'4.0'},{os:'Linux',browser:'Firefox',version:'5.0'},{os:'Linux',browser:'Firefox',version:'6.0'},{os:'Linux',browser:'Chrome',version:'5'},{os:'Linux',browser:'Chrome',version:'6'},{os:'Linux',browser:'Chrome',version:'7'},{os:'Linux',browser:'Chrome',version:'8'},{os:'Linux',browser:'Chrome',version:'9'},{os:'Linux',browser:'Chrome',version:'10.0'},{os:'Linux',browser:'Chrome',version:'11.0'},{os:'Linux',browser:'Chrome',version:'12.0'},{os:'Linux',browser:'Chrome',version:'13.0'},{os:'Windows/7',browser:'Explorer',version:'7'},{os:'Windows/7',browser:'Explorer',version:'8'},{os:'Windows/7',browser:'Chrome',version:'5'},{os:'Windows/7',browser:'Chrome',version:'6'},{os:'Windows/7',browser:'Chrome',version:'7'},{os:'Windows/7',browser:'Chrome',version:'8'},{os:'Windows/7',browser:'Chrome',version:'9'},{os:'Windows/7',browser:'Chrome',version:'10.0'},{os:'Windows/7',browser:'Chrome',version:'11.0'},{os:'Windows/7',browser:'Chrome',version:'12.0'},{os:'Windows/7',browser:'Chrome',version:'13.0'},{os:'Windows/7',browser:'Firefox',version:'3.5'},{os:'Windows/7',browser:'Firefox',version:'3.6'},{os:'Windows/7',browser:'Firefox',version:'4.0'},{os:'Windows/7',browser:'Firefox',version:'5.0'},{os:'Windows/7',browser:'Firefox',version:'6.0'}],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;}
else if(TP.BrowserDetect.browser=='Firefox'){if(parseFloat(TP.BrowserDetect.version)>=3.5){this.supported=true;break;}}
else if(TP.BrowserDetect.browser=='Chrome'){if(parseFloat(TP.BrowserDetect.version)>=5){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.cookieCheck();}}};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));}}}
if(typeof Event.wheel==='undefined'){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 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 PrettySelect2=function(containerDomId,parameters){if(typeof parameters=='undefined'){parameters={};}
this.initialize(containerDomId,parameters);};PrettySelect2.prototype={initialize:function(containerDomId,parameters){this.elContainer=null;this.containerDomId=containerDomId;this.parameters=parameters;this.debug=false;this.enabled=true;this.selectedItem=null;this.selectedIndex=-1;this.lastItem=null;this.firstItem=null;this.listShown=false;this.rendered=false;this.listShim=null;this.options=[];if(typeof containerDomId=='undefined'||containerDomId==null||containerDomId==false){this.elContainer=document.createElement('div');this.elContainer.id='PrettySelect2_auto_'+(new Date().getTime());}else if(typeof containerDomId=='string'){this.elContainer=document.getElementById(containerDomId);if(this.elContainer==null){this.elContainer=document.createElement('div');this.elContainer.id=containerDomId;}}else if(typeof containerDomId=='object'){this.elContainer=containerDomId;}else{this.elContainer=document.getElementById(containerDomId);}
if(typeof this.parameters!=='undefined'){if(typeof this.parameters.debug!=='undefined'){this.debug=this.parameters.debug;}
if(typeof this.parameters.enabled!=='undefined'){this.enabled=this.parameters.enabled;}
if(typeof this.parameters.prefix!=='undefined'){this.prefix=this.parameters.prefix;}else{this.prefix=this.elContainer.id+"_";}
if(typeof this.parameters.handleimageclassname!=='undefined'){this.handleimageclassname=this.parameters.handleimageclassname;}else{this.handleimageclassname="sprite-icon-prettyselectarrow";}
if(typeof this.parameters.renderFn=='function'){this.renderItemFn=this.parameters.renderFn;}
if(typeof this.parameters.postSelect=='function'){this.postSelect=this.parameters.postSelect;}
if(typeof this.parameters.postRender=='function'){this.postRender=this.parameters.postRender.bind(this);}
if(typeof this.parameters.options!=='undefined'){for(var idx=0;idx<this.parameters.options.length;idx++){var option=this.parameters.options[idx];if(typeof option.renderParameters=='undefined'){this.add(option.value,option.text);}else{this.add(option.value,option.text,option.renderParameters);}}}}
if(this.options.length>0){this.render();}},clearOptions:function(){this.options=[];this.selectedItem=null;this.selectedIndex=-1;this.lastItem=null;this.firstItem=null;},itemOnMouseOver:function(event,item){item.oldClass=item.className;item.className+=" PrettySelectItemHover";},itemOnMouseOut:function(event,item){if(item.oldClass)
item.className=item.oldClass;},documentOnClick:function(event){if(typeof event.srcElement!=='undefined'){var target=event.srcElement;}else{var target=event.target;}
var ancestors=TP.ancestors(target);for(var idx=0;idx<ancestors.length;idx++){if(ancestors[idx]==this.elContainer){return;}}
if(this.listVisible()){this.hideList();}},renderSeperator:function(){var elSeparator=document.createElement("div");elSeparator.className="PrettySelectSeperator";return elSeparator;},renderSelectedItem:function(){this.elSelectedItem.innerHTML="";var elHandle=document.createElement("div");elHandle.id="handle";elHandle.className="PrettySelectHandle";var elHandleImage=document.createElement("div");elHandleImage.className=this.handleimageclassname;elHandle.appendChild(elHandleImage);this.elSelectedItem.appendChild(elHandle);var renderedItem=this.selectedItem.render();this.elSelectedItem.appendChild(renderedItem);},renderSelectedItem:function(){this.elSelectedItem.innerHTML="";var elHandle=document.createElement("div");elHandle.id="handle";elHandle.className="PrettySelectHandle";var elHandleImage=document.createElement("div");elHandleImage.className=this.handleimageclassname;elHandle.appendChild(elHandleImage);this.elSelectedItem.appendChild(elHandle);var renderedItem=this.selectedItem.render();this.elSelectedItem.appendChild(renderedItem);},renderListFn:function(){this.elListContainer=document.createElement("div");this.elListContainer.id=this.prefix+"list";this.elListContainer.className="PrettySelectList";return this.elListContainer;},render:function(){if(this.elContainer.tagName.toUpperCase()=="SELECT"){var counter=0;for(var i=0;i<this.elContainer.childNodes.length;i++){var node=this.elContainer.childNodes[i];if(node.tagName){switch(node.tagName.toUpperCase()){case'OPTION':var stripingClass=(counter%2==0)?'prettySelectOptionEven':'prettySelectOptionOdd';this.add(node.value,node.innerHTML,{subItem:false,stripingClass:stripingClass});counter++;break;case'OPTGROUP':this.addGroup(node.label);counter=0;for(var j=0;j<node.childNodes.length;j++){var subNode=node.childNodes[j];if(subNode.tagName){if(subNode.tagName.toUpperCase()=='OPTION'){var stripingClass=(counter%2==0)?'prettySelectOptionEven':'prettySelectOptionOdd';this.add(subNode.value,subNode.innerHTML,{subItem:true,stripingClass:stripingClass});counter++;}}}
break;default:break;}}}
var newContainer=document.createElement("div");newContainer.id=this.elContainer.id;newContainer.className=this.elContainer.className;this.elContainer.parentNode.replaceChild(newContainer,this.elContainer);this.elContainer=newContainer;}
this.elContainer.innerHTML="";this.elInput=document.createElement("input");this.elInput.id=this.prefix+'input';this.elInput.name=this.prefix+'input';this.elInput.type="hidden";this.elContainer.appendChild(this.elInput);if(!this.rendered){if(this.elContainer.addEventListener){this.elContainer.addEventListener('click',this.toggleList.bindAsEventListener(this),false);}else if(this.elContainer.attachEvent){this.elContainer.attachEvent('onclick',this.toggleList.bindAsEventListener(this));}
if(document.addEventListener){document.addEventListener('click',this.documentOnClick.bindAsEventListener(this),false);}else if(document.attachEvent){document.attachEvent('onclick',this.documentOnClick.bindAsEventListener(this));}}
this.elSelectedItem=document.createElement("div");this.elSelectedItem.id=this.prefix+"selected";this.elSelectedItem.className="PrettySelectItem SelectedPrettySelectItem"
this.elContainer.appendChild(this.elSelectedItem);this.select(null);this.elListContainer=this.renderListFn();this.elListContainer.style.position='absolute';this.elContainer.appendChild(this.elListContainer);this.elListContainer.style.display='none';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.elListContainer.parentNode.insertBefore(this.listShim,this.elListContainer);}else{this.ie=false;}
var firstItem=this.getFirstItem();var stop=false;if(!firstItem){stop=true;}
while(!stop){var renderedItem=firstItem.render();if(firstItem.getType()==='item'){if(renderedItem.addEventListener){renderedItem.addEventListener('click',this.select.bind(this,firstItem.getValue()),false);}else if(renderedItem.attachEvent){renderedItem.attachEvent('onclick',this.select.bind(this,firstItem.getValue()));}
if(renderedItem.addEventListener){renderedItem.addEventListener('mouseover',this.itemOnMouseOver.bindAsEventListener(this,renderedItem),false);}else if(renderedItem.attachEvent){renderedItem.attachEvent('onmouseover',this.itemOnMouseOver.bindAsEventListener(this,renderedItem));}
if(renderedItem.addEventListener){renderedItem.addEventListener('mouseout',this.itemOnMouseOut.bindAsEventListener(this,renderedItem),false);}else if(renderedItem.attachEvent){renderedItem.attachEvent('onmouseout',this.itemOnMouseOut.bindAsEventListener(this,renderedItem));}}
this.elListContainer.appendChild(renderedItem);firstItem=firstItem.getNext();if(firstItem==null){stop=true;}else{var separator=this.renderSeperator();this.elListContainer.appendChild(separator);}}
if(typeof this.postRender=='function'){this.postRender();}
this.rendered=true;},select:function(selectedValue){if(this.options.length!==0){if(this.selectedItem==null){var selectedItem=this.getFirstItem();while(selectedItem.getType()==='group'){selectedItem=selectedItem.getNext();}
this.selectedIndex=this.getSelectedIndex(selectedItem.getValue());this.selectedItem=selectedItem;selectedValue=this.selectedItem.getValue();var doNothing=false;}else{var previousValue=this.selectedItem.getValue();var doNothing=(previousValue==selectedValue);this.selectedIndex=this.getSelectedIndex(selectedValue);this.selectedItem=this.options[this.selectedIndex];for(var i=0,iLeng=this.elListContainer.childNodes.length;i<iLeng;i++){var nodeClassName,node=this.elListContainer.childNodes[i];if(node.tagName&&node.className&&(node.className.indexOf('PrettySelectItemContent')>0)){nodeClassName=node.className;if(nodeClassName.indexOf('PrettySelectItemHover')>0){node.className=nodeClassName.replace('PrettySelectItemHover','');}
if(node.id==(this.prefix+selectedValue)&&(node.className.indexOf('PrettySelectItemHover')<0)){node.className=node.className+' PrettySelectItemHover';}}}}
if(!doNothing){var selectedItem=this.getSelectedItem();if(selectedItem){this.elInput.value=selectedItem.getValue();if(this.selectedIndex!==-1){this.renderSelectedItem();}
if(typeof this.postSelect=='function'){this.postSelect(this,selectedValue);}}}}},toggleList:function(){if(this.enabled){if(this.listShown){this.hideList();}else{this.showList();}}},showList:function(){this.listShown=true;var selectedValue=this.getSelectedItem().getValue();this.select(selectedValue);this.elListContainer.style.display='';if(this.ie==true){this.listShim.style.display=this.elListContainer.style.display;this.listShim.style.width=this.elListContainer.offsetWidth;this.listShim.style.height=this.elListContainer.offsetHeight;this.listShim.style.top=this.elListContainer.style.top;this.listShim.style.left=this.elListContainer.style.left;this.listShim.style.zIndex=this.elListContainer.style.zIndex-1;}},hideList:function(){this.listShown=false;this.elListContainer.style.display='none';if(this.ie==true){this.listShim.style.display=this.elListContainer.style.display;this.listShim.style.width=this.elListContainer.offsetWidth;this.listShim.style.height=this.elListContainer.offsetHeight;this.listShim.style.top=this.elListContainer.style.top;this.listShim.style.left=this.elListContainer.style.left;this.listShim.style.zIndex=this.elListContainer.style.zIndex-1;}},listVisible:function(){return this.listShown;},add:function(value,text,renderParameters,asGroup){if(typeof renderParameters=='undefined'){var parameters={};}else{var parameters=renderParameters;}
if(asGroup){var item=new PrettySelectGroup(this,{text:text});}else{var item=new PrettySelectItem(this,{value:value,text:text,renderFn:this.renderItemFn,renderParameters:parameters});}
var itemValue=item.getValue();if(!this.lastItem){item.setNext(null);item.setPrevious(null);this.lastItem=item;this.firstItem=item;}else if(this.options.length>0){if(typeof position!=='undefined'){var targetItem=this.parameters[position.getValue()];var previousItem=targetItem.getPrevious();targetItem.setPrevious(item);previousItem.setNext(item);item.setNext(targetItem);item.setPrevious(previousItem);}else{item.setNext(null);item.setPrevious(this.getLastItem());this.lastItem=item;item.getPrevious().setNext(item);}}
this.options.push(item);},addGroup:function(text){this.add(text,text,{},true);},remove:function(index){var itemToRemove=this.options[index];var previousItem=itemToRemove.getPrevious();var nextItem=itemToRemove.getNext();if(previousItem!==null){previousItem.setNext(nextItem);}
if(nextItem!==null){nextItem.setPrevious(previousItem);}
this.options.length--;delete this.options[index];},getSelectedItem:function(){if(this.selectedIndex!==-1){return this.options[this.selectedIndex];}else{return false;}},getSelectedIndex:function(selectedValue){var selectedIndex=-1;for(var idxOption=0;idxOption<this.options.length;idxOption++){var option=this.options[idxOption];if(option.getValue()==selectedValue){selectedIndex=idxOption;}}
return selectedIndex;},getLastItem:function(){return this.lastItem;},getFirstItem:function(){return this.firstItem;},getPrefix:function(){if(typeof this.prefix!=='undefined'){return this.prefix;}else{return"";}},getContainer:function(){return this.elContainer;},getListContainer:function(){return this.elListContainer;},disable:function(){this.enabled=false;},enable:function(){this.enabled=true;},getValue:function(){var selectedItem=this.getSelectedItem();if(selectedItem!==false){return selectedItem.getValue();}else{return null;}}};var PrettySelectItem=function(container,parameters){this.initialize(container,parameters);};PrettySelectItem.prototype={initialize:function(container,parameters){this.next=null;this.previous=null;this.prefix=null;this.select=container;this.parameters=parameters;this.container=container;if(typeof this.parameters!=='undefined'){if(typeof this.parameters.value!=='undefined'){this.value=this.parameters.value;this.text=this.parameters.value;this.containerId=this.select.getPrefix()+this.parameters.value}else{throw"No value was specified for the option.";}
if(typeof this.parameters.text!=='undefined'){this.text=this.parameters.text;}
if(typeof this.parameters.renderFn=='function'){this.renderFn=this.parameters.renderFn;}else{this.renderFn=function(renderParams){var elContainer=document.createElement("div");elContainer.id=this.containerId;elContainer.innerHTML=this.text;elContainer.className="PrettySelectItem";if(renderParams.subItem){elContainer.className+=' indented';}
if(renderParams.stripingClass){elContainer.className+=' '+renderParams.stripingClass;}
return elContainer;}}
if(typeof this.parameters.renderParameters!=='undefined'){this.renderParameters=this.parameters.renderParameters;}}},getType:function(){return'item';},getPrevious:function(){return this.previous;},setPrevious:function(item){this.previous=item;},getNext:function(){return this.next;},setNext:function(item){this.next=item;},getValue:function(){return this.value;},setValue:function(newValue){this.value=newValue;},getRenderParameters:function(){var renderParameters={value:this.value,text:this.text,containerId:this.containerId};TP.extendObject(renderParameters,this.renderParameters);this.renderParameters=renderParameters;return renderParameters;},render:function(){var renderParameters=this.getRenderParameters();var renderFn=this.renderFn.bind(this,renderParameters);var renderedItem=renderFn();var elContainer=document.createElement("div");elContainer.id=this.containerId;elContainer.className="PrettySelectItem PrettySelectItemContent";if(renderParameters.stripingClass){elContainer.className+=' '+renderParameters.stripingClass;}
elContainer.appendChild(renderedItem);return elContainer;}};var PrettySelectGroup=function(container,params){this.select=container;this.container=container;this.parameters=params;if(typeof this.parameters!=='undefined'){this.containerId=this.select.getPrefix()+'_GROUP_'+new Date().getTime();if(typeof this.parameters.text!=='undefined'){this.text=this.parameters.text;}else{throw"No value was specified for the option.";}
if(typeof this.parameters.renderFn=='function'){this.renderFn=this.parameters.renderFn;}else{this.renderFn=function(){var elContainer=document.createElement("div");elContainer.id=this.containerId;elContainer.innerHTML=this.text;elContainer.className="PrettySelectGroup";return elContainer;}}}}
PrettySelectGroup.prototype={getType:function(){return'group';},getPrevious:function(){return this.previous;},setPrevious:function(item){this.previous=item;},getNext:function(){return this.next;},setNext:function(item){this.next=item;},getValue:function(){return this.value;},setValue:function(newValue){this.value=newValue;},render:function(){try{var renderFn=this.renderFn.bind(this);var renderedItem=renderFn();var elContainer=document.createElement("div");elContainer.id=this.containerId;elContainer.className="PrettySelectGroupContainer";elContainer.appendChild(renderedItem);}catch(e){}
return elContainer;}}
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,onClick:null};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(typeof this.options.onClick==='function'){this.box.observe('click',this.options.onClick);}
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,VARIABLE_CODE_STATE:'_STATE_',VARIABLE_CODE_ADDRESS:'_ADDRESS_',VARIABLE_CODE_ADDRESS_LINE1:'_ALADDRESS1_',VARIABLE_CODE_ADDRESS_LINE2:'_ALADDRESS2_',VARIABLE_CODE_ADDRESS_RECEPTION:'_RCADDRESS_',NON_PREVIEW_WITH_ENVELOPE:4,NON_PREVIEW_WITHOUT_ENVELOPE:5,helpBox:new Array(),regexp:new Array(),giftCardDenominationTextboxName:'giftcard_denomination',giftCardRemoved:false,TEXTBOX_TYPE_PANEL:1,TEXTBOX_TYPE_LAYOUT:2,TEXTBOX_TYPE_DOODLE:3,TEXTBOX_TYPE_SIGNATURE:4,TEXTBOX_TYPE_PERSONALSEAL:5,TEXTBOX_TYPE_MESSAGEBOX:6,TEXTBOX_TYPE_SNAPSHOT:7,TEXTBOX_TYPE_PHOTOGRAPHER:8,DELIVERY_METHOD_ADDRESS:1,DELIVERY_METHOD_EMAIL:2,DELIVERY_USER:1,DELIVERY_RECIPIENT:2,TEXTURE_TYPE_FOLDED:2,baseResolution:null,popupZIndex:50001,maskZIndex:50000,editorZIndex:40000,handleZIndex:10000,borderZIndex:50,photoZIndex:100,textboxZIndex:200,layoutZIndex:300,overlayZIndex:400,separatorZIndex:500,doodleZIndex:900,dynamicTextboxZIndex:1000,trimOptionZIndex:2000,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,PANELTYPE_ID_FRONT:1,PANELTYPE_ID_INSIDE:2,PANELTYPE_ID_BACK:3,PANELTYPE_ID_AUTOBACK:4,SERVICE_MYSQL:1,SERVICE_MONGO:2,mainElement:$('pageContainer'),renderingDecimalPrecision:0,maxUserPhotos:30,userPhotos:[],adminPhotos:[],hashStepName:null,returnAddressLabelData:{returnAddressLabel:null,returnAddressLabelProductId:null,returnAddressLabelQuantity:null},digitalServices:{rsvp:1,snapshot:2},ie6:(window.external&&typeof window.XMLHttpRequest=='undefined'),ie7:((navigator.appVersion.indexOf('MSIE 7.')==-1)?false:true),ie8:((navigator.appVersion.indexOf('MSIE 8.')==-1)?false:true),ie9:((navigator.appVersion.indexOf('MSIE 9.')==-1)?false:true),safari:(/Safari/.test(navigator.userAgent)),isIe:function(){return(this.ie6||this.ie7||this.ie8||this.ie9);},environment:null,hosts:{"static":null,images:null,imagesProxy:null},store:null,steps:[],uris:[],eventHandlers:{'changecolor':[],'showbackbutton':[],'changepanel':[],'changelayout':[],'changegiftcard':[],'infoentered':[],'login':[],'personalizestepsave':[],'previewstepsave':[],'envelopestepsave':[],'recipientstepsave':[],'deliverystepsave':[],'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':[],'deliverymethodchange':[],'requestpaymentupdate':[],'contactsloaded':[],'urlpanelchanged':[],'personalizationsaved':[],'personalizationchanged':[],'enterinfoloaded':[],'changetrimoption':[],'panelimageloaded':[],'importphotographerphoto':[],'memberlogin':[],'mongosaved':[],'snapshoturlchecked':[]},activeStepIndex:null,activeStep:null,preShippedEnvelopes:false,numbersToWords:{0:'zero',1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine'},photographerId:null,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(!this.errorManager){this.errorManager=new ErrorManager();}
if(!Personalize.personalization){Personalize.personalization={};Personalize.personalization.id=null;}
this.baseResolution=144;if(window.opera){history.navigationMode='compatible';}
Event.observe(window,'unload',function(){Personalize.services.saveSessionPersonalization();});$('saveButton').hide();if(!Personalize.productPhotoEffects){Personalize.productPhotoEffects={};var productEffectsCookie=TP.getCookie("productPhotoEffects_v5");if(productEffectsCookie){Personalize.productPhotoEffects=JSON.parse(TP.getCookie("productPhotoEffects_v5"));}}
Personalize.gcEventData={};var gcEventDataCookie=TP.getCookie("gcData");if(gcEventDataCookie){gcEventDataCookie=decodeURIComponent(decodeURIComponent(gcEventDataCookie));Personalize.gcEventData=JSON.parse(gcEventDataCookie);}
var digitalServiceCookie=TP.getCookie('TP_DigitalService');if(digitalServiceCookie){digitalServiceCookie=decodeURIComponent(digitalServiceCookie).evalJSON();Personalize.rsvp.url=digitalServiceCookie.url;Personalize.rsvp.optIn=digitalServiceCookie.optIn;}},setStepUrl:function(){var hash=this.steps[this.activeStepIndex].name;if(Personalize.personalization.mongoId){hash+='_'+Personalize.personalization.mongoId;}else if(Personalize.personalization.id){hash+='_'+Personalize.personalization.id;}
if(!(window.location.hash==''&&hash=='enterInfo')){window.location.hash=hash;}},registerSteps:function(stepsArray){this.steps=stepsArray;for(var stepId in this.steps){var step=this.steps[stepId];step.id=step.number=stepId;this.steps[stepId].init();}
this.activeStepIndex=this.findFirstAvailableStep();this.activeStep=this.steps[this.activeStepIndex];if(this.hashStepName){this.activeStep=this.getStepByName(this.hashStepName);this.activeStepIndex=this.getStepIndexByName(this.hashStepName);}else{if(Personalize.personalization.savedStep&&!this.isRepersonalization()){for(var stepId in this.steps){if(this.steps[stepId].element.id==Personalize.personalization.savedStep){if(this.steps[stepId].available&&this.steps[stepId].firstActivation!=false){this.activeStep=this.steps[stepId];this.activeStepIndex=stepId;}else{this.activeStepIndex=this.findPreviousAvailableStep(stepId);this.activeStep=this.steps[this.activeStepIndex];}}}}}
if(Personalize.header){Personalize.header.renderStepNavigation();}
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;},getStepIndexByName:function(stepName){for(var stepId in this.steps){step=this.steps[stepId];if(step.name===stepName)return stepId;}},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',this.steps[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',this.steps[newStep].name);this.activeStep.deactivate();this.activeStepIndex=newStep;this.activeStep=this.steps[this.activeStepIndex];this.activeStep.activate(false);this.updateNavigationTabs();this.setStepUrl();}}else{if(this.activeStep){if(this.activeStep.back){this.activeStep.back();}}}},finishRepersonalization:function(){Personalize.services.savePersonalization(false,function(){try{var destination='/resubmitConfirm.html';var formElement=new Element('form',{action:destination,method:'POST',style:'display: none;'});var personalizationId=Personalize.personalization.id;var parameterElement=new Element('input',{name:'personalizationId',value:personalizationId});formElement.insert(parameterElement);$(document.body).insert(formElement);formElement.submit();}catch(e){}});},finish:function(){if(this.isRepersonalization()){this.finishRepersonalization();return;}
Personalize.services.savePersonalization(false,function(){try{var p=Personalize.personalization;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,p13nMongoId:p.mongoId,instructions:p.instructions,envelopeId:finalEnvelopeId,innerEnvelopeId:finalInnerEnvelopeId,additionalEnvelopes:p.additionalEnvelopes,returnAddress:(parseFloat(p.returnAddress)==1)?1:0,returnAddressFontId:p.returnAddressFontId,returnAddressFontColorId:p.returnAddressFontColorId,returnAddressFontSize:p.returnAddressFontSize,returnAddressLeading:p.returnAddressLeading,redirect:'/related.html?pid='+p.productId+Personalize.product.color.number};if(typeof(p.returnAddressText)=='object'&&p.returnAddressText){addToCartParameters.returnAddressLine1=p.returnAddressText.name||null;addToCartParameters.returnAddressLine2=p.returnAddressText.streetAddress||null;addToCartParameters.returnAddressLine3=p.returnAddressText.locality||null;addToCartParameters.returnAddressLine4=p.returnAddressText.region+', '+p.returnAddressText.postalCode;}else{var returnAddressLines=(p.returnAddressText)?p.returnAddressText.split('\n'):[];addToCartParameters.returnAddressLine1=returnAddressLines[0]||null;addToCartParameters.returnAddressLine2=returnAddressLines[1]||null;addToCartParameters.returnAddressLine3=returnAddressLines[2]||null;addToCartParameters.returnAddressLine4=returnAddressLines[3]||null;}
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.personalization.primaryProxy.orderId){addToCartParameters.oid=Personalize.personalization.primaryProxy.orderId;}
var destination='/addtocart.php';if(Personalize.isGreetingCard()){addToCartParameters.cardAddresses=Object.toJSON(Personalize.getStepByName('Delivery').getAddressesObject());var activePlan=false;if(Personalize.member){try{activePlan=Personalize.member.gcActivePlan.id;}catch(e){}}
destination='https://'+window.location.hostname+'/greeting/AddToCart';if(Personalize.personalization.gcRedirect){destination+='?gcRedirect='+Personalize.personalization.gcRedirect;}
try{addToCartParameters.fulfillmentInfo=p.fulfillmentInfo;addToCartParameters.deliveryDateType=p.deliveryDateType;}catch(e){}}
var addToCartFormElement=new Element('form',{action:destination,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();}catch(e){console.log(e);}});},activateStep:function(stepName){for(var stepId in this.steps){var step=this.steps[stepId];if(step.name==stepName){this.activeStepIndex=stepId;if(this.activeStep&&this.activeStep!=step){this.trigger('changestep',stepName);this.activeStep.deactivate();this.activeStep=this.steps[this.activeStepIndex];this.activeStep.activate(false);this.updateNavigationTabs();this.setStepUrl();return;}}}},renderNavigationTabs:function(){var tabsListContainer=$("personalizeStepTabsList");if(!tabsListContainer){return;}
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{var title=(step.displayName)?step.displayName:step.title;if($("personalizeStepTitle")){$("personalizeStepTitle").update(title);}
$(step.name+"StepTabName").removeClassName('disabled');if(step.description!==""&&typeof step.description!=="undefined"&&$("personalizeStepDescription")){$("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'});if(!this.isGreetingCard()){try{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();}}}catch(e){}}}}}},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,l=Personalize.eventHandlers[event].length;handlerId<l;handlerId++){var handlerObject=Personalize.eventHandlers[event][handlerId];var handler=handlerObject[0];try{handler.apply(handler,args);}catch(e){}}},observe:function(event,handler,identifier){event=event.toLowerCase();Personalize.eventHandlers[event].push([handler,identifier]);},stopObserve:function(event,identifier){if(identifier){for(var handlerId=Personalize.eventHandlers[event].length-1;handlerId>=0;handlerId--){var handlerObject=Personalize.eventHandlers[event][handlerId];var handler=handlerObject[0];var savedIdentifier=handlerObject[1];if(savedIdentifier==identifier){Personalize.eventHandlers[event].splice(handlerId,1);}}}else{Personalize.eventHandlers[event]=[];}},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];},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.stopObserving('mouseover');element.stopObserving('mouseout');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);},getProductPanelId:function(panelTypeId){for(var panelId in this.product.panels){if(this.product.panels[panelId].panelTypeId==panelTypeId){return panelId;}}
return null;},isRepersonalization:function(){return Boolean(Personalize.repersonalization);},readServiceIsMongo:function(){return(parseFloat(this.readService)==this.SERVICE_MONGO);},writeServiceIsMongo:function(){return(parseFloat(this.writeService)==this.SERVICE_MONGO);},isMongoId:function(id){return(typeof id=="string"&&id.length==24);},isMongoPersonalization:function(){return Boolean(Personalize.personalization.mongoId);},isPhotoMontage:function(){return(Personalize.product.fulfillmentItemType.name=="Photo Montage");},isPlanner:function(){return(Personalize.product.productType.name=="Planners");},isStamp:function(){return(Personalize.product.productType.name=="Stamps");},isMagnet:function(){return(Personalize.product.productType.name=="Magnets");},isNoPreviewNoEnvelope:function(){return(Personalize.product.productType.personalizeTypeId==Personalize.NON_PREVIEW_WITHOUT_ENVELOPE);},isNoPreviewWithEnvelope:function(){return(Personalize.product.productType.personalizeTypeId==Personalize.NON_PREVIEW_WITH_ENVELOPE);},isGreetingCard:function(){return(Personalize.product.fulfillmentItemType.name=="Greeting Card");},isCircularCard:function(){return Boolean(this.product.sizeId=='AR'||this.product.sizeId=='AX'||this.product.sizeId=='AZ');},isSample:function(){return Boolean(Personalize.adminUserId&&Personalize.sample);},isResetCookie:function(){return Boolean(Personalize.resetCookie)&&Personalize.isSample();},hasGiftCard:function(){return(Personalize.isGreetingCard()&&(Personalize.product.giftCards==true)&&(Personalize.product.giftCardClass==true));},hasRsvp:function(){return Boolean(Personalize.rsvp&&parseFloat(Personalize.rsvp.enabled)&&(parseFloat(Personalize.rsvp.digitalServiceId)==this.digitalServices.rsvp));},hasSnapshot:function(){return Boolean(Personalize.rsvp&&parseFloat(Personalize.rsvp.enabled)&&(parseFloat(Personalize.rsvp.digitalServiceId)==this.digitalServices.snapshot));},hasDigitalService:function(){return(this.hasRsvp()||this.hasSnapshot());},isDigitalServiceOn:function(){return(parseFloat(Personalize.personalization.rsvp.optIn)==1);},isBackPanel:function(panelType){return(parseInt(panelType)==this.PANELTYPE_ID_BACK||parseInt(panelType)==this.PANELTYPE_ID_AUTOBACK);},isFrontPanel:function(panelType){return(parseInt(panelType)==this.PANELTYPE_ID_FRONT);},isFoldedCard:function(){return(parseInt(this.product.textureId)==this.TEXTURE_TYPE_FOLDED);},help:function(){if(Personalize.site!='TP'){if(!this.helpDlg){this.helpDlg=new PersonalizePopup('Personalization Help','helpPopup_');var content=this.helpDlg.getPopupElement();var helpText='';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();}
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;},countPanelPhotos:function(panelId){var photoCount=0;var panel=Personalize.product.panels[panelId];if(panel){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;},loadMemberContacts:function(){if(this.memberContactsLoaded)return;var url="http://"+window.location.host+'/addressbook/'+'contacts.json';new Ajax.Request(url,{method:'get',onSuccess:function(transport){this.memberContacts=transport.responseJSON;this.memberContactsLoaded=true;this.trigger('contactsloaded',this.memberContacts);}.bind(this)});},hasLocalStorage:function(){try{return('localStorage'in window&&window['localStorage']!==null);}catch(e){return false;}},getLocalVariable:function(key){if(this.hasLocalStorage()){return(localStorage.getItem(key))?localStorage.getItem(key):TP.getCookie(key);}else{return TP.getCookie(key);}},setLocalVariable:function(key,value,maxCookieSize){if(this.hasLocalStorage()){try{localStorage.setItem(key,value);}catch(e){if(!maxCookieSize||value.length<maxCookieSize){TP.setCookie(key,value);}}}else{if(!maxCookieSize||value.length<maxCookieSize){TP.setCookie(key,value);}}},afterMemberSignin:function(){this.services.getP13nStep().loadUserPhotos();var headerSignIn_OutLink=$('personalize_signin_out');headerSignIn_OutLink.innerHTML="Sign Out";headerSignIn_OutLink.title="Sign Out";},trackPageview:function(pageName){try{_gaq.push(['_trackPageview',pageName]);}catch(e){}}};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.temporaryHideFlag=false;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.closeBoxTxt=new Element('div',{'class':this.cssPrefix+'Close clickable personalizePopupCloseTxt'}).update('Close');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={hidden:true,getPopupElement:function(){return this.contentElement;},showPopup:function(){this.hidden=false;this.maskElement.style.height=document.viewport.getHeight()+'px';this.closeBox.onclick=this.outsideClick.bind(this);this.closeBoxTxt.onclick=this.outsideClick.bind(this);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'});}
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(){this.hidden=true;if(Personalize.apostropheWarningObj){Personalize.apostropheWarningObj.hide();}
for(helpBoxId in Personalize.helpBox){if(Personalize.helpBox[helpBoxId]){if(Personalize.helpBox[helpBoxId].shown){Personalize.helpBox[helpBoxId].close();}}}
if(Personalize.photoUploaderWarningBalloon){Personalize.photoUploaderWarningBalloon.hide();}
Event.stopObserving(document,'keypress',this.keyDownHandler);this.maskElement.hide();this.domElement.hide();},destroy:function(){this.hidden=true;this.domElement.remove();this.maskElement.remove();},suspenseHidePopup:function(){this.hidden=true;if(Personalize.photoUploaderWarningBalloon){Personalize.photoUploaderWarningBalloon.hide();}
this.temporaryHideFlag=true;this.maskElement.setStyle({visibility:'hidden'});this.domElement.setStyle({visibility:'hidden'});},resumeHidePopup:function(){this.hidden=false;this.temporaryHideFlag=false;this.maskElement.setStyle({visibility:'visible'});this.domElement.setStyle({visibility:'visible'});}}
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,totalFileCount:0,failedFileArray:new Array(),overSizedFileArray:new Array(),warningBalloons:new Array(),initialize:function(){this.failedFileArray=new Array();this.uploadedCount=0;this.totalFileCount=0;if(this.warningBalloons.length>0){this.warningBalloons.invoke('hide');}
var warningTitle='<div class = \"sprite-icon-warning\" style = \"float:left; margin-right:6px;\"></div><div>Warning</div>';var warningBalloonMaxPhotos=new WarningPopUp({title:warningTitle,okay:'true',warning:'true',zIndex:60000,right:'true',fixed:'true',outsideClick:false});warningBalloonMaxPhotos.setAnchor(null);this.warningBalloons['warningBalloonMaxPhotos']=warningBalloonMaxPhotos;this.warningBalloons.push(warningBalloonMaxPhotos);var warningBalloonPhotoUpError=new WarningPopUp({title:warningTitle,okay:'true',warning:'true',zIndex:60000,right:'true',fixed:'true',outsideClick:false});warningBalloonPhotoUpError.setAnchor(null);this.warningBalloons['warningBalloonPhotoUpError']=warningBalloonPhotoUpError;this.warningBalloons.push(warningBalloonPhotoUpError);var warningBalloonPhotoOverSized=new WarningPopUp({title:warningTitle,okay:'true',warning:'true',zIndex:60000,right:'true',fixed:'true',outsideClick:false});warningBalloonPhotoOverSized.setAnchor(null);this.warningBalloons['warningBalloonPhotoOverSized']=warningBalloonPhotoOverSized;this.warningBalloons.push(warningBalloonPhotoOverSized);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:TP.getCookie('PHPSESSID'),maxUserPhotos:Personalize.maxUserPhotos};}();return this.environment;},showOverSizePhotoWarning:function(){if(this.overSizedFileArray.length>0){var warningContent="Oops! Some of your photos are too big to upload. We'll have to skip them. <br/> <br/>";warningContent+=this.overSizedFileArray.join("<br/>");var anchor=$('progress-bar');var topOffset=0;this.warningBalloons.each(function(item){if(item.shown){topOffset+=parseFloat(item.domElement.getHeight());}});this.warningBalloons['warningBalloonPhotoOverSized'].setAnchor(anchor);this.warningBalloons['warningBalloonPhotoOverSized'].setMainContent(warningContent);this.warningBalloons['warningBalloonPhotoOverSized'].show(topOffset);this.overSizedFileArray.length=0;}},hideAllWarnings:function(){this.warningBalloons.invoke('hide');},showUploadFailedWarning:function(){if(this.totalFileCount==0||this.failedFileArray.length==0)return;if(this.uploadedCount+this.failedFileArray.length==this.totalFileCount){var anchor=$('progress-bar');var topOffset=0;this.warningBalloons.each(function(item){if(item.shown){topOffset+=parseFloat(item.domElement.getHeight());}});this.warningBalloons['warningBalloonPhotoUpError'].setAnchor(anchor);var warningContent="Oops! There was a problem uploading some of your photos. Please try uploading the following files again: <br/> <br/>";warningContent+=this.failedFileArray.join("<br/>");warningContent+="<br/> <br/>And as always, feel free to contact our stationery specialists by phone, email or Live Chat if you have any questions.";this.warningBalloons['warningBalloonPhotoUpError'].setMainContent(warningContent);if(Personalize.getStepByName('Personalize').photoServices.hidden){Personalize.getStepByName('Personalize').photoServices.addToSuspendedWarnings(this.warningBalloons['warningBalloonPhotoUpError']);}else{this.warningBalloons['warningBalloonPhotoUpError'].show(topOffset);}
this.failedFileArray.length=0;this.totalFileCount=0;Personalize.uploading=false;}},updateUploadStatus:function(responseData){switch(responseData.status){case'totalFiles':this.totalFileCount=parseFloat(responseData.message);break;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);if(this.totalFileCount==this.uploadedCount){Personalize.uploading=false;if(this.responseDataMax){this.progressBar.setProgress(this.responseDataMax,this.responseDataMax);}else{this.progressBar.setDoneProgress();}}
this.showUploadFailedWarning();break;case'updateprogress':Personalize.uploading=true;this.responseDataMax=responseData.max;this.progressBar.setProgress(responseData.min,responseData.max);this.showUploadFailedWarning();break;case'resetprogress':this.progressBar.reset();this.uploadedCount=0;this.hideAllWarnings();break;case'uploadcomplete':Personalize.uploading=false;this.showUploadFailedWarning();break;case'maxallowed':this.warningBalloons['warningBalloonMaxPhotos'].setTitle='<div class = \"sprite-icon-warning\" style = \"float:left; margin-right:6px;\"></div><div>Warning</div>';this.warningBalloons['warningBalloonMaxPhotos'].setMainContent('Oops! You can only store '+Personalize.maxUserPhotos+' images in your account at a time. We\'ll add as many photos as we can if you click "Okay" below, but in order to add extra photos you\'ll need to delete some existing images first.');var anchor=$('progress-bar');this.warningBalloons['warningBalloonMaxPhotos'].setAnchor(anchor);this.warningBalloons['warningBalloonMaxPhotos'].show();this.showUploadFailedWarning();break;case'ioRetry':console.log(responseData.message);break;case'ioerror':this.failedFileArray.push(responseData.message.name);this.showUploadFailedWarning();break;case'oversize':this.overSizedFileArray.push(responseData.message);this.showOverSizePhotoWarning();this.showUploadFailedWarning();break;case'security':this.failedFileArray.push(responseData.message);this.showUploadFailedWarning();break;case'debug':console.log(responseData.message);this.showUploadFailedWarning();break;default:this.showUploadFailedWarning();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',{'id':'progress-bar','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++;}},setDoneProgress:function(){var totalNumBars=parseInt(this.width/this.barWidth);var numberRequiredBar=parseInt(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);this.label.update("Complete "+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 RegularExpression=Class.create({variablecode:null,variablePresent:false,regularExpressionList:null,data:null,initialize:function(variablecode){this.variablecode=variablecode;for(code in Personalize.regularExpressionList){if(this.variablecode==code){this.regularExpressionList=Personalize.regularExpressionList[code];this.variablePresent=true;break;}}},checkForRegularExp:function(data){this.data=data;for(regExp in this.regularExpressionList){var pattern=new RegExp(this.regularExpressionList[regExp],'ig');result=pattern.test(this.data);if(result){return result;}}
return false;},action:function(element){switch(this.variablecode){case'_FAMILYNAME_':case'_LASTNAME_':if(!Personalize.apostropheWarningObj){Title='<div class = \"sprite-icon-info\" style = \"float: left; margin-right: 5px;\"></div><div>Apostrophe Usage</div>';Content='Add an \"s\" to your last name to make it plural (i.e. The Smiths). If your last name ends in \"s\", \"z\", \"x\", \"ch\" or \"sh\" add \"es\" (i.e. The Cruzes). Never add apostrophes unless you\'re indicating possession (i.e. The Smiths\' Home).';Personalize.apostropheWarningObj=new WarningPopUp({title:Title,content:Content,warning:'true',close:'true',right:'true',fixed:'true',zIndex:60000,outsideClick:false});Personalize.apostropheWarningObj.setAnchor(element);}
Personalize.apostropheWarningObj.show();break;}},hasRegularExpression:function(){return this.variablePresent;}});var WarningPopUp=Class.create({initialize:function(options){this.options={title:null,content:null,close:null,okay:null,warning:null,right:null,bottom:null,fixed:null,zIndex:60000,width:230,click:false,giftCard:false,outsideClick:true};this.shown=false;this.options=Object.extend(this.options,options);this.domElement=new Element('div',{'class':'personalizeWarningCallout',style:'width: '+(this.options.width+42)+'px;'});this.contentElement=new Element('div',{'class':'personalizeWarningCalloutContent bg-wrapper'});this.titleWidth=this.options.width;if(this.options.title){if(this.options.close){this.titleWidth=this.titleWidth-30;}
this.titleElement=new Element('div',{'id':'calloutTitle','class':'calloutTitle',style:'float: left; width:'+this.titleWidth+'px;'}).update(this.options.title);this.contentElement.insert(this.titleElement);}
if(this.options.close){this.closeElement=new Element('div',{'id':'calloutClose','class':'clickable sprite-icon-warningclose',style:'float:right; margin:5px;'});this.contentElement.insert(this.closeElement);}
this.mainContentElement=new Element('div',{'id':'calloutContent','class':'calloutContent',style:'clear:both;'});this.contentElement.insert(this.mainContentElement);if(this.options.giftCard){this.titleElement.setStyle({fontSize:'12px'});this.removeGiftCardLink=new Element('div',{'class':'clickable',id:'personalizeRemoveGiftCard'}).update('Remove Gift Card');this.editGiftCardLink=new Element('div',{'class':'clickable',id:'personalizeEditGiftCard'}).update('Edit Gift Card');if(Personalize.product.classId!='170'){this.mainContentElement.insert(this.editGiftCardLink);this.editGiftCardLink.observe('click',function(event){Personalize.controlOverlay.hide();Personalize.activeStep.enterInfo.show();}.bind(Personalize.activeStep));}
this.mainContentElement.insert(this.removeGiftCardLink);this.removeGiftCardLink.observe('click',function(event){Personalize.controlOverlay.hide();var answer=confirm('Are you sure you want to remove the Gift Card?');if(answer){Personalize.personalization.giftCardSelected=false;Personalize.personalization.giftCardDenomination=null;Personalize.giftCardDenominationAmount=null;Personalize.trigger('changegiftcard');if('giftCardAmount_'+Personalize.product.id){TP.setCookie('giftCardAmount_'+Personalize.product.id,null);}}}.bind(Personalize.activeStep));}
if(this.options.content){this.mainContentElement.update(this.options.content);}
if(this.options.okay){this.okayElement=new Element('div',{'id':'calloutOkay','class':'calloutOkay clickable'}).update('Okay');this.contentElement.insert(this.okayElement);}
this.arrowElement=new Element('div',{'id':'personalizeWarningCalloutArrow','class':'personalizeWarningCalloutArrow',style:'margin-top: 10px;'});this.domElement.insert(this.contentElement);this.domElement.insert(this.arrowElement);this.domElement.hide();$(document.body).insert(this.domElement);this.neverShowAgain=false;if(!this.options.close&&!this.options.okay&&!this.options.giftCard){Personalize.observe('textboxclick',this.foreverHide.bind(this));this.domElement.addClassName('clickable');this.domElement.onclick=function(){this.foreverHide();}.bind(this);this.cookieName='personalizeTextCallout';if(TP.getCookie(this.cookieName)){this.neverShowAgain=true;}
this.options.click=true;}else{if(this.options.close){this.closeElement.observe('click',this.hide.bind(this));}
if(this.options.okay){this.okayElement.observe('click',this.hide.bind(this));}
if(this.options.giftCard){}}
if(this.options.warning){this.titleElement.setStyle({color:'#F26522'});}},foreverHide:function(){this.hide();TP.setCookie(this.cookieName,1,1);this.neverShowAgain=true;},setAnchor:function(anchor){this.anchor=anchor;},setTitle:function(title){this.titleElement.update(title);},setMainContent:function(content){this.mainContentElement.update(content);},position:function(topOffset){if(typeof topOffset==='undefined'){topOffset=0;}
var anchor=this.anchor;var anchorPosition=anchor.viewportOffset();var scroll=document.viewport.getScrollOffsets();anchorPosition.top+=scroll.top;anchorPosition.left+=scroll.left;var top=anchorPosition.top+topOffset-15;if(this.options.bottom){top=anchorPosition.top+anchor.getHeight()-this.domElement.getHeight();}
if(this.options.right){var left=anchorPosition.left+anchor.getWidth();this.arrowElement.addClassName('sprite-icon-trainingRightArrow');this.arrowElement.setStyle({float:'right',right:'-2px'});this.contentElement.setStyle({float:'right'});}else{var left=anchorPosition.left-this.domElement.getWidth();this.arrowElement.addClassName('sprite-icon-trainingArrow');this.arrowElement.setStyle({float:'left',left:'-2px'});this.contentElement.setStyle({float:'left'});}
this.contentElement.setStyle({width:this.options.width+'px'});this.domElement.setStyle({position:'absolute',top:top+'px',left:left+'px',zIndex:this.options.zIndex});if(this.options.fixed){this.domElement.setStyle({position:'fixed'});}},show:function(topOffset){if(this.options.click){if(TP.getCookie(this.cookieName)){return;}}
if(this.anchor){this.position(topOffset);this.shown=true;this.domElement.show();if(this.options.outsideClick){this.closeWarningPopUp=this.stopObserving.bindAsEventListener(this)
$(document).observe('click',this.closeWarningPopUp);}}else{}},hide:function(){this.shown=false;this.domElement.hide();},stopObserving:function(ev){try{var ancestors=ev.element().ancestors();for(var i=0;i<ancestors.length;i++){var ancestor=ancestors[i];if(ancestor==this.domElement){ev.stop();return;}}
$(document).stopObserving('click',this.closeWarningPopUp);this.hide();}catch(e){}}});var TPError=Class.create({initialize:function(error){this.type=error.type;this.id=error.id;this.target=error.target;this.message=error.message;}});var ErrorManager=Class.create({initialize:function(tpError){this.tpErrors=[];},notify:function(tpError,override){if(override){for(var i=0;i<this.tpErrors.length;i++){var error=this.tpErrors[i];if(error.id==tpError.id&&error.type==tpError.type){console.log('here 01');this.tpErrors[i]=tpError;return;}}}
this.tpErrors.push(tpError);},flush:function(){delete this.tpErrors;this.tpErrors=[];},show:function(options){return;if(!this.tpErrors.length){return;}
var message='';if(options){if(options.combined){for(var i=0;i<this.tpErrors.length;i++){var error=this.tpErrors[i];message+=error.message+"\n";}}
if(options.flush){this.flush();}}
if(!Personalize.errorPopUp){Personalize.errorPopUp=new PersonalizePopup('Error','error_');}
this.content=Personalize.errorPopUp.getPopupElement();var contentDiv=new Element('div').update(message);this.content.update(contentDiv);},hide:function(options){Personalize.errorPopUp.hidePopup();alert('hide something');},getMessage:function(errorId){var message='';for(var i=0;i<this.tpErrors.length;i++){var tpError=this.tpErrors[i];if(errorId=tpError.id){message=tpError.messages;}}
return message;}});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,deliveryDate:null,deliveryAddress:null,sample:null,photographerId:null,mongoId:null,giftCardDenomination:null,savedStep:null,emailRequest:{emailAddress:null,emailMessage:null},trimOption:{trimOptionId:null,trimOptionPrice: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;}
if(json.emailRequest){this.emailRequest.emailAddress=json.emailRequest.emailAddress;this.emailRequest.emailMessage=json.emailRequest.emailMessage;}
if(json.trimOption){this.trimOption.trimOptionId=json.trimOption.trimOptionId;this.trimOption.trimOptionPrice=json.trimOption.trimOptionPrice;}
if(json.savedStep){this.savedStep=json.savedStep;}}},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,deliveryDate:self.deliveryDate,deliveryAddress:self.deliveryAddress,sample:self.sample,photographerId:self.photographerId,mongoId:self.mongoId,primaryProxy:self.primaryProxy,accessEmails:self.accessEmails,panels:self.panels,templateCodeValues:self.templateCodeValues,giftCardDenomination:self.giftCardDenomination,emailRequest:self.emailRequest,trimOption:self.trimOption,savedStep:self.savedStep};}};var Panel=function(){this.textboxes={};this.photos={};this.overlays={};this.separators={};this.dropAreas={};this.designAreas={};this.layoutTextboxes={};this.layoutPhotos={};this.layoutOverlays={};this.layoutDesignAreas={};this.dynamicTextboxes={};};Panel.prototype={id:null,personalizationId:null,panelId:null,layoutId:null,layoutX:null,layoutY:null,layoutWidth:null,layoutHeight:null,layoutZ:null,approvalInitial:null,approvalTimestamp:null,imageHash:null,textboxes:{},photos:{},overlays:{},separators:{},designAreas:{},dropAreas:{},doodles:{},layoutTextboxes:{},layoutPhotos:{},layoutOverlays:{},layoutDropAreas:{},dynamicTextboxes:{},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.dropAreas){for(var dropAreaJsonIndex in json.dropAreas){var dropAreaJson=json.dropAreas[dropAreaJsonIndex];var dropArea=new DropArea();dropArea.loadJSON(dropAreaJson);this.dropAreas[dropAreaJsonIndex]=dropArea;}}
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;}}
if(json.layoutDropAreas){for(var layoutDropAreaJsonIndex in json.layoutDropAreas){var layoutDropAreaJson=json.layoutDropAreas[layoutDropAreaJsonIndex];var layoutDropArea=new LayoutDropArea();layoutDropArea.loadJSON(layoutDropAreaJson);this.layoutDropAreas[layoutDropAreaJsonIndex]=layoutDropArea;}}
if(json.dynamicTextboxes){for(var dynamicTextboxJsonIndex in json.dynamicTextboxes){var dynamicTextboxJson=json.dynamicTextboxes[dynamicTextboxJsonIndex];var dynamicTextbox=new Textbox();dynamicTextbox.loadJSON(dynamicTextboxJson);this.dynamicTextboxes[dynamicTextboxJsonIndex]=dynamicTextbox;}}}},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,imageHash:self.imageHash,textboxes:self.textboxes,photos:self.photos,overlays:self.overlays,separators:self.separators,dropAreas:self.dropAreas,designAreas:self.designAreas,layoutTextboxes:self.layoutTextboxes,layoutPhotos:self.layoutPhotos,layoutOverlays:self.layoutOverlays,layoutDropAreas:self.layoutDropAreas,doodles:self.doodles,dynamicTextboxes:self.dynamicTextboxes};},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,editable:null,angle:null,fontId:null,fontColorId:null,fontSize:null,backgroundColorId:null,frameColorId:null,frameWidth:0,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,editable:self.editable,angle:self.angle,fontId:self.fontId,fontColorId:self.fontColorId,fontSize:self.fontSize,backgroundColorId:self.backgroundColorId,frameColorId:self.frameColorId,frameWidth:self.frameWidth};}};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:0,cropY:0,cropWidth:0,cropHeight:0,rotation:0,effectId:null,sampleImageId:null,aspectRatio:1,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);this.aspectRatio=parseFloat(this.aspectRatio);},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,sampleImageId:self.sampleImageId,aspectRatio:self.aspectRatio};}};var Overlay=function(){};Overlay.prototype={id:null,panelId:null,overlayId:null,x:null,y:null,width:null,height:null,z:null,imageId:null,editable:null,switchedOn: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.editable=parseFloat(this.editable);this.switchedOn=parseFloat(this.switchedOn);},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,editable:self.editable,switchedOn:self.switchedOn};}};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,dropAreaId:null,doodleColorId:null,doodleId:null,name:null,displayName:null,imageId:null,x:null,y:null,width:null,height:null,z:null,rotateDegree:0,mirror:0,textOptions:{},loadJSON:function(json){if(json){TP.extendObject(this,json);}
this.name=this.name;this.displayName=this.displayName;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.rotateDegree=parseFloat(this.rotateDegree);this.mirror=parseFloat(this.mirror);this.textOptions=this.textOptions;},toJSON:function(){var self=this;return{id:self.id,panelId:self.panelId,dropAreaId:self.dropAreaId,doodleColorId:self.doodleColorId,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,rotateDegree:self.rotateDegree,mirror:self.mirror,textOptions:self.textOptions};}};var DoodleTextbox=function(){};DoodleTextbox.prototype={id:null,doodleId: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,editable: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,doodleId:self.doodleId,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,editable:self.editable,angle:self.angle,fontId:self.fontId,fontColorId:self.fontColorId,fontSize:self.fontSize};}};var DoodleDesignBox=function(){};DoodleDesignBox.prototype={id:null,doodleId:null,designBoxId:null,styleId:null,x:null,y:null,width:null,height:null,textboxes:{},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,doodleId:self.doodleId,designBoxId:self.designBoxId,styleId:self.styleId,x:self.x,y:self.y,width:self.width,height:self.height,textboxes:self.textboxes};}};var DoodleDesignBoxTextbox=function(){};DoodleDesignBoxTextbox.prototype={id:null,designBoxId: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,editable: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,designBoxId:self.designBoxId,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,editable:self.editable,angle:self.angle,fontId:self.fontId,fontColorId:self.fontColorId,fontSize:self.fontSize};}};var LayoutTextbox=function(){};LayoutTextbox.prototype=new Textbox();var LayoutPhoto=function(){};LayoutPhoto.prototype=new Photo();var LayoutOverlay=function(){};LayoutOverlay.prototype=new Overlay();var Rsvp=function(){};Rsvp.prototype={id:null,personalizationId:null,urlId:null,optIn:null,contactInfo:null,eventId:null,loadJSON:function(json){if(json){TP.extendObject(this,json);}},toJSON:function(){var self=this;return{id:self.id,personalizationId:self.personalizationId,urlId:self.urlId,optIn:self.optIn,contactInfo:self.contactInfo,eventId:self.eventId};}};var DropArea=function(){};DropArea.prototype={id:null,panelId:null,dropAreaId:null,name: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,dropAreaId:self.dropAreaId,x:self.x,y:self.y,width:self.width,height:self.height};}};var LayoutDropArea=function(){};LayoutDropArea.prototype=new DropArea();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){if(Personalize.writeServiceIsMongo()){this.savePersonalizationMongo(title,callback,createNew);}else{this.savePersonalizationMySQL(title,callback,createNew);}},savePersonalizationMongo:function(title,callback,createNew){var attempts=3;var creatingNew=(createNew||!Personalize.personalization.mongoId)?true:false;var personalization=Personalize.personalization;try{personalization.templateCodeValues=this.getP13nStep().getTemplateCodeValues();}catch(e){personalization.templateCodeValues={};}
if(createNew){personalization.name=title;}else{personalization.name=Personalize.getProjectDisplayName();}
if(Personalize.member){if(Personalize.member.id){Personalize.personalization.memberId=Personalize.member.id;Personalize.personalization.primaryProxy.memberId=Personalize.member.id;}}
var rsvp=null;if(Personalize.hasDigitalService()){rsvp=Personalize.personalization.rsvp;}
var url='/personalize/mongo/'+((!creatingNew)?personalization.mongoId:'');this.savePersonalizationAjaxCall(url,creatingNew,personalization,rsvp,callback,attempts);},savePersonalizationMySQL:function(title,callback,createNew){var attempts=3;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;}else{personalization.name=Personalize.getProjectDisplayName();}
if(Personalize.member){if(Personalize.member.id){Personalize.personalization.memberId=Personalize.member.id;Personalize.personalization.primaryProxy.memberId=Personalize.member.id;}}
var rsvp=null;if(Personalize.hasDigitalService()){rsvp=Personalize.personalization.rsvp;}
var url='/personalization/'+((!creatingNew)?personalization.id:'');this.savePersonalizationAjaxCall(url,creatingNew,personalization,rsvp,callback,attempts);},savePersonalizationAjaxCall:function(url,creatingNew,personalization,rsvp,callback,attempts){if(attempts>0){new Ajax.Request(url,{parameters:{personalization:JSON.stringify(personalization),rsvp:JSON.stringify(rsvp)},onSuccess:function(transport){Personalize.trigger("mongosaved");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){this.copySavedPersonalization(p,sp);}
if(sp.mongoId){p.mongoId=sp.mongoId;}else{Personalize.readService=Personalize.SERVICE_MYSQL;Personalize.writeService=Personalize.SERVICE_MYSQL;}
if(Personalize.hasDigitalService()){var urlCookieName=(Personalize.hasSnapshot())?'snapshotUrlId':'rsvpUrlId';TP.deleteCookie(urlCookieName,'/');Personalize.services.saveRsvpEvent(Personalize.personalization.templateCodeValues);}}
if(typeof callback==='function'){callback();}}.bind(this),onFailure:function(){attempts=attempts-1;if(attempts>0){this.savePersonalizationAjaxCall(url,creatingNew,personalization,rsvp,callback,attempts);}}.bind(this),onException:function(transport,exception){}});}},copySavedPersonalization:function(p,sp){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 dropAreaId in pPanel.dropAreas){var pDropArea=pPanel.dropAreas[dropAreaId];var spDropArea=spPanel.dropAreas[dropAreaId];if(spDropArea){pDropArea.id=spDropArea.id;pDropArea.panelId=spDropArea.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;}}
for(var layoutDropAreaId in pPanel.layoutDropAreas){var pLayoutDropArea=pPanel.layoutDropAreas[layoutDropAreaId];var spLayoutDropArea=spPanel.layoutDropAreas[layoutDropAreaId];if(spLayoutDropArea){pLayoutDropArea.id=spLayoutDropArea.id;pLayoutDropArea.panelId=spLayoutDropArea.panelId;}}}}},loadPersonalization:function(personalizationId,options){var requestUrl=(Personalize.isMongoId(personalizationId))?'/personalize/mongo/'+personalizationId:'/personalization/'+personalizationId;new Ajax.Request(requestUrl,{method:'get',onSuccess:function(transport){var savedPersonalization=transport.responseJSON;if(savedPersonalization){if(!Personalize.adminUserId){if(savedPersonalization.primaryProxy.orderId&&savedPersonalization.primaryProxy.orderStatusId!=1&&!Personalize.isRepersonalization()){window.location.href=Personalize.hosts.www+'product/'+Personalize.product.id+'/'+Personalize.product.name+'.html';return;}}
if(savedPersonalization.mongoFailed){savedPersonalization.mongoId=null;Personalize.readService=Personalize.SERVICE_MYSQL;Personalize.writeService=Personalize.SERVICE_MYSQL;}
try{Personalize.personalization.loadJSON(savedPersonalization);}catch(e){}
Personalize.personalization.quantity=Personalize.quantity;if(Personalize.hasDigitalService()){Personalize.rsvp.url=Personalize.personalization.rsvp.url;Personalize.rsvp.optIn=Personalize.personalization.rsvp.optIn;Personalize.rsvp.contactInfo=Personalize.personalization.rsvp.contactInfo;Personalize.rsvp.eventId=Personalize.personalization.rsvp.eventId;}
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){}}}}}}}
var productPanel=Personalize.product.panels[panelId];for(var textboxId in panel.textboxes){var textbox=panel.textboxes[textboxId];var productTextbox=productPanel.textboxes[textboxId];textbox.styleClassId=this.createStyleClass(panel.panelId,productTextbox.fonts,productTextbox.fontColors,productTextbox.fontSizes);}
for(var overlayIndex in productPanel.overlays){var productOverlay=productPanel.overlays[overlayIndex];if(typeof panel.overlays[overlayIndex]=="undefined"){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.switchedOn=0;overlay.imageId=productOverlay.color.imageId;panel.overlays[overlayIndex]=overlay;}
panel.overlays[overlayIndex].editable=productOverlay.editable;}}}
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();for(var colorId in product.colors){if(product.colors[colorId].number==product.productColorNumber){Personalize.product.color=TP.copy(product.colors[colorId]);}}
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];for(var productColorId in productPanel.colors){if(productColorId==product.color.id){productPanel.color=TP.copy(productPanel.colors[productColorId]);}}
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.backgroundColorId=productTextbox.backgroundColorId;textbox.frameColorId=productTextbox.frameColorId;textbox.frameWidth=productTextbox.frameWidth;textbox.editable=productTextbox.editable;textbox.styleClassId=this.createStyleClass(panel.panelId,productTextbox.fonts,productTextbox.fontColors,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[product.color.id]){var fontColor=productTextbox.fontColors[product.color.id][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=(typeof productPhoto.colors[product.color.id]!="undefined")?productPhoto.colors[product.color.id].frameColorId:null;photo.overlayImageId=(typeof productPhoto.colors[product.color.id]!="undefined")?productPhoto.colors[product.color.id].overlayImageId:null;photo.logo=productPhoto.logo;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.editable=productOverlay.editable;overlay.switchedOn=(parseFloat(productPanel.colors[product.color.id].renderWithBorder))?1:0;overlay.imageId=(typeof productOverlay.colors[product.color.id]!="undefined")?productOverlay.colors[product.color.id].imageId:null;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.dropAreas={};for(var dropAreaIndex in productPanel.dropAreas){var productDropArea=productPanel.dropAreas[dropAreaIndex];var dropArea=new DropArea();dropArea.dropAreaId=productDropArea.id;dropArea.x=productDropArea.x;dropArea.y=productDropArea.y;dropArea.width=productDropArea.width;dropArea.height=productDropArea.height;panel.dropAreas[dropAreaIndex]=dropArea;}
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;}
if(Personalize.hasDigitalService()){p13n.rsvp=new Rsvp();p13n.rsvp.urlId=Personalize.rsvp.url.id;p13n.rsvp.optIn=Personalize.rsvp.optIn;p13n.rsvp.contactInfo=Personalize.rsvp.contactInfo;}
p13n.sample=Personalize.sample;p13n.photographerId=Personalize.photographerId;return p13n;},addLayoutOverlay:function(panel,overlayIndex,productOverlay){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.editable=productOverlay.editable;overlay.switchedOn=0;overlay.imageId=productOverlay.imageId;panel.layoutOverlays[overlayIndex]=overlay;},addGiftCardLayoutTextbox: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;textbox.backgroundColorId=layoutTextbox.backgroundColorId;textbox.frameColorId=layoutTextbox.frameColorId;textbox.frameWidth=layoutTextbox.frameWidth;var layouts=(Personalize.product.panels[panel.panelId]).layouts;for(var layoutId in layouts){if(layouts[layoutId].layout.layoutTypeId=='3'){var productLayoutTextbox=layouts[layoutId].textboxes[textbox.textboxId];for(var styleId in layouts[layoutId].style){var style=layouts[layoutId].style[styleId];tempArray=new Array();tempArray=productLayoutTextbox.name.split('_');var styleName=layouts[layoutId].layout.name+'_'+tempArray.pop();if(style.name.strip()==styleName.strip()){for(var font in style.font)
{if(style.font[font]['default']==1){textbox.fontId=style.font[font].fontId;}}
for(var fontColor in style.fontColors)
{if(style.fontColors[fontColor]['default']==1){textbox.fontColorId=style.fontColors[fontColor].fontColorId;}}
for(var fontSize in style.fontSizes)
{if(style.fontSizes[fontSize]['default']==1){textbox.fontSize=style.fontSizes[fontSize].fontSize;}}}}}}
if(typeof panel.layoutTextboxes==='undefined')panel.layoutTextboxes=new Object();panel.layoutTextboxes[textbox.textboxId]=textbox;},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;textbox.backgroundColorId=layoutTextbox.backgroundColorId;textbox.frameColorId=layoutTextbox.frameColorId;textbox.frameWidth=layoutTextbox.frameWidth;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;}
if(typeof layoutTextbox.fontColors!="undefined"){var productColorId=Personalize.personalization.productColorId;var firstFontColorId=null;for(var i in layoutTextbox.fontColors[productColorId]){var fontColor=layoutTextbox.fontColors[productColorId][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;},addDynamicTextbox:function(){var textbox=new Textbox();textbox.z=600;textbox.width=360;textbox.height=40;textbox.fontId=23;textbox.fontColorId=12;textbox.fontSize=10;textbox.horizontalAlignmentId=2;textbox.verticalAlignmentId=3;textbox.defaultCasingId=2;textbox.typeId=7;return textbox;},addDynamicPhotographerTextbox:function(){var textbox=new Textbox();textbox.z=600;textbox.width=40;textbox.height=360;textbox.fontId=23;textbox.fontColorId=12;textbox.fontSize=10;textbox.horizontalAlignmentId=2;textbox.verticalAlignmentId=3;textbox.defaultCasingId=2;textbox.angle=90;textbox.typeId=8;return textbox;},getTextboxUrl:function(textbox){var textboxImageUrl=Personalize.hosts.text+'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 formatter=new PersonalizeFormatter();var responses=formatter.formatText(formatRequests);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{if((Personalize.hasRsvp())&&templateVariableMatch[1]=='RSVPPHONE'){variableCodeResponses[templateVariableCode][templateVariableFormat]=this.getRsvpText(variableCodeResponses[templateVariableCode][templateVariableFormat]);}
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];if(typeof textbox.content==='undefined'){continue;}
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();}},asIsPersonalize:function(callback){var templateVariablesRegex=/_([^_]+)_(?:\{([^}]+)\})?/g;var templateVariableRegex=/_([^_]+)_(?:\{([^}]+)\})?/;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 textboxContent=textbox.content;var templateVariableMatches=textboxContent.match(templateVariablesRegex);if(templateVariableMatches){for(var i=0;i<templateVariableMatches.length;i++){var match=templateVariableMatches[i];textbox.content=textbox.content.replace(match,"");}}}
for(var layoutTextboxIndex in panel.layoutTextboxes){try{var textbox=panel.textboxes[textboxIndex];var textboxContent=textbox.content;var templateVariableMatches=textboxContent.match(templateVariablesRegex);if(templateVariableMatches){for(var i=0;i<templateVariableMatches.length;i++){var match=templateVariableMatches[i];textbox.content=textbox.content.replace(match,"");}}}catch(e){}}}
if(TP.getCookie('giftCardAmount_'+Personalize.product.id)){var giftCardDenominationCookie=TP.getCookie('giftCardAmount_'+Personalize.product.id).evalJSON();if(giftCardDenominationCookie){Personalize.personalization.giftCardSelected=true;Personalize.personalization.giftCardDenomination=giftCardDenominationCookie;Personalize.giftCardDenominationAmount=((Personalize.giftCardDenominations[Personalize.personalization.giftCardDenomination].amount).split('.'))[0];for(var panelId in Personalize.product.panels){var productPanel=Personalize.product.panels[panelId];if(productPanel.number!=2){continue;}
for(var layoutId in productPanel.layouts){var layout=productPanel.layouts[layoutId];if(parseFloat(layout.layout.layoutTypeId)==3){var personalizationPanel=Personalize.personalization.panels[productPanel.id];for(var layoutTextboxId in layout.textboxes){var layoutTextbox=layout.textboxes[layoutTextboxId];if(layoutTextbox.name==Personalize.giftCardDenominationTextboxName){layoutTextbox.content=Personalize.giftCardDenominationAmount;}
this.addGiftCardLayoutTextbox(personalizationPanel,layoutTextbox,true);}
for(var layoutOverlayId in layout.overlays){var layoutOverlay=layout.overlays[layoutOverlayId];this.addLayoutOverlay(personalizationPanel,layoutOverlayId,layoutOverlay);}
break;}}}}}},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.sessionId=Personalize.sessionId;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*photo.aspectRatio,cropY:photo.cropY*photo.aspectRatio,cropWidth:photo.cropWidth*photo.aspectRatio,cropHeight:photo.cropHeight*photo.aspectRatio,rotation:photo.rotation,effectId:photo.effectId,zoom:photo.zoom};}}
sessionPersonalization.panels[panelId]=sessionPanel;}}
var sessionPersonalizations=[];var cookieSessionPersonalizations=Personalize.getLocalVariable('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 maxCookieSize=(Personalize.isSample())?4096:2048;var sessionPersonalizationsJsonString=encodeURIComponent(JSON.stringify(sessionPersonalizations));if(!Personalize.hasLocalStorage()){while(sessionPersonalizationsJsonString.length>maxCookieSize){sessionPersonalizations.shift();sessionPersonalizationsJsonString=encodeURIComponent(JSON.stringify(sessionPersonalizations));}}
Personalize.setLocalVariable('sessionPersonalizations',sessionPersonalizationsJsonString);},loadSessionPersonalization:function(){if(Personalize.isResetCookie())return;var sessionPersonalizations=Personalize.getLocalVariable('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'&&parsedSessionPersonalization.sessionId==TP.getCookie('PHPSESSID')){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;},getRsvpText:function(rsvpPhoneText){var rsvpText=rsvpPhoneText;var rsvpPhoneChecked=$('rsvp_phone_check').checked;if(Personalize.isDigitalServiceOn()){rsvpText=Personalize.hosts.rsvp+Personalize.rsvp.url.url;if(rsvpPhoneChecked){rsvpText+=' or '+rsvpPhoneText;Personalize.personalization.rsvp.contactInfo=rsvpPhoneText;}}else{rsvpText=(rsvpPhoneChecked)?rsvpPhoneText:'';Personalize.personalization.rsvp.contactInfo=rsvpText;}
return rsvpText;},saveRsvpEvent:function(templateCodeValues){var rsvpEvent={};var city='';var state='';for(var templateCode in templateCodeValues){var eventName=this.getRsvpVarEventName(templateCode);if(eventName!=''){switch(parseFloat(templateCodeValues[templateCode].type)){case Personalize.VARIABLE_TYPE_TEXT:case Personalize.VARIABLE_TYPE_TEXTBOX:rsvpEvent[eventName]=templateCodeValues[templateCode].text;break;case Personalize.VARIABLE_TYPE_NAME:rsvpEvent[eventName]=templateCodeValues[templateCode].name;break;case Personalize.VARIABLE_TYPE_DATE:rsvpEvent[eventName]=(templateCodeValues[templateCode].year||'0000')+'-'+(templateCodeValues[templateCode].month||'00')+'-'+(templateCodeValues[templateCode].date||'00');rsvpEvent[eventName]=(rsvpEvent[eventName].indexOf('00-00')>0)?'0000-00-00':rsvpEvent[eventName];break;}}else if(templateCode=='_HOST_'){var host=templateCodeValues[templateCode].name.split(' ');rsvpEvent.hostFirstName=host[0];rsvpEvent.hostLastName='';for(var i=1;i<host.length;i++){rsvpEvent.hostLastName+=host[i]+' ';}}else if(templateCode=='_TIME_'||templateCode=='_STARTTIME_'){var eventTime=(templateCodeValues[templateCode].hour||'00')+':'+(templateCodeValues[templateCode].minute||'00')+':'+(templateCodeValues[templateCode].second||'00');}else if(templateCode=='_ENDTIME_'){var eventEndTime=(templateCodeValues[templateCode].hour||'00')+':'+(templateCodeValues[templateCode].minute||'00')+':'+(templateCodeValues[templateCode].second||'00');}else if(templateCode=='_CITY_'){city=templateCodeValues[templateCode].text;}else if(templateCode=='_STATE_'){state=templateCodeValues[templateCode].text;}}
if(typeof rsvpEvent['eventDate']!="undefined"){var eventDate=rsvpEvent['eventDate'];}
if(typeof eventTime!="undefined"){rsvpEvent['eventDate']=(eventDate||'')+' '+eventTime;}
if(typeof eventEndTime!="undefined"){rsvpEvent['eventDateEnd']=(eventDate||'')+' '+eventEndTime;}
if(rsvpEvent['address']!="undefined"&&city!=''){rsvpEvent['address']+='\n'+city+', '+state;}
if(Personalize.member){if(Personalize.member.id){rsvpEvent.memberId=Personalize.member.id;}}
if(Personalize.personalization.id){rsvpEvent.personalizationId=Personalize.personalization.id;}
rsvpEvent.storeId=Personalize.storeId;rsvpEvent.rsvpUrlId=Personalize.rsvp.url.id;rsvpEvent.digitalServiceTypeId=Personalize.rsvp.digitalServiceId;var action='create';if(typeof Personalize.rsvp.eventId!=='undefined'&&Personalize.rsvp.eventId){action='update';rsvpEvent.id=Personalize.rsvp.eventId;}
new Ajax.Request('/personalize/rsvp/',{parameters:{action:action,rsvpEvent:JSON.stringify(rsvpEvent)},onSuccess:function(transport){var rsvpEventIdWasNull=(Personalize.personalization.rsvp.eventId==null)?true:false;var response=transport.responseJSON;if(typeof response.eventId!=='undefined'){Personalize.rsvp.eventId=response.eventId;Personalize.personalization.rsvp.eventId=response.eventId}else if(typeof response.id!=='undefined'){Personalize.rsvp.eventId=response.id;Personalize.personalization.rsvp.eventId=response.id;}
if(rsvpEventIdWasNull&&Personalize.personalization.rsvp.eventId!=null){Personalize.services.savePersonalization();}},onFailure:function(){}});},getRsvpVarEventName:function(variableCode){for(var i in Personalize.templateVariables){if(Personalize.templateVariables[i].code==variableCode){return Personalize.templateVariables[i].eventName;}}
return'';},loadMember:function(options){new Ajax.Request('/personalize/member/',{method:'get',onSuccess:function(transport){var response=transport.responseJSON;if(typeof response.id!=='undefined'){Personalize.member=response;}
if(typeof options.onComplete==='function'){options.onComplete();}},onFailure:function(){}});}};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));}
$('wpdHostingHelp').observe('click',this.popupHelp.bindAsEventListener(this));this.sampleImageContainer.observe('click',this.popupBalloon.bindAsEventListener(this));},activate:function(){$(this.element.id).show();this.disableNextButtons();$('saveButton').hide();Personalize.trackPageview('/personalize/SelectVerse');},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].sampleImages[Personalize.product.color.id]:Personalize.product.templates.groups[this.chosenGroup].templates[this.selectedTemplate].layouts[id].sampleImages[Personalize.product.color.id];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;},isTemplateLayoutOnFirstPanel:function(){var firstPanelId=this.findFirstTemplateLayoutPanel();return(firstPanelId)?Personalize.isFrontPanel(Personalize.product.panels[firstPanelId]):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').insert(new Element('div',{style:'float: left;margin-right: 5px;'}).update(layout.layout.displayName));var helpIcon=new Element('div',{'class':'sprite-icon-help',id:'help_'+layout.layout.displayName,'style':'display: inline-block;'});title.insert(helpIcon);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(helpIcon,'click',this.popupHelp.bindAsEventListener(this,layout.layout.displayName));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;this.enableNextButtons();}.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;var defaultTemplateGroupSet=false
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));if(!defaultTemplateGroupSet&&(group['default']==1)){defaultTemplateGroupSet=true;this.setDefaultTemplateGroup(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));},setDefaultTemplateGroup:function(defaultRadio){this.chosenGroup=this.selectedGroup;this.selectedGroup=defaultRadio.value;var templateContainer=this.groupTemplateContainers[this.selectedGroup];this.setGroupSelectionIndicator();templateContainer.show();this.openContainer=templateContainer;},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();}},popupHelp:function(ev,helpType){var helpTitle='';var helpText='';if(helpType=='Formal'){helpTitle=helpType+' Invitational Style'
helpText=Personalize.strings.WPD_FORMAL_HELP;}else if(helpType=='Casual'){helpTitle=helpType+' Invitational Style'
helpText=Personalize.strings.WPD_CASUAL_HELP;}else{helpTitle='Hosting'
helpText=Personalize.strings.WPD_HOSTING_HELP;}
var helpDlg=new PersonalizePopup(helpTitle,'helpPopup_');var content=helpDlg.getPopupElement();var text=new Element('div',{align:'left'}).update(helpText);content.insert(text);content.setStyle({padding:'20px',fontFamily:'Helvetica',fontSize:'12px',width:'400px'});helpDlg.showPopup();Event.stop(ev);},popupBalloon:function(ev){if(!this.balloon){this.balloonContent=new Element('div',{style:'text-align: left;font-size: 12px;'});this.balloonClose=new Element('div',{'class':'sprite-btn-close clickable','style':'float:right; margin-left:6px;'});this.balloonCloseHandler=this.hidePopupBalloon.bindAsEventListener(this);this.balloonClose.observe('click',this.balloonCloseHandler);this.balloonContent.insert(this.balloonClose);this.balloonContent.insert('<p><b style="font-size:15px">You\'ll be able to edit your card later in the process.</b></p><p>First, select your hosting scenario and style on the right so we can help you choose the appropriate wording.</p><p>Then you can enter your information and edit the card as needed.</p>');this.balloon=new TPBalloon({width:300,height:130,fadeTime:0.5,contentClass:'toolTipContent',anchor:'templateSelectBox',content:this.balloonContent,stemPosition:'rightMiddle',imageBase:Personalize.hosts['static']+'/image/balloon/'});}
this.balloon.show();$('rightColumn').observe('click',this.balloonCloseHandler);},hidePopupBalloon:function(ev){$('rightColumn').stopObserving('click',this.balloonCloseHandler);this.balloon.hide();},disableNextButtons:function(){if(this.selectedVerse){return;}
var nextButtons=$$('div.sprite-btn-next');nextButtons.each(function(button){button.removeClassName('sprite-btn-next');button.addClassName('sprite-btn-next-disabled');});},enableNextButtons:function(){var nextButtons=$$('div.sprite-btn-next-disabled');nextButtons.each(function(button){button.removeClassName('sprite-btn-next-disabled');button.addClassName('sprite-btn-next');});}});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:{},tabOrder:1100,init:function(){this.name='personalizeEnterInfo';this.description='Enter the details you would like included on your invitations. You can go back to change hosts or style anytime.';this.available=true;this.avatarWizardId=this.element.id+"_avatarWizardContainer";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.description='Enter the details you would like included on your invitations.';}
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.isTemplateLayoutOnFirstPanel()){$(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();if(!this.templateVariables){$('wpdBoxHeader').hide();$(this.enterInfoElementId).hide();$('enterInfoBox').setStyle({borderWidth:'0px'});}else{$('wpdBoxHeader').show();$(this.enterInfoElementId).show();$('enterInfoBox').setStyle({borderWidth:'1px 2px 2px 1px'});}
Personalize.trackPageview('/personalize/EnterInfo');},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));Personalize.setLocalVariable('templateCodeValues',cookieValue,1536);},loadCookieTemplateCodeValues:function(){var cookieTemplateCodeValues=Personalize.getLocalVariable('templateCodeValues');if(cookieTemplateCodeValues){try{var parsedCookie=JSON.parse(decodeURIComponent(cookieTemplateCodeValues));}catch(e){}
if(parsedCookie){this.templateCodeValues=parsedCookie;}}},loadPersonalizationTemplateCodeValues:function(){if(Personalize.personalization.id){this.templateCodeValues=Personalize.personalization.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);},isTemplateLayoutOnFirstPanel:function(){if(!this.verseStep)return false;return this.verseStep.isTemplateLayoutOnFirstPanel();},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){$('enterInfo_avatarWizardHeading').update('Thanks! Now let\'s<br /> fill in the details!');var avatarWizard=$('enterInfo_avatarWizard');avatarWizard.update('');avatarWizard.insert('<p>On the previous page, you chose:</p>');avatarWizard.insert('<div>'+Personalize.product.templates.groups[this.selectedGroupId].name+'</div>');avatarWizard.insert('<div>'+Personalize.product.templates.groups[this.selectedGroupId].templates[this.selectedTemplateId].layouts[this.verseStep.getSelectedVerse()].displayName+' wording</div>');$('enterInfo_avatarImageContainer').removeClassName('sprite-avatar-step4');$('enterInfo_avatarImageContainer').addClassName('sprite-avatar-step2');}else if(Personalize.product.templateId){$(this.avatarWizardId).hide();}},renderWizard:function(){var wizard=this.getWizard();if(!wizard){return;}
var container=$(this.wizardStepTabsDomId);container.update(new Element('div',{'class':'instruction',style:'position: relative;'}).insert('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.'));var usedVariables=[];for(var stepId in wizard.steps){var step=wizard.steps[stepId];this.renderWizardStep(step,container,usedVariables);}
if(Personalize.isSample()){this.templateIterator(this.renderWizardStep.bind(this),[container,usedVariables]);}},renderWizardStep:function(step,container,usedVariables){var newTab=new Element('div',{id:"wizardStep_"+step.id,style:'clear: both;'});container.insert(newTab);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;if(typeof usedVariables[currentVariable.id]==='undefined'){usedVariables[currentVariable.id]=currentVariableCode;}else{continue;}
var tabOrder=this.tabOrder++;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('*'));}
var inputContainer=new Element('div',{'class':'enterInfofield',style:'clear:both;'});if(currentVariable.help&&(currentVariable.code.indexOf('ENTREE')==-1)){var helpIcon=new Element('div',{'class':'sprite-icon-help clickable enterInfoHelpIcon'});inputContainer.insert(helpIcon);helpIcon.observe('click',this.popupHelp.bindAsEventListener(this,currentVariable.help,currentVariable.name));}
if(currentVariable.help&&(currentVariable.code.indexOf('ENTREE')>0)){inputContainer.insert(new Element('div',{'class':'enterInfoHelp'}).update(currentVariable.help));}
var textInput;if(currentVariableCode==Personalize.VARIABLE_CODE_STATE){var stateDropDown=new Element('select',{tabindex:tabOrder++,id:namespace+'_stateAbbr',name:namespace+'_stateAbbr',style:'width: 175px'});stateDropDown.observe('change',function(){var ids=(this.id).split('_');updateFullStateName('wizardStepVariable_'+ids[1]);}.bind(stateDropDown));inputContainer.insert(stateDropDown);stateDropDown.insert(new Element('option',{value:''}).update('Select one...'));stateDropDown.insert(new Element('option',{value:'Others'}).update('Others / province'));var usStates=Personalize.stateList['US States'];for(var key in usStates){stateDropDown.insert(new Element('option',{value:usStates[key]}).update(key+' - '+usStates[key]));}
textInput=new Element('input',{tabindex:tabOrder++,id:namespace,name:namespace,onkeyup:"enterKeyNext(event)",style:'display : none; width: 140px;'});}else{textInput=new Element('input',{tabindex:tabOrder++,id:namespace,name:namespace,'class':'textInput',onkeyup:"enterKeyNext(event)"})}
inputContainer.insert(textInput);if(currentVariable.code==Personalize.VARIABLE_CODE_ADDRESS||currentVariable.code==Personalize.VARIABLE_CODE_ADDRESS_LINE1||currentVariable.code==Personalize.VARIABLE_CODE_ADDRESS_LINE2){textInput.observe('change',function(){for(var addressAbbreviation in Personalize.addressAbbreviations){addrAbbr=Personalize.addressAbbreviations[addressAbbreviation];tempPattern=new RegExp('[.]','ig');var tempAbbr=addrAbbr['abbreviation'].replace(tempPattern,'[.]');var pattern=new RegExp(' '+tempAbbr+' ','ig');var tempString=this.value.replace(pattern,' '+addrAbbr['fullName']+' ');pattern=new RegExp(' '+tempAbbr+'$','ig');tempString=tempString.replace(pattern,' '+addrAbbr['fullName']);pattern=new RegExp('^'+tempAbbr+'$','ig');tempString=tempString.replace(pattern,addrAbbr['fullName']);pattern=new RegExp('^'+tempAbbr+' ','ig');this.value=tempString.replace(pattern,addrAbbr['fullName']+' ');}}.bind(textInput));}
newTab.insert(inputContainer);}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('*'));}
var inputContainer=new Element('div',{'class':'enterInfofield',style:'clear:both; margin-left:10px'});if(currentVariable.help){var helpIcon=new Element('div',{'class':'sprite-icon-help clickable enterInfoHelpIcon'});inputContainer.insert(helpIcon);helpIcon.observe('click',this.popupHelp.bindAsEventListener(this,currentVariable.help,currentVariable.name));}
inputContainer.insert(new Element('textarea',{tabindex:tabOrder++,id:namespace,name:namespace,rows:8,cols:35}));newTab.insert(inputContainer);}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'});if(currentVariable.help){var helpIcon=new Element('div',{'class':'sprite-icon-help clickable enterInfoHelpIcon'});enterInfofield.insert(helpIcon);helpIcon.observe('click',this.popupHelp.bindAsEventListener(this,currentVariable.help,currentVariable.name));}
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)});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'});if(currentVariable.help){var helpIcon=new Element('div',{'class':'sprite-icon-help clickable enterInfoHelpIcon'});enterInfofield.insert(helpIcon);helpIcon.observe('click',this.popupHelp.bindAsEventListener(this,currentVariable.help,currentVariable.name));}
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'));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];this.updateFormWithTemplateCodeValuesFromStep(step);}
if(Personalize.isSample()){this.templateIterator(this.updateFormWithTemplateCodeValuesFromStep.bind(this));}},updateFormWithTemplateCodeValuesFromStep:function(step){if(!step)return;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;if(code==Personalize.VARIABLE_CODE_STATE){var stateAbbr=document.getElementById(variableDomPrefix+'_stateAbbr');if(stateAbbr){var checkIfOthersSelected=true;$$('select#'+variableDomPrefix+'_stateAbbr option').each(function(o){if(o.value==textField.value){o.selected=true;checkIfOthersSelected=false;if(textField.getStyle('display')!='none'){textField.setStyle({display:'none'});}
$break;}});if(checkIfOthersSelected==true){stateAbbr.selectedIndex='1';if(textField.getStyle('display')=='none'){textField.setStyle({display:'inline'});}}}}}
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];this.loadTemplateCodeValuesFromFormStep(step);}
if(Personalize.isSample()){this.templateIterator(this.loadTemplateCodeValuesFromFormStep.bind(this));}},loadTemplateCodeValuesFromFormStep:function(step){if(!step)return;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;}}}},templateIterator:function(handler,args){if(typeof Personalize.product.templates!=='undefined'&&typeof Personalize.product.templates.groups!=='undefined'){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];var wizard=template.wizard;for(var stepId in wizard.steps){var step=wizard.steps[stepId];var argumentList=[];argumentList.push(step);if(args){for(var i=0;i<args.length;i++){argumentList.push(args[i]);}}
handler.apply(handler,argumentList);}}}}},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();},popupHelp:function(ev,text,title){var helpTitle='Help';var helpDlg=new PersonalizePopup(helpTitle,'helpPopup_');var content=helpDlg.getPopupElement();var text=new Element('div',{align:'left'}).update(text);content.insert(text);content.setStyle({padding:'20px',fontFamily:'Helvetica',fontSize:'12px',width:'400px'});helpDlg.showPopup();Event.stop(ev);}});var personalizePersonalize=new Step('personalizeStep','Personalize');TP.extendObject(personalizePersonalize,{init:function(loadedPhotos){this.styleEditors=[];this.name='Personalize';this.description='Click any text to change it. <br />A professional designer will adjust layout, sizing and spacing, then send you a proof before any printing begins.';this.textboxEditors=[];this.photos=[];this.overlays=[];this.textboxes=[];this.separators=[];this.dropAreas=[];this.layoutTextboxes=[];this.layoutPhotos=[];this.layoutOverlays=[];this.layoutSavedData={textboxes:[],photos:[],overlays:[]};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.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.colorSwitcher.beforeSwitchCallback=this.beforeChangeColorCheck.bind(this);this.layoutTray=new personalizeLayoutTray();this.borderTray=new PersonalizeBorderTray();if(!Personalize.isSample()){this.photoTray=new PersonalizePhotoTray();if(!loadedPhotos){this.photoTray.requestPhotos();}else{this.photoTray.loaded=true;this.photoTray.photos=loadedPhotos;}}else{this.photoTray=new SamplePhotoTray();this.photoTray.loaded=true;this.photoTray.photos=Personalize.adminPhotos;}
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;Personalize.observe('changelayout',this.layoutChange.bind(this));this.tabController=null;this.dropAreasVisible=false;this.lastPanelDoodleId=0;this.optimalResolution=null;this.resolution=null;this.maxOptimalWidth=550;this.maxOptimalHeight=500;},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'}));Personalize.personalization.savedStep=this.element.id;if(!Personalize.member){this.login(true,name,createNew);return;}else{Personalize.services.savePersonalization(name,this.saveComplete.bind(this),createNew);}},cancelSave:function(){if(this.saveDialog)
this.saveDialog.hidePopup();},login:function(showSave,title,createNew){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;},createNew);},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='Text Box '+(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){}}}
if($('textboxHelp')){$('textboxHelp').observe('click',this.popupHelp.bindAsEventListener(this,'textbox'));}
this.renderMonogramTray();},renderMonogramTray:function(){if(!this.hasMonogram()){return;}
var trayDomId='personalizeStep_monogramTray';var monogramTrayContainer=new Element('div',{id:'monogramTrayContainer'});var monogramTray=new Element('div',{id:trayDomId});var titleContainer=new Element('div',{'class':'personalizeMonogramEditorHeader'});var titleDisplayText=new Element('div',{style:'width:50%; float:left; margin-left: 5px; width: 310px;','class':'personalizeTextEditorHeaderTitle clickable'});var titleCollapseBtn=new Element('div',{id:trayDomId+'_collapse','class':'clickable sprite-btn-minus',style:'float: left;'});var titleHelpBtn=new Element('div',{'class':'clickable sprite-btn-help',style:'float: left;'});titleCollapseBtn.observe('click',this.collapseMonogramTray.bind(this,trayDomId));titleDisplayText.observe('click',this.collapseMonogramTray.bind(this,trayDomId));titleHelpBtn.observe('click',this.showMonogramHelp.bind(this));titleContainer.insert(titleCollapseBtn);titleContainer.insert(titleDisplayText.update('Design Options'));titleContainer.insert(titleHelpBtn);monogramTrayContainer.insert(titleContainer);monogramTrayContainer.insert(monogramTray);$(this.styleEditorElementId).insert(monogramTrayContainer);},showMonogramHelp:function(){if(!this.monogramHelpDlg){this.monogramHelpDlg=new PersonalizePopup('Motif Help','monogramHelp');}
this.ccDlgElem=this.monogramHelpDlg.getPopupElement();var textElem=new Element('div',{style:'margin:16px;width:340px;font-family:helvetica; font-size:12px; ',align:'left'}).update('You can add stylish design motifs to your cards and invitations. If the motif you choose is a monogram, you can edit the monogram information by clicking on the motif itself. To add borders to a design, simply click the corresponding check box.');var buttonElem=new Element('div',{align:'right',style:'margin:8px;'}).update(new Element('div',{'class':'sprite-btn_close clickable'}));buttonElem.observe('click',this.monogramHelpDlg.hidePopup.bind(this.monogramHelpDlg));this.ccDlgElem.update(textElem);this.ccDlgElem.insert(buttonElem);this.ccDlgElem.setStyle({width:'356px'});this.monogramHelpDlg.showPopup();},collapseMonogramTray:function(trayDomId){var trayDom=$(trayDomId);var trayDomCollapseBtn=$(trayDomId+'_collapse');if(trayDom&&trayDomCollapseBtn){if(trayDom.visible()){trayDom.hide();trayDomCollapseBtn.removeClassName('sprite-btn-minus');trayDomCollapseBtn.addClassName('sprite-btn-plus');}else{trayDom.show();trayDomCollapseBtn.addClassName('sprite-btn-minus');trayDomCollapseBtn.removeClassName('sprite-btn-plus');}}},getPreviewImageInfo:function(){var productPanel=Personalize.product.panels[this.currentPanel.panelId];if(parseFloat(productPanel.backPanel)==1){var previewImageInfo=productPanel.backPanelImages.paperTypes[Personalize.product.paperId];previewImageInfo.height=parseFloat(previewImageInfo.height);previewImageInfo.width=parseFloat(previewImageInfo.width);}else{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.calcResolution();if(setByHeight){var sizeString='/height/'+newHeight;var shadowSizeString='/height/'+(parseFloat(newHeight)+11);}else{var sizeString='/width/'+newWidth;var shadowSizeString='/width/'+(parseFloat(newWidth)+11);}
var personalizeShadowUrl='';if(parseFloat(productPanel.backPanel)==1){var sizeConstrained=(parseFloat(newHeight)+11);if(newWidth>newHeight){sizeConstrained=(parseFloat(newWidth)+11);}
var personalizeImageUrl=Personalize.hosts.images+'product/'+Personalize.product.id+'/panel/'+productPanel.number+'/paper/'+Personalize.product.paperId+'/type/personalize/shadow/0/width/'+sizeConstrained+'/height/'+sizeConstrained+'.jpg';}else{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;},calcResolution:function(){var productPanel=Personalize.product.panels[this.currentPanel.panelId];var imageWidth=0;var imageHeight=0;if(parseFloat(productPanel.backPanel)==1){var image=productPanel.backPanelImages.paperTypes[Personalize.product.paperId];image.height=parseFloat(image.height);image.width=parseFloat(image.width);imageWidth=image.width+parseFloat(0.250*image.resolution);imageHeight=image.height+parseFloat(0.250*image.resolution);}else{var image=productPanel.color.personalizeImage;imageWidth=image.width;imageHeight=image.height;}
var aspectRatio=imageWidth/imageHeight;var possibleAspect=this.maxOptimalWidth/this.maxOptimalHeight;if(aspectRatio<possibleAspect){this.optimalResolution=image.resolution*(this.maxOptimalHeight/imageHeight);if(this.maxOptimalHeight>imageHeight){this.optimalResolution=image.resolution;}}else{this.optimalResolution=image.resolution*(this.maxOptimalWidth/imageWidth);if(this.maxOptimalWidth>imageWidth){this.optimalResolution=image.resolution;}}
this.resolution=this.optimalResolution;},changePreviewImage:function(){var imageInfo=this.getPreviewImageInfo();var tmpImg=new Image();tmpImg.onload=this.previewImageLoaded.bindAsEventListener(this,imageInfo.personalizeImageUrl,tmpImg);tmpImg.src=imageInfo.personalizeImageUrl;},changeDoodleTrayColors:function(){this.renderDoodleTray();if(!$('personalizeStep_monogramTray')){for(var panelId in Personalize.personalization.panels){for(var doodle in Personalize.personalization.panels[panelId].doodles){if(Personalize.personalization.panels[panelId].doodles[doodle].type==2){var dropArea=Personalize.personalization.panels[panelId].doodles[doodle].dropArea;var productPanel=Personalize.product.panels[panelId];var doodleFound=false;for(var availableDoodleId in productPanel.availableDoodles){var associatedDoodle=productPanel.availableDoodles[availableDoodleId];var doodleId=associatedDoodle.doodleColorImage.doodleId;var productDoodle=Personalize.product.doodles[doodleId];if(productDoodle.type==0){continue;}
if(associatedDoodle.productPanelColorId==Personalize.product.color.id){var trayDoodle=TP.extendObject(new TrayDoodle(associatedDoodle),new TrayMonogram());personalizePersonalize.doodleTray.imageSpace.addItem(trayDoodle);if(doodleId==Personalize.personalization.panels[panelId].doodles[doodle].doodleId){delete Personalize.personalization.panels[panelId].doodles[doodle];dropArea.removeDoodle();dropArea.addDoodle(trayDoodle,0,0,true);doodleFound=true;break;}}}
if(!doodleFound){delete Personalize.personalization.panels[panelId].doodles[doodle];}
break;}}}}
for(var i=0;i<this.dropAreas.length;i++){var dropArea=this.dropAreas[i];dropArea.changeColor();}
if(!this.dropAreas.length&&this.globalDropArea){this.globalDropArea.changeColor();}},renderTabController:function(){var doodleAvailable=this.hasDoodles();var photoAvailable=this.hasPhotos();this.tabController=new PersonalizeTabController('personalizeStepBottomTrayTabControllers',{cssPrefix:'personalizeBottomTabController'});this.bottomTabsHelp='';if(doodleAvailable){var doodleTab=new PersonalizeBottomTab('doodleTab','Design Accents',{className:'bottomTab activeTab',active:false});doodleTab.contentElementDomId='personalizeStep_doodleTray';this.tabController.addTab(doodleTab);this.bottomTabsHelp='doodle';}
if(photoAvailable){var photoTab=new PersonalizeBottomTab('photoTab','Photos',{className:'bottomTab',active:true});photoTab.contentElementDomId='personalizeStep_photoTray';this.tabController.addTab(photoTab);this.bottomTabsHelp='photo';}
this.tabController.render();if(doodleAvailable||photoAvailable){$('personalizeStepBottomTrayTabControllers').insert('<div class="sprite-icon-help clickable" id="bottomTabsHelp" style="float:right;margin-top:10px;"></div>');$('bottomTabsHelp').observe('click',this.popupHelp.bindAsEventListener(this,this.bottomTabsHelp));}
if($('doodleTab')){$('doodleTab').observe('click',function(){this.bottomTabsHelp='doodle';}.bind(this));}
if($('photoTab')){$('photoTab').observe('click',function(){this.bottomTabsHelp='photo';}.bind(this));}},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||Personalize.product.isMagnet||Personalize.isCircularCard()||parseFloat(productPanel.noShadow)==1)){if(imageInfo.personalizeShadowUrl){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.layoutTextboxes.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);}
var hasBorder=false;for(var overlayId in this.currentPanel.overlays){var overlay=this.currentPanel.overlays[overlayId];var panelOverlay=new PersonalizeOverlay(overlay,this.resolution);if(overlay.editable=='1'){hasBorder=true;this.borderTray.render(panelOverlay);if(overlay.switchedOn==1){panelOverlay.render(previewPane);}}else{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);}
this.dropAreas=[];for(var dropAreaId in this.currentPanel.dropAreas){var dropArea=this.currentPanel.dropAreas[dropAreaId];var panelDropArea=new PersonalizeDropArea(dropArea,this.resolution);panelDropArea.render(previewPane);this.dropAreas.push(panelDropArea);}
this.globalDropArea=null;if(!this.dropAreas.length){this.globalDropArea=TP.extendObject(new PersonalizeDropArea(null,this.resolution),new PersonalizeGlobalDropArea());this.globalDropArea.render(previewPane);}
if(this.currentPanel.panelLayoutId){for(var panelLayoutPhotoId in this.currentPanel.layoutPhotos){var layoutPhoto=this.currentPanel.layoutPhotos[panelLayoutPhotoId];var productLayoutPhoto=productPanel.layouts[this.currentPanel.panelLayoutId].photos[panelLayoutPhotoId];var personalizationLayoutPhoto=new PersonalizePhoto(layoutPhoto,productLayoutPhoto,this.resolution);personalizationLayoutPhoto.render(previewPane);this.layoutPhotos.push(personalizationLayoutPhoto);}
for(var panelLayoutOverlayId in this.currentPanel.layoutOverlays){var layoutOverlay=this.currentPanel.layoutOverlays[panelLayoutOverlayId];var personalizationLayoutOverlay=new PersonalizeOverlay(layoutOverlay,this.resolution);if(!hasBorder&&layoutOverlay.editable=='1'){this.borderTray.render(personalizationLayoutOverlay);hasBorder=true;if(layoutOverlay.switchedOn==1){personalizationLayoutOverlay.render(previewPane);}}else{personalizationLayoutOverlay.render(previewPane);}
this.layoutOverlays.push(personalizationLayoutOverlay);}}
if(!hasBorder){this.borderTray.remove();}},activatePanelLayout:function(){if(!this.currentPanel.panelLayoutId||this.currentPanel.panelLayoutRendered[this.currentPanel.panelLayoutId]){return;}
var productPanel=Personalize.product.panels[this.currentPanel.panelId];var layout=productPanel.layouts[this.currentPanel.panelLayoutId];this.currentPanel.layoutPhotos={};for(var photoId in layout.photos){var productLayoutPhoto=layout.photos[photoId];var layoutPhoto=TP.extendObject(new LayoutPhoto(),productLayoutPhoto);layoutPhoto.photoId=productLayoutPhoto.id;this.currentPanel.layoutPhotos[productLayoutPhoto.id]=layoutPhoto;}
this.currentPanel.layoutTextboxes={};for(var textboxId in layout.textboxes){Personalize.services.addLayoutTextbox(this.currentPanel,layout.textboxes[textboxId]);}
this.currentPanel.layoutOverlays={};for(var overlayId in layout.overlays){var productLayoutOverlay=layout.overlays[overlayId];var layoutOverlay=TP.extendObject(new LayoutOverlay(),productLayoutOverlay);layoutOverlay.overlayId=productLayoutOverlay.id;layoutOverlay.id=null;this.currentPanel.layoutOverlays[productLayoutOverlay.id]=layoutOverlay;}
this.currentPanel.panelLayoutRendered[layout.layoutId]=true;},layoutChange:function(layoutId){try{var splicedStyleClassId=null;for(var i=0;i<this.layoutTextboxes.length;i++){var textbox=this.layoutTextboxes[i];this.layoutSavedData.textboxes[i]=TP.copy(textbox.textbox);for(var j=0;j<this.textboxEditors.length;j++){if(textbox.textbox.textboxId==this.textboxEditors[j].textbox.textboxId){splicedStyleClassId=this.textboxEditors[j].myStyleEditor.styleClass.styleClassId;this.textboxEditors.splice(j,1);break;}}
for(var k=0;k<this.styleEditors.length;k++){if(splicedStyleClassId===this.styleEditors[k].styleClass.styleClassId){this.styleEditors.splice(k,1);break;}}
textbox.remove();textbox.editor.remove();delete textbox;}
for(var i=0;i<this.layoutPhotos.length;i++){var photo=this.layoutPhotos[i];this.layoutSavedData.photos[i]=TP.copy(photo.photo);photo.remove();delete photo;}
for(var i=0;i<this.layoutOverlays.length;i++){var overlay=this.layoutOverlays[i];this.layoutSavedData.overlays[i]=TP.copy(overlay.overlay);overlay.remove();delete overlay;}
this.layoutTextboxes=[];this.layoutPhotos=[];this.layoutOverlays=[];this.currentPanel.panelLayoutId=layoutId;this.currentPanel.layoutId=layoutId;var productPanel=Personalize.product.panels[this.currentPanel.panelId];var layout=productPanel.layouts[layoutId];this.currentPanel.layoutTextboxes={};this.currentPanel.layoutPhotos={};this.currentPanel.layoutOverlays={};var photoCount=0;for(var photoId in layout.photos){var productLayoutPhoto=layout.photos[photoId];var layoutPhoto=TP.extendObject(new LayoutPhoto(),productLayoutPhoto);layoutPhoto.photoId=productLayoutPhoto.id;if(this.layoutSavedData.photos[photoCount]){var oldPhoto=this.layoutSavedData.photos[photoCount];layoutPhoto.contentPhotoId=oldPhoto.contentPhotoId;layoutPhoto.effectId=oldPhoto.effectId;layoutPhoto.rotation=oldPhoto.rotation;layoutPhoto.cropX=oldPhoto.cropX;layoutPhoto.cropY=oldPhoto.cropY;layoutPhoto.cropHeight=oldPhoto.cropHeight;layoutPhoto.cropWidth=oldPhoto.cropWidth;}
this.currentPanel.layoutPhotos[productLayoutPhoto.id]=layoutPhoto;var personalizationLayoutPhoto=new PersonalizePhoto(layoutPhoto,productLayoutPhoto,this.resolution);personalizationLayoutPhoto.render(this.previewImageHandle);this.layoutPhotos.push(personalizationLayoutPhoto);photoCount++;}
for(var overlayId in layout.overlays){var productLayoutOverlay=layout.overlays[overlayId];var layoutOverlay=TP.extendObject(new LayoutOverlay(),productLayoutOverlay);layoutOverlay.overlayId=productLayoutOverlay.id;layoutOverlay.id=null;this.currentPanel.layoutOverlays[productLayoutOverlay.id]=layoutOverlay;var personalizationLayoutOverlay=new PersonalizeOverlay(layoutOverlay,this.resolution);personalizationLayoutOverlay.render(this.previewImageHandle);this.layoutOverlays.push(personalizationLayoutOverlay);}
var maxStyleClassId=0;var requiringNormalization=[];for(var textboxId in layout.textboxes){Personalize.services.addLayoutTextbox(this.currentPanel,layout.textboxes[textboxId]);var textbox=this.currentPanel.layoutTextboxes[textboxId];var editor=new PersonalizeTextboxEditor();editor.textbox=textbox;editor.productTextbox=layout.textboxes[textboxId];if(!editor.getStyleClassId()&&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);Personalize.product.styleClasses[style.styleClassId]=style;styleEditor.setStyleClass(style);styleEditor.attachTextEditor(currentEditor);this.styleEditors.push(styleEditor);this.textboxEditors.push(currentEditor);}
this.renderEditPanel();this.changeDoodleTrayColors();if($('photoTab')){this.tabController.activateTab('photoTab');}
for(var i=0;i<this.textboxes.length;i++){var personalizeTextbox=this.textboxes[i];var oldFontId=personalizeTextbox.textbox.fontId;var oldFontSizeId=personalizeTextbox.textbox.fontSize;var myStyleEditor=personalizeTextbox.editor.myStyleEditor;myStyleEditor.convertPrettySelects();myStyleEditor.fontSelect.select(oldFontId);myStyleEditor.fontSizeSelect.select(oldFontSizeId);}
var textboxCount=0;for(var textboxId in this.currentPanel.layoutTextboxes){var textbox=this.currentPanel.layoutTextboxes[textboxId];var panelTextbox=new PersonalizeTextbox(textbox,this.resolution);panelTextbox.findEditorAndAttach();panelTextbox.render(this.previewImageHandle);var myStyleEditor=panelTextbox.editor.myStyleEditor;var defaultFontId=textbox.fontId;var defaultFontSize=textbox.fontSize;myStyleEditor.convertPrettySelects();myStyleEditor.fontSelect.select(defaultFontId);myStyleEditor.fontSizeSelect.select(defaultFontSize);if(this.layoutSavedData.textboxes[textboxCount]){var oldTextbox=this.layoutSavedData.textboxes[textboxCount];panelTextbox.editor.textArea.value=oldTextbox.content;textbox.horizontalAlignmentId=oldTextbox.horizontalAlignmentId;textbox.verticalAlignmentId=oldTextbox.verticalAlignmentId;panelTextbox.editor.initialTextAlign(true);myStyleEditor.fontSelect.select(oldTextbox.fontId);myStyleEditor.fontSizeSelect.select(oldTextbox.fontSize);var changeFontColor=myStyleEditor.fontColorSelect.setValue.bindAsEventListener(myStyleEditor,oldTextbox.fontColorId);changeFontColor();for(var k=0;k<myStyleEditor.fontColorSelect.swatches.length;k++){if(myStyleEditor.fontColorSelect.swatches[k].colorId==oldTextbox.fontColorId){selectColorSwatchElem=myStyleEditor.fontColorSelect.changeSelection.bindAsEventListener(myStyleEditor.fontColorSelect,myStyleEditor.fontColorSelect.swatches[k]);selectColorSwatchElem();break;}}
panelTextbox.content=oldTextbox.content;panelTextbox.fontColorId=oldTextbox.fontColorId;panelTextbox.fontId=oldTextbox.fontId;panelTextbox.fontSize=oldTextbox.fontSize;}
this.layoutTextboxes.push(panelTextbox);textboxCount++;}
this.selectFirstTextbox();}catch(e){}
this.currentPanel.panelLayoutRendered[layout.layoutId]=true;},renderDoodleTray:function(){var doodleDom=$('personalizeStep_doodleTray');if(this.hasDoodles()){doodleDom.show();this.doodleTray=new DoodleTray();this.doodleTray.render('personalizeStep_doodleTray');}else{doodleDom.hide();if($('personalizeStep_monogramTray')){this.doodleTray=new MonogramTray();this.doodleTray.render('personalizeStep_monogramTray');}}
if(this.hasMonogram()){}},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){}}
var panelLayoutId=this.currentPanel.panelLayoutId;if(panelLayoutId){try{editor.productTextbox=Personalize.product.panels[panelId].layouts[panelLayoutId].textboxes[textbox.textboxId];}catch(e){}}}}
if(!editor.getStyleClassId()&&editor.hasLocalStyle()){requiringNormalization.push(editor);}else{var styleClassId=editor.getStyleClassId();if(styleClassId>maxStyleClassId){maxStyleClassId=styleClassId;}
siblingEditors=this.findEditorForStyleClassId(styleClassId);styleEditor=null;var styleEditor=new PersonalizeStyleEditor('Text Style');for(var k=0;k<siblingEditors.length;k++){styleEditor.addSibling(siblingEditors[k]);siblingEditors[k].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);Personalize.product.styleClasses[style.styleClassId]=style;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){var editors=[];for(var i=0;i<this.styleEditors.length;i++){if(this.styleEditors[i].isStyleClass(styleClassId)){editors.push(this.styleEditors[i]);}}
return editors;},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);Personalize.trackPageview('/personalize/Personalize');},showDropAreas:function(){this.dropAreasVisible=false;for(var i=0;i<this.dropAreas.length;i++){var dropArea=this.dropAreas[i];dropArea.show();}},hideDropAreas:function(){this.dropAreasVisible=true;for(var i=0;i<this.dropAreas.length;i++){var dropArea=this.dropAreas[i];dropArea.hide();}},hasDoodles:function(){var productPanel=Personalize.product.panels[this.currentPanel.panelId];var doodleCount=0;for(var availableDoodleId in productPanel.availableDoodles){var availableDoodle=productPanel.availableDoodles[availableDoodleId];var doodleId=availableDoodle.doodleColorImage.doodleId;var productDoodle=Personalize.product.doodles[doodleId];if(productDoodle.type==0){doodleCount++;}else{return false;}}
return doodleCount>0;},hasMonogram:function(){var productPanel=Personalize.product.panels[this.currentPanel.panelId];var monogramCount=0;for(var availableDoodleId in productPanel.availableDoodles){var availableDoodle=productPanel.availableDoodles[availableDoodleId];var doodleId=availableDoodle.doodleColorImage.doodleId;var productDoodle=Personalize.product.doodles[doodleId];if(productDoodle.type>0){monogramCount++;}}
return monogramCount>0;},hasPhotos:function(){for(var panelId in Personalize.product.panels){var panel=Personalize.product.panels[panelId];for(var photoId in panel.photos){return true;}
for(var photoId in panel.layouts[this.currentPanel.panelLayoutId]){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){if(Personalize.isIe()||Personalize.ie8){Droppables.drops=[];}
this.setPanelLayoutId();this.activatePanelLayout();this.createEditors();this.renderPanelSelect();this.renderColorSwitcher();this.renderEditPanel();this.renderDoodleTray();this.renderPreviewPanel();this.renderTabController();if(this.hasPhotos()){this.renderPhotoTray();this.photoTray.updateUsedThumbs();}
this.clearError();this.layoutTray.populate();this.convertPrettySelects();this.enableNextButtons();this.rendered=true;}else{}}catch(e){}
$(this.element.id).show();this.selectFirstTextbox();if(Personalize.saveLogin){Personalize.saveLogin=0;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){if(Personalize.isIe()||Personalize.ie8){Droppables.drops=[];}
this.cleanupEditors();this.currentPanel=newPanel;this.textboxes=[];this.layoutTextboxes=[];this.layoutPhotos=[];this.layoutOverlays=[];this.dropAreas=[];var productPanel=Personalize.product.panels[this.currentPanel.panelId];this.panelNameElement.update('Personalize Your Card');this.setPanelLayoutId();this.activatePanelLayout();this.createEditors();this.renderEditPanel();this.renderDoodleTray();this.renderPreviewPanel();this.renderTabController();this.renderPhotoTray();this.layoutTray.populate();this.convertPrettySelects();this.selectFirstTextbox();},beforeChangeColorCheck:function(fnHandler,targetColorId){var productPanel=Personalize.product.panels[this.currentPanel.panelId];var associateDoodles=[];for(var availableDoodleId in productPanel.availableDoodles){var availableDoodle=productPanel.availableDoodles[availableDoodleId];if(availableDoodle.productPanelColorId==targetColorId){associateDoodles.push(availableDoodle);}}
var doodleCount=0;var doodleFound=0;for(var doodleId in this.currentPanel.doodles){var personalizationDoodle=this.currentPanel.doodles[doodleId];doodleCount++;for(var i=0;i<associateDoodles.length;i++){var availableDoodle=associateDoodles[i];if(personalizationDoodle.doodleId==availableDoodle.doodleColorImage.doodleId){doodleFound++;break;}}}
if(doodleCount==doodleFound){if(typeof fnHandler==='function'){fnHandler();return;}}
if(!this.changeColorConfirmDlg){this.changeColorConfirmDlg=new PersonalizePopup('Change color confirmation','changeColorConfirmDlg');}
this.ccDlgElem=this.changeColorConfirmDlg.getPopupElement();var textElem=new Element('div',{style:'margin:16px;width:340px;font-family:helvetica; font-size:12px; ',align:'left'}).update('Certain Design Accents are not available in the new color you\'ve chosen. They will be removed when you change colors. Would you like to continue?');var buttonElem=new Element('div',{align:'right',style:'margin:8px;'});var closeBtn=new Element('div',{'class':'sprite-btn_close clickable',style:'float: right; margin-left: 5px;'});closeBtn.observe('click',this.changeColorConfirmDlg.hidePopup.bind(this.changeColorConfirmDlg));buttonElem.insert(closeBtn);var acceptBtn=new Element('div',{'class':'sprite-btn-accept clickable',style:'float: right;'});acceptBtn.observe('click',this.agreeToChangeColor.bind(this,this.changeColorConfirmDlg.hidePopup.bind(this.changeColorConfirmDlg),fnHandler));buttonElem.insert(acceptBtn);buttonElem.insert(new Element('div',{style:'clear: both;'}));this.ccDlgElem.update(textElem);this.ccDlgElem.insert(buttonElem);this.ccDlgElem.setStyle({width:'356px'});this.changeColorConfirmDlg.showPopup();},agreeToChangeColor:function(popupHandler,fnHandler){if(typeof popupHandler==='function'){popupHandler();}
if(typeof fnHandler==='function'){fnHandler();}},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);if(this.overlays[i].overlay.editable=='1'){this.borderTray.render(this.overlays[i]);}}
Personalize.personalization.colorCyan=null;Personalize.personalization.colorMagenta=null;Personalize.personalization.colorYellow=null;Personalize.personalization.colorBlack=null;this.panelTextboxesChangeColor(newColor);this.changeDoodleTrayColors();}catch(e){}},panelTextboxesChangeColor:function(colorId){try{var currentPanelId=this.currentPanel.panelId;var styleClasses=Personalize.product.styleClasses;var personalizePanels=Personalize.personalization.panels;var productPanels=Personalize.product.panels;for(var panelId in personalizePanels){if(panelId!=currentPanelId&&(productPanels[panelId].number<productPanels[currentPanelId].number)){for(var layoutTextboxId in personalizePanels[panelId].layoutTextboxes){var layoutTextbox=personalizePanels[panelId].layoutTextboxes[layoutTextboxId];var fontColors=styleClasses[layoutTextbox.styleClassId].style.fontColors[colorId];for(var fontColorId in fontColors){if(fontColors[fontColorId]['default']==1){layoutTextbox.fontColorId=fontColorId;}}}
for(var textboxId in personalizePanels[panelId].textboxes){var textbox=personalizePanels[panelId].textboxes[textboxId];var fontColors=styleClasses[textbox.styleClassId].style.fontColors[colorId];for(var fontColorId in fontColors){if(fontColors[fontColorId]['default']==1){textbox.fontColorId=fontColorId;}}}}}}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);},convertPrettySelects:function(){if(this.styleEditors.length==this.textboxEditors.length){for(var i=0;i<this.styleEditors.length;i++){var textEditor=this.textboxEditors[i];var styleEditor=textEditor.myStyleEditor;var textbox=textEditor.panelTextbox.textbox;var oldFontId=textbox.fontId;var oldFontSize=textbox.fontSize;styleEditor.convertPrettySelects();styleEditor.fontSelect.select(oldFontId);styleEditor.fontSizeSelect.select(oldFontSize);}}},selectFirstTextbox:function(){if(this.textboxEditors.length!=0){this.textboxEditors[0].getFocus();this.textboxEditors[0].setFocus();}},setPanelLayoutId:function(){var productPanel=Personalize.product.panels[this.currentPanel.panelId];this.currentPanel.panelLayoutRendered={};if(this.currentPanel.layoutId&&!this.hasTemplateLayouts(this.currentPanel.panelId)){this.currentPanel.panelLayoutId=this.currentPanel.layoutId;this.currentPanel.panelLayoutRendered[this.currentPanel.layoutId]=true;return;}
if(!this.currentPanel.panelLayoutId){try{for(var id in productPanel.layouts){this.currentPanel.panelLayoutRendered[id]=false;if(typeof layout==='undefined'){var layout=productPanel.layouts[id];}}
if(typeof layout!=='undefined'){this.currentPanel.panelLayoutId=layout.layoutId;this.currentPanel.layoutId=layout.layoutId;}}catch(e){}}},hasTemplateLayouts:function(panelId){var productPanel=Personalize.product.panels[panelId];for(var i in productPanel.templateLayouts){return true;}
return false;},popupHelp:function(ev,helpType){var helpTitle='';var helpText='';if(helpType=='textbox'){helpTitle='Text box'
helpText=Personalize.strings.WPD_TEXTBOX_HELP;}else{if(this.bottomTabsHelp=='doodle'){helpTitle='Design Accents'
helpText=Personalize.strings.WPD_DOODLE_HELP;}else if(this.bottomTabsHelp=='photo'){helpTitle='Photos'
helpText=Personalize.strings.WPD_PHOTO_HELP;}}
var helpDlg=new PersonalizePopup(helpTitle,'helpPopup_');var content=helpDlg.getPopupElement();var text=new Element('div',{align:'left'}).update(helpText);content.insert(text);content.setStyle({padding:'20px',fontFamily:'Helvetica',fontSize:'12px',width:'400px'});helpDlg.showPopup();Event.stop(ev);},enableNextButtons:function(){var nextButtons=$$('div.sprite-btn-next-disabled');nextButtons.each(function(button){button.removeClassName('sprite-btn-next-disabled');button.addClassName('sprite-btn-next');});}});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.beforeSwitch.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);},beforeSwitch:function(ev,colorId,colorElement){if(typeof this.beforeSwitchCallback==='function'){this.beforeSwitchCallback(this.handleColorSwitch.bind(this,ev,colorId,colorElement),colorId);}},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){if(parseFloat(productPanel.backPanel)==1){return Personalize.hosts.images+'product/'+Personalize.product.id+'/panel/'+productPanel.number+'/paper/'+Personalize.product.paperId+'/height/36/background/ffffff/shadow/1.jpg';}else{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;};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=210;var sizeWidth=50;var colorWidth=75;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',{'class':'textEditorFontSelect',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&&parseFloat(font.minimumSize)<=this.maxFontSize()){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.fontChangeHandler.bind(this));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&&parseFloat(font.minimumSize)<=this.maxFontSize()){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.fontSizeSelect=new Element('select',{'class':'textEditorSizeSelect',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,title:color.displayName});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 fontTitleText='Font ';if(!small)fontTitleText=this.title;var titleDiv=new Element('div',{style:"float:left; width:"+fontWidth+"px",'class':'styleTitle'}).update(fontTitleText);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;},fontChangeHandler:function(){this.renderFontSizeSelect();this.styleChangeHandler(null,this.fontSelect);},renderFontSizeSelect:function(){var fontId=this.getSelectedFontId();var font=Personalize.masterFontList[fontId];var minimumSize=parseFloat(font.minimumSize);var selectedFontSize=this.getSelectedFontSize();selectedFontSize=(selectedFontSize>minimumSize)?selectedFontSize:minimumSize;try{this.fontSizeSelect.clearOptions();for(var size in this.styleClass.style.fontSizes){if(size>=minimumSize){this.fontSizeSelect.add(size,size);}}
this.fontSizeSelect.render();}catch(e){}
this.fontSizeRestore(selectedFontSize);},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);}},fontSizeRestore:function(selectedFontSize){try{var selectedIndex=this.fontSizeSelect.getSelectedIndex(selectedFontSize);if(selectedIndex>0){this.fontSizeSelect.select(selectedFontSize);this.fontSizeSelect.selectedIndex=selectedIndex;}}catch(e){}},mouseOver:function(ev){try{if(ev.target.hasClassName('sprite-icon-prettyselectarrow')||$(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();this.fontSelect.select(values.fontId);this.fontSizeSelect.select(values.fontSize);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();}},convertPrettySelects:function(){try{var psSizeSelect=new PrettySelect2(this.fontSizeSelect.identify(),{postSelect:this.styleChangeHandler.bind(this),renderFn:function(params){var item=new Element('div').update(this.text);item.setStyle({});item.identify();return item;}});psSizeSelect.render();this.fontSizeSelect=psSizeSelect;var psFontSelect=new PrettySelect2(this.fontSelect.identify(),{postSelect:this.fontChangeHandler.bind(this),renderFn:function(params){var item=new Element('div',{'class':'sprite-font-'+this.value});return item;}});psFontSelect.render();this.fontSelect=psFontSelect;}catch(e){}},maxFontSize:function(){for(var fontSizeId in this.styleClass.style.fontSizes){var maxFontSize=fontSizeId;}
return maxFontSize;}};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((parseFloat(this.textbox.controlX)>0||parseFloat(this.textbox.controlY)>0||parseFloat(this.textbox.controlWidth)>0||parseFloat(this.textbox.controlHeight)>0)){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((parseFloat(this.textbox.controlX)>0||parseFloat(this.textbox.controlY)>0||parseFloat(this.textbox.controlWidth)>0||parseFloat(this.textbox.controlHeight)>0)){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();setTimeout(this.editor.showToolTip.bind(this.editor),500);},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.00});clearInterval(this.loadingTimer);this.loadingTimer=null;if(this.height!=0&&this.width!=0){var width=this.image.naturalWidth?this.image.naturalWidth:this.image.width;var height=this.image.naturalHeight?this.image.naturalHeight:this.image.height;if(height>this.height||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 imageWidth=bounds.width;var imageHeight=bounds.height;if(this.textbox.angle%90==0&&this.textbox.angle%180!=0){imageWidth=bounds.height;imageHeight=bounds.width;}
var parameters={width:imageWidth,height:imageHeight,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',angle:this.textbox.angle,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.text+'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'});},remove:function(){this.stripeElement.remove();this.domElement.remove();}};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;this.toolTipRendered=false;};PersonalizeTextboxEditor.prototype={attachTextbox:function(panelTextbox){this.panelTextbox=panelTextbox;},hasLocalStyle:function(){var colors=false;var sizes=false;var fonts=false;if(typeof this.productTextbox!=='undefined'){for(var i in this.productTextbox.fontColors[Personalize.personalization.productColorId]){colors=true;continue;}
for(var i in this.productTextbox.fontSizes){sizes=true;continue;}
for(var i in this.productTextbox.fonts){fonts=true;continue;}}
return(colors&&sizes&&fonts);},getStyleObject:function(){var obj={};obj.style={};obj.style.fontColors=this.productTextbox.fontColors;obj.style.fontSizes=this.productTextbox.fontSizes;obj.style.fonts=this.productTextbox.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.leftAlign.addClassName('textAlignIconSelected');this.centerAlign.removeClassName('textAlignIconSelected');this.rightAlign.removeClassName('textAlignIconSelected');this.panelTextbox.render();},doRightAlign:function(){this.textbox.horizontalAlignmentId=3;this.rightAlign.addClassName('textAlignIconSelected');this.centerAlign.removeClassName('textAlignIconSelected');this.leftAlign.removeClassName('textAlignIconSelected');this.panelTextbox.render();},doCenterAlign:function(){this.textbox.horizontalAlignmentId=2;this.centerAlign.addClassName('textAlignIconSelected');this.rightAlign.removeClassName('textAlignIconSelected');this.leftAlign.removeClassName('textAlignIconSelected');this.panelTextbox.render();},initialTextAlign:function(){var alignmentId=(this.textbox.horizontalAlignmentId)?this.textbox.horizontalAlignmentId:this.productTextbox.horizontalAlignmentId;switch(parseFloat(alignmentId)){case 1:this.leftAlign.addClassName('textAlignIconSelected');this.centerAlign.removeClassName('textAlignIconSelected');this.rightAlign.removeClassName('textAlignIconSelected');break;case 2:this.centerAlign.addClassName('textAlignIconSelected');this.rightAlign.removeClassName('textAlignIconSelected');this.leftAlign.removeClassName('textAlignIconSelected');break;case 3:this.rightAlign.addClassName('textAlignIconSelected');this.centerAlign.removeClassName('textAlignIconSelected');this.leftAlign.removeClassName('textAlignIconSelected');break;default:this.leftAlign.addClassName('textAlignIconSelected');this.centerAlign.removeClassName('textAlignIconSelected');this.rightAlign.removeClassName('textAlignIconSelected');}},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>'}
if(this.title.indexOf('1')>0){titleString+='<div class="sprite-icon-help clickable" id="textboxHelp" style="float:right;"></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:24px; position:relative;margin: 2px 0px;'});this.leftAlign=new Element('div',{id:'leftAlign_'+idPostfix,style:'float: left','class':'sprite-btn-align-left clickable textAlignIcon'});this.centerAlign=new Element('div',{id:'centerAlign_'+idPostfix,style:'float: left','class':'sprite-btn-align-center clickable textAlignIcon'});this.rightAlign=new Element('div',{id:'rightAlign_'+idPostfix,style:'float: left','class':'sprite-btn-align-right clickable textAlignIcon'});var applyButton=new Element('div',{id:'applyButton_'+idPostfix,'class':'sprite-btn-apply clickable'});this.leftAlign.observe('click',this.doLeftAlign.bind(this));this.centerAlign.observe('click',this.doCenterAlign.bind(this));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(this.leftAlign);this.bottomElement.insert(this.centerAlign);this.bottomElement.insert(this.rightAlign);this.initialTextAlign();}
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();if(Personalize.ie6){this.textArea.setStyle({width:'330px'});}
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));this.textArea.observe('mouseover',this.overHandler.bindAsEventListener(this));this.textArea.observe('mouseout',this.outHandler.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});}}
this.hideToolTip();},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')||$(target).hasClassName('panelThumbnailContainer')||$(target).hasClassName('panelThumbnail')){return;}else if($(target).descendantOf('personalizeLayoutTray_tray')){if(Personalize.isIe()){this.lightDown();this.expanded=false;return;}}else if(target.parentNode&&target.parentNode!=window.document){if($(target.parentNode).descendantOf(this.domElement)){if(this.focusLoserCache){$(document).stopObserving('click',this.focusLoserCache);}
this.focusLoserCache=this.focusLoser.bindAsEventListener(this);$(document).observe('click',this.focusLoserCache);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;}}else if(ev.target.parentNode){if($(ev.target.parentNode).descendantOf(this.domElement)){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;}},overHandler:function(){this.lightUp();},outHandler:function(){if(this.hasFocus)return;this.lightDown();},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();},showToolTip:function(){try{if(!this.toolTipRendered){this.toolTipRendered=true;this.toolTip=new TPBalloon({anchor:this.textArea.identify(),width:200,height:40,fadeTime:0.3,imageBase:Personalize.hosts['static']+'/image/balloon/',stemPosition:'rightMiddle',content:'<b>Choose your text and font options here.</b>',contentClass:'toolTipContent',animator:new TPBalloonPointerAnimator({repetitions:2,distance:5,delay:0})});}}catch(e){}
this.toolTip.show();setTimeout(this.hideToolTip.bind(this),5000);},hideToolTip:function(){if(this.toolTip){this.toolTip.hide();}},remove:function(){this.domElement.remove();}};var PersonalizePhotoTray=function(){this.domElement=null;this.photos=[];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.trayScrollLeft=new Element('div',{style:'float:left;margin-left:3px;margin-right:10px;margin-top:33px;','class':'sprite-btn-scroll-left clickable'}).update('');this.trayScrollRight=new Element('div',{style:'float:left;margin-left:10px;margin-right:3px;margin-top:33px;','class':'sprite-btn-scroll-right clickable'}).update('');this.trayScrollLeft.observe('mouseover',this.scrollLeft.bind(this));this.trayScrollLeft.observe('mouseout',this.scrollLeftStop.bind(this));this.trayScrollRight.observe('mouseover',this.scrollRight.bind(this));this.trayScrollRight.observe('mouseout',this.scrollRightStop.bind(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.trayScrollLeft);this.mainElement.insert(this.trayAreaContainer);this.mainElement.insert(this.trayScrollRight);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);this.imageSpace=new PhotoTrayImageSpace('PhotoTrayArea');this.imageSpace.parent=this;this.imageSpace.photos=(!Personalize.isSample())?this.photos:Personalize.adminPhotos;this.imageSpace.render();},uploadPhoto:function(){Personalize.activeStep.uploadPhotos();},addPhoto:function(photo){this.photos.push(photo);this.addThumb(photo);this.imageSpace.addItem();},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;Personalize.trigger('userphotosloaded');if(this.populateOnLoad){this.populate();}else{this.preloadThumbs();}}.bind(this)});},addThumb:function(photo){var thumbImg=new Element('img',{});thumbImg.onload=function(){try{var width=this.getWidth()?this.getWidth():this.width;var height=this.getHeight()?this.getHeight():this.height;$(this).up().setStyle({'top':(60-height)+'px','position':'relative'});$(this).next().setStyle({'top':(height-20)+'px','left':(width-24)+'px'});$(this).setStyle({'left':((60-width)/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){console.log("erroe -",e);}};thumbImg.style.display='none';thumbImg.reflections=this.reflections;thumbImg.photoId=photo.id
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;},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(){if(Personalize.isSample()){return;}
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();}}}}}
for(var i in Personalize.activeStep.layoutPhotos){var photo=Personalize.activeStep.layoutPhotos[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();}}}}}},setScrollLeftAvailable:function(){if(this.trayScrollLeft.hasClassName('sprite-btn-left-off-arrow')){this.trayScrollLeft.removeClassName('sprite-btn-left-off-arrow');this.trayScrollLeft.addClassName('sprite-btn-scroll-left');}},setScrollRightAvailable:function(){if(this.trayScrollRight.hasClassName('sprite-btn-right-arrow-off')){this.trayScrollRight.removeClassName('sprite-btn-right-arrow-off');this.trayScrollRight.addClassName('sprite-btn-scroll-right');}},scrollLeftFinish:function(){if(this.trayScrollLeft.hasClassName('sprite-btn-scroll-left')){this.trayScrollLeft.removeClassName('sprite-btn-scroll-left');this.trayScrollLeft.addClassName('sprite-btn-left-off-arrow');}},scrollRightFinish:function(){if(this.trayScrollRight.hasClassName('sprite-btn-scroll-right')){this.trayScrollRight.removeClassName('sprite-btn-scroll-right');this.trayScrollRight.addClassName('sprite-btn-right-arrow-off');}},scrollLeft:function(){if(!this.imageSpace){return;}
this.imageSpace.scrollLeft();},scrollRight:function(){if(!this.imageSpace){return;}
this.imageSpace.scrollRight();},scrollRightStop:function(){if(!this.imageSpace){return;}
this.imageSpace.scrollRightStop();},scrollLeftStop:function(){if(!this.imageSpace){return;}
this.imageSpace.scrollLeftStop();}};var SamplePhotoTray=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;};SamplePhotoTray.prototype=TP.extendObject(new PersonalizePhotoTray(),{renderThumbs:function(){this.countElement.update('<b>Photo Tray</b>');this.trayArea.update('');for(var photoIndex=0;photoIndex<Personalize.adminPhotos.length;photoIndex++){var fileId=Personalize.adminPhotos[photoIndex].id;this.addThumb(fileId);}},addThumb:function(fileId){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'});this.style.display='block';$(this).addClassName('imageDraggable');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(fileId);thumbImg.fileId=fileId;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);this.trayWidth+=80;this.trayArea.setStyle({width:this.trayWidth+'px'});this.trayArea.insert(thumb);},getPhotoThumbUrl:function(fileId){return Personalize.hosts.images+'image/file/'+fileId+'/width/70/height/70.jpg';}});var PhotoTrayImageSpace=function(spaceDomId){this.domId=spaceDomId;this.unitWidth=80;this.unitHeight=80;this.photos=[];this.scrollDuration=0.5;this.scrollRightFlag=false;this.scrollLeftFlag=false;this.maxRightTo=0;};PhotoTrayImageSpace.prototype={addItem:function(){this.containerDom.setStyle({width:(this.unitWidth*this.photos.length)+'px',height:this.unitHeight+'px'});},scrollLeft:function(){this.scrollLeftFlag=true;var parent=this.containerDom.up();var parentOffset=parent.positionedOffset();var offSet=Personalize.pxToNumber(this.containerDom.style.left);if(!offSet){offSet=0;}
if(offSet>=0){return;}
this.parent.setScrollRightAvailable();var moveLeftAmount=-offSet;var numberOfItemsToScroll=Math.abs(offSet)/this.unitWidth;var duration=numberOfItemsToScroll*this.scrollDuration;this.scrollLeftEffect=new Effect.Move(this.domId,{x:moveLeftAmount,duration:duration,mode:'relative',transition:Effect.Transitions.linear,beforeUpdate:this.scrollLeftUpdate.bind(this),afterFinish:this.scrollLeftFinish.bind(this)});},scrollRight:function(){this.scrollRightFlag=true;var parent=this.containerDom.up();var parentOffset=parent.positionedOffset();var offSet=Personalize.pxToNumber(this.containerDom.style.left);var containerWidth=Personalize.pxToNumber(this.containerDom.style.width);if(!offSet){offSet=0;}
this.maxRightTo=-(containerWidth-parent.getWidth());if(offSet<=this.maxRightTo){return;}
this.parent.setScrollLeftAvailable();var numberOfItemsToScroll=this.photos.length-((Math.abs(offSet)+parent.getWidth())/this.unitWidth);var duration=numberOfItemsToScroll*this.scrollDuration;this.scrollRightEffect=new Effect.Move(this.domId,{x:this.maxRightTo-offSet,duration:duration,mode:'relative',transition:Effect.Transitions.linear,beforeUpdate:this.scrollRightUpdate.bind(this),afterFinish:this.scrollRightFinish.bind(this)});},scrollLeftRightCheck:function(){var parent=this.containerDom.up();var parentOffset=parent.positionedOffset();var offSet=Personalize.pxToNumber(this.containerDom.style.left);var containerWidth=Personalize.pxToNumber(this.containerDom.style.width);if(!offSet){offSet=0;}
if(offSet>=0){this.parent.scrollLeftFinish();}
if(containerWidth<this.parentWidth){this.parent.scrollRightFinish();}},scrollRightFinish:function(){this.parent.scrollRightFinish();},scrollLeftFinish:function(){this.parent.scrollLeftFinish();},scrollRightStop:function(){this.scrollRightFlag=false;},scrollLeftStop:function(){this.scrollLeftFlag=false;},scrollRightUpdate:function(){if(!this.scrollRightFlag){this.scrollRightEffect.cancel();}},scrollLeftUpdate:function(){if(!this.scrollLeftFlag){this.scrollLeftEffect.cancel();}},render:function(){itemContainer=$(this.domId);itemContainer.setStyle({width:(this.unitWidth*this.photos.length)+'px',height:this.unitHeight+'px'});this.containerDom=itemContainer;return this.containerDom;}};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){if(element.photo){this.swapPhoto(element.photo);}else if(Personalize.isSample()&&element.fileId){new Ajax.Request('/personalize/sampleImage',{method:'post',parameters:{fileId:element.fileId},onSuccess:function(transport){this.swapPhoto(transport.responseJSON);this.photo.sampleImageId=element.fileId;}.bind(this),onFailure:function(){alert('Error adding PMS 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('');var domWidth=parseInt(this.domElement.style.width);var domHeight=parseInt(this.domElement.style.height);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:domWidth,height:domHeight,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();var comparisonId=(!Personalize.isSample())?this.photo.contentPhotoId:this.photo.sampleImageId;for(var i=0;i<photos.length;i++){if(photos[i].id==comparisonId){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.textv2Cache+'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();}},remove:function(){this.handleElement.remove();this.domElement.remove();this.borderElement.remove();}};var personalizeLayoutTray=function(){this.init();};personalizeLayoutTray.prototype={init:function(){this.count=0;this.domElement=$('personalizeLayoutTrayBox');this.contentElement=$('personalizeLayoutTray_tray');this.selectedLayoutElement=null;this.selectedLayoutId=null;this.thumbContainerWidth=91;Personalize.observe('changepanel',this.changePanel.bind(this));},changePanel:function(){this.populate();},populate:function(){this.contentElement.update();var panel=Personalize.activeStep.currentPanel;var productPanel=Personalize.product.panels[panel.panelId];var count=0;for(var layoutId in productPanel.layouts){count++;var layout=productPanel.layouts[layoutId];this.addThumb(layout,(layoutId==panel.panelLayoutId));}
if(count>1){var contentWidth=this.thumbContainerWidth*count;this.contentElement.setStyle({width:contentWidth+'px',height:'120px'});this.domElement.show();}else{this.domElement.hide();}
this.count=count;},addThumb:function(layout,selected){var layoutElementContainer=new Element('div',{'class':'personalizeLayoutTrayThumbContainer clickable'});var layoutElement=new Element('div',{'class':'personalizeLayoutTrayThumb'});var layoutImg=new Element('img',{'class':'layoutImage ',title:layout.layout.displayName});var title=layout.layout.displayName.replace(/\s(\d)/g,"<br />$1");var layoutTitle=new Element('div',{'class':'personalizeLayoutTrayThumbName'}).update(title);layoutImg.onload=function(){var parentHeight=70;var parentWidth=70;var marginTop=(parentHeight-this.height)/2;var marginLeft=(parentWidth-this.width)/2;$(this).setStyle({marginTop:marginTop+'px',marginLeft:marginLeft+'px'});}
layoutElementContainer.observe('click',this.selectLayout.bind(this,layout,layoutElement));layoutImg.src=Personalize.hosts.images+'image/layout/'+layout.layout.imageId+'/width/70/height/70/shadow/1.png';if(selected){this.selectedLayoutElement=layoutElement;this.selectedLayoutId=layout.id;this.selectedLayoutElement.addClassName('selected');}
layoutElementContainer.insert(layoutElement.insert(layoutImg));layoutElementContainer.insert(layoutTitle);this.contentElement.insert(layoutElementContainer);},selectLayout:function(layout,element){if(layout.layoutId==this.selectedLayoutId)return;element.addClassName('selected');if(this.selectedLayoutElement)this.selectedLayoutElement.removeClassName('selected');this.selectedLayoutElement=element;this.selectedLayoutId=layout.layoutId;Personalize.trigger('changelayout',layout.layoutId,Personalize.activeStep.currentPanel.panelId);}};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'});var zIndex=(this.overlay.editable==1)?(++Personalize.borderZIndex):(++Personalize.overlayZIndex+parseFloat(this.overlay.z));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:zIndex});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'});}},editHandler:function(ev){var checkbox=Event.element(ev);if(!checkbox.checked){this.overlay.switchedOn=0;this.remove();}else{this.overlay.switchedOn=1;this.render($('personalizeImagePreviewPane'));}},getBorderImageUrl:function(){var width=Personalize.roundForRendering(Personalize.resolutionConvert(parseFloat(this.overlay.width),144,this.resolution))-1;var height=Personalize.roundForRendering(Personalize.resolutionConvert(parseFloat(this.overlay.height),144,this.resolution))-1;var cropY=0;var cropHeight=15;var cropX=15;var cropWidth=100;var borderImageUrl=Personalize.hosts.images+'image/overlay/'+this.overlay.imageId+'/resolution/'+this.resolution+'/cropY/'+cropY+'/cropHeight/'+cropHeight+'/cropX/'+cropX+'/cropWidth/'+cropWidth+'/width/'+width+'/height/'+height+'.png';return borderImageUrl;},remove:function(){this.domElement.remove();}};var PersonalizeBorderTray=function(){this.domElement=null;this.overlay=null;this.checked=null;};PersonalizeBorderTray.prototype={render:function(overlay){$('personalizeStep_designOptions').update('');this.overlay=overlay;this.domElement=new Element('div',{'id':'borderTray'});this.domElement.insert(new Element('div').update('<span style="font-weight:bold">Borders</span>'));this.checkBox=new Element('input',{'type':'checkbox','id':'borderCheck','class':'clickable'});var newDiv=new Element('div',{'style':'float: left;'});newDiv.insert(this.checkBox);if(overlay.overlay.switchedOn==1){this.checkBox.checked=true;}
this.checkBox.observe('click',overlay.editHandler.bindAsEventListener(overlay));newDiv.insert(new Element('span').update('Turn Borders On'));this.domElement.insert(newDiv);$('personalizeStep_designOptions').insert(this.domElement);},remove:function(){if(this.domElement){this.domElement.remove();this.domElement=null;}}};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'});if(TP.BrowserDetect.browser=='Firefox'){button.observe('click',this.dialog.suspenseHidePopup.bind(this.dialog));}else{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'});}else{if(this.dialog.temporaryHideFlag){this.dialog.resumeHidePopup();return;}}
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(){if(TP.BrowserDetect.browser=='Firefox'){this.dialog.suspenseHidePopup();}else{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 most designs to any color on our Custom Color Palette for an <a href="/about-us/terms-of-service.htm#a" target="_blank">additional fee</a>. If you have questions about whether a specific design can be changed to a custom color, please <a href="/contact-us/" target="_blank">contact us</a>.<br /><br />We strongly recommend ordering physical samples, which will include the Custom Color Options Card that corresponds to the paper type you\'ve selected. Colors appear differently on your computer monitor or when printed at home, so our Custom Color Options Cards are the best way to see custom colors as they would appear on your invitations.<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 PersonalizeBottomTab=function(tabDomId,tabName,options){this.tabDomId=tabDomId;this.tabName=tabName;this.options=options;this.tabDom=null;this.className='';if(typeof this.options.className!=='undefined'){this.className=this.options.className;}
this.state=false;if(typeof this.options.active!=='undefined'){this.state=this.options.active;}};PersonalizeBottomTab.prototype={render:function(){this.tabDom=new Element('div',{id:this.tabDomId,'class':this.options.className}).update(this.tabName);this.tabDom.observe('click',this.parent.activateTab.bind(this.parent,this.tabDomId));return this.tabDom;},activate:function(){this.state=true;this.tabDom.addClassName('activeTab');this.tabDom.removeClassName('bottomTab');var contentEl=$(this.contentElementDomId);contentEl.show();},deactivate:function(){this.state=true;this.tabDom.removeClassName('activeTab');this.tabDom.addClassName('bottomTab');var contentEl=$(this.contentElementDomId);contentEl.hide();}};var PersonalizeTabController=function(tabControllerDomId){this.tabContainerDomId=tabControllerDomId;this.currentTabId=null;this.items=[];this.tabControllerDom=$(this.tabContainerDomId);};PersonalizeTabController.prototype={addTab:function(tab){for(var i=0;i<this.items.length;i++){var savedTab=this.items[i];if(savedTab.tabDomId==tab.tabDomId){return;}}
tab.parent=this;this.items.push(tab);},removeTab:function(tabDomId){var tab=$(this.items[tabDomId]);if(tab){tab.remove();}},render:function(){if(this.items.length){this.tabControllerDom.show();}else{this.tabControllerDom.hide();}
this.tabControllerDom.update('');var toBeActivatedTabDomId=null;for(var i=0;i<this.items.length;i++){var tab=this.items[i];if(tab.tabDom)continue;this.tabControllerDom.insert(tab.render());if(tab.state){toBeActivatedTabDomId=tab.tabDom.id;}}
if(toBeActivatedTabDomId){this.activateTab(toBeActivatedTabDomId);}},activateTab:function(tabDomId){for(var i=0;i<this.items.length;i++){var tab=this.items[i];if(tab.tabDom.id==tabDomId){tab.activate();}else{tab.deactivate();}}}};var DoodleTray=function(){this.containerDomId=null;this.container=null;this.imageSpace=null;this.visible=false;this.showDropAreaElement=null;};DoodleTray.prototype={render:function(containerId){var currentColorId=Personalize.product.color.id;this.containerDomId=containerId;this.container=$(this.containerDomId);this.container.update('');var trayHeader=new Element('div',{'class':'trayHeader'});var headerText=new Element('div',{'class':'headerDescription'}).update('Drag these onto areas of your card to make it uniquely you');this.showDropAreaElement=new Element('div',{'class':'headerShowDropArea clickable',id:'showHideDropAreas'}).update('Show drop areas');this.showDropAreaElement.observe('click',this.showDropAreas.bind(this));trayHeader.insert(headerText);trayHeader.insert(this.showDropAreaElement);trayHeader.insert(new Element('div',{style:'clear: both;'}));this.container.insert(trayHeader);var mainTrayContainer=new Element('div',{style:'padding-left: 3px; padding-right: 3px; margin-top: 15px;'});var doodleImagesArea=new Element('div',{'class':'doodle-images-area'});this.imageSpace=new DoodleTrayImageSpace('doodleTraySpace');this.imageSpace.parent=this;this.imageSpace.parentWidth=508;var productPanel=Personalize.product.panels[personalizePersonalize.currentPanel.panelId];for(var availableDoodleId in productPanel.availableDoodles){var associatedDoodle=productPanel.availableDoodles[availableDoodleId];if(associatedDoodle.productPanelColorId==currentColorId){var trayDoodle=new TrayDoodle(associatedDoodle);this.imageSpace.addItem(trayDoodle);}}
doodleImagesArea.insert(this.imageSpace.render());var isDropArea=false;for(var dropAreaId in productPanel.dropAreas){isDropArea=true;break;}
if(isDropArea){this.showDropAreaElement.show();}else{this.showDropAreaElement.hide();}
this.trayScrollLeft=new Element('div',{'class':'sprite-btn-scroll-left clickable',style:'float: left; margin-top: 30px; margin-right: 5px;'});this.trayScrollLeft.observe('mouseover',this.scrollLeft.bind(this));this.trayScrollLeft.observe('mouseout',this.scrollLeftStop.bind(this));this.trayScrollRight=new Element('div',{'class':'sprite-btn-scroll-right clickable',style:'float: left; margin-top: 30px; margin-left: 5px;'});this.trayScrollRight.observe('mouseover',this.scrollRight.bind(this));this.trayScrollRight.observe('mouseout',this.scrollRightStop.bind(this));mainTrayContainer.insert(this.trayScrollLeft);mainTrayContainer.insert(doodleImagesArea);mainTrayContainer.insert(this.trayScrollRight);mainTrayContainer.insert(new Element('div',{style:'clear: both;'}));var trayFooter=new Element('div',{'class':'trayFooter'});var deleteAllDoodlesLink=new Element('div',{id:'deleteAllDoodles','class':'clickable',style:'display:none;'}).update('Remove all Design Accents');deleteAllDoodlesLink.observe('click',this.deleteAllDoodles.bindAsEventListener(this));trayFooter.insert(deleteAllDoodlesLink);this.container.insert(new Element('div',{style:'clear: both;'}));this.container.insert(mainTrayContainer);this.container.insert(trayFooter);this.imageSpace.scrollLeftRightCheck();},getTrayDoodle:function(associatedDoodleId){return this.imageSpace.getTrayDoodle(associatedDoodleId);},getDefaultTrayDoodle:function(doodleId){return this.imageSpace.getDefaultTrayDoodle(doodleId);},getTrayDoodleByImageId:function(doodleImageId){return this.imageSpace.getTrayDoodleByImageId(doodleImageId);},showDropAreas:function(){this.visible=!this.visible;if(this.visible){personalizePersonalize.showDropAreas();if(this.showDropAreaElement){this.showDropAreaElement.update('Hide drop areas');}}else{personalizePersonalize.hideDropAreas();if(this.showDropAreaElement){this.showDropAreaElement.update('Show drop areas');}}},setScrollLeftAvailable:function(){if(this.trayScrollLeft.hasClassName('sprite-btn-left-off-arrow')){this.trayScrollLeft.removeClassName('sprite-btn-left-off-arrow');this.trayScrollLeft.addClassName('sprite-btn-scroll-left');}},setScrollRightAvailable:function(){if(this.trayScrollRight.hasClassName('sprite-btn-right-arrow-off')){this.trayScrollRight.removeClassName('sprite-btn-right-arrow-off');this.trayScrollRight.addClassName('sprite-btn-scroll-right');}},scrollLeftFinish:function(){if(this.trayScrollLeft.hasClassName('sprite-btn-scroll-left')){this.trayScrollLeft.removeClassName('sprite-btn-scroll-left');this.trayScrollLeft.addClassName('sprite-btn-left-off-arrow');}},scrollRightFinish:function(){if(this.trayScrollRight.hasClassName('sprite-btn-scroll-right')){this.trayScrollRight.removeClassName('sprite-btn-scroll-right');this.trayScrollRight.addClassName('sprite-btn-right-arrow-off');}},scrollLeft:function(){if(!this.imageSpace){return;}
this.imageSpace.scrollLeft();},scrollRight:function(){if(!this.imageSpace){return;}
this.imageSpace.scrollRight();},scrollRightStop:function(){if(!this.imageSpace){return;}
this.imageSpace.scrollRightStop();},scrollLeftStop:function(){if(!this.imageSpace){return;}
this.imageSpace.scrollLeftStop();},deleteAllDoodles:function(ev){if(personalizePersonalize.dropAreas.length>0){for(var i=0;i<personalizePersonalize.dropAreas.length;i++){var dropareaDoodles=personalizePersonalize.dropAreas[i].doodles;while(dropareaDoodles.length>0){dropareaDoodles[0].remove();}
personalizePersonalize.dropAreas[i].hide();personalizePersonalize.dropAreas[i].removeBackgroundDropHere();}}else{var doodles=personalizePersonalize.globalDropArea.doodles;while(doodles.length>0){doodles[0].remove();}}
$('deleteAllDoodles').hide();Event.stop(ev);}};var MonogramTray=function(){};MonogramTray.prototype=TP.extendObject(new DoodleTray(),{render:function(containerId){var currentColorId=Personalize.product.color.id;this.containerDomId=containerId;this.container=$(this.containerDomId);this.container.update('');var mainTrayContainer=new Element('div',{style:'padding-left: 3px; padding-right: 3px; margin-top: 15px;'});var doodleImagesArea=new Element('div',{'class':'monogram-images-area'});var instruction=new Element('div',{style:'margin-left:10px;'}).update('Click on any motif to add it to its designated spot on your design.');this.container.insert(instruction);this.imageSpace=new MonogramTrayImageSpace('doodleTraySpace');this.imageSpace.parent=this;this.imageSpace.parentWidth=299;var keys=Object.keys(Personalize.product.doodles);for(var i=1;i<=keys.length;i++){var productPanel=Personalize.product.panels[personalizePersonalize.currentPanel.panelId];for(var availableDoodleId in productPanel.availableDoodles){var associatedDoodle=productPanel.availableDoodles[availableDoodleId];var doodleId=associatedDoodle.doodleColorImage.doodleId;var productDoodle=Personalize.product.doodles[doodleId];if(productDoodle.type==0){continue;}
if(associatedDoodle.productPanelColorId==currentColorId){if(productDoodle.sort==i){var trayDoodle=TP.extendObject(new TrayDoodle(associatedDoodle),new TrayMonogram());this.imageSpace.addItem(trayDoodle);}}}}
doodleImagesArea.insert(this.imageSpace.render());this.trayScrollLeft=new Element('div',{'class':'sprite-btn-scroll-left clickable',style:'float: left; margin-top: 30px; margin-right: 5px;'});this.trayScrollLeft.observe('mouseover',this.scrollLeft.bind(this));this.trayScrollLeft.observe('mouseout',this.scrollLeftStop.bind(this));this.trayScrollRight=new Element('div',{'class':'sprite-btn-scroll-right clickable',style:'float: left; margin-top: 30px; margin-left: 5px;'});this.trayScrollRight.observe('mouseover',this.scrollRight.bind(this));this.trayScrollRight.observe('mouseout',this.scrollRightStop.bind(this));mainTrayContainer.insert(this.trayScrollLeft);mainTrayContainer.insert(doodleImagesArea);mainTrayContainer.insert(this.trayScrollRight);mainTrayContainer.insert(new Element('div',{style:'clear: both;'}));var trayFooter=new Element('div',{'class':'trayFooter'});this.container.insert(new Element('div',{style:'clear: both;'}));this.container.insert(mainTrayContainer);this.container.insert(trayFooter);this.imageSpace.scrollLeftRightCheck();}});var DoodleTrayImageSpace=function(spaceDomId){this.domId=spaceDomId;this.unitWidth=100;this.unitHeight=100;this.totalDoodlesWidth=0;this.trayDoodles=[];this.scrollDuration=0.5;this.scrollRightFlag=false;this.scrollLeftFlag=false;this.maxRightTo=0;};DoodleTrayImageSpace.prototype={addItem:function(trayDoodle){if(trayDoodle){this.trayDoodles.push(trayDoodle);}},scrollLeft:function(){this.scrollLeftFlag=true;var parent=this.containerDom.up();var parentOffset=parent.positionedOffset();var offSet=Personalize.pxToNumber(this.containerDom.style.left);if(!offSet){offSet=0;}
if(offSet>=0){return;}
this.parent.setScrollRightAvailable();var moveLeftAmount=-offSet;var numberOfItemsToScroll=Math.abs(offSet)/this.unitWidth;var duration=numberOfItemsToScroll*this.scrollDuration;this.scrollLeftEffect=new Effect.Move(this.domId,{x:moveLeftAmount,duration:duration,mode:'relative',transition:Effect.Transitions.linear,beforeUpdate:this.scrollLeftUpdate.bind(this),afterFinish:this.scrollLeftFinish.bind(this)});},scrollRight:function(){this.scrollRightFlag=true;var parent=this.containerDom.up();var parentOffset=parent.positionedOffset();var offSet=Personalize.pxToNumber(this.containerDom.style.left);var containerWidth=Personalize.pxToNumber(this.containerDom.style.width);if(!offSet){offSet=0;}
if(!this.maxRightTo){this.maxRightTo=-(containerWidth-parent.getWidth());}
if(offSet<=this.maxRightTo){return;}
this.parent.setScrollLeftAvailable();var averageUnitWidth=parent.getWidth()/this.trayDoodles.length;var numberOfItemsToScroll=Math.ceil((parent.getWidth()-Math.abs(offSet))/averageUnitWidth);var duration=numberOfItemsToScroll*this.scrollDuration;this.scrollRightEffect=new Effect.Move(this.domId,{x:this.maxRightTo-offSet,duration:duration,mode:'relative',transition:Effect.Transitions.linear,beforeUpdate:this.scrollRightUpdate.bind(this),afterFinish:this.scrollRightFinish.bind(this)});},scrollLeftRightCheck:function(){var parent=this.containerDom.up();var parentOffset=parent.positionedOffset();var offSet=Personalize.pxToNumber(this.containerDom.style.left);var containerWidth=Personalize.pxToNumber(this.containerDom.style.width);if(!offSet){offSet=0;}
if(offSet>=0){this.parent.scrollLeftFinish();}
if(containerWidth<this.parentWidth){this.parent.scrollRightFinish();}},scrollRightFinish:function(){this.parent.scrollRightFinish();},scrollLeftFinish:function(){this.parent.scrollLeftFinish();},scrollRightStop:function(){this.scrollRightFlag=false;},scrollLeftStop:function(){this.scrollLeftFlag=false;},scrollRightUpdate:function(){if(!this.scrollRightFlag){this.scrollRightEffect.cancel();}},scrollLeftUpdate:function(){if(!this.scrollLeftFlag){this.scrollLeftEffect.cancel();}},getTrayDoodle:function(associatedDoodleId){for(var i=0;i<this.trayDoodles.length;i++){var trayDoodle=this.trayDoodles[i];if(trayDoodle.associatedDoodle.id==associatedDoodleId){return trayDoodle;}}
return null;},getDefaultTrayDoodle:function(doodleId){for(var i=0;i<this.trayDoodles.length;i++){var trayDoodle=this.trayDoodles[i];if(trayDoodle.associatedDoodle.doodleColorImage.doodleId==doodleId&&trayDoodle.associatedDoodle['default']==1){return trayDoodle;}}
return null;},getTrayDoodleByImageId:function(doodleImageId){for(var i=0;i<this.trayDoodles.length;i++){var trayDoodle=this.trayDoodles[i];if(trayDoodle.associatedDoodle.doodleColorImage.imageId==doodleImageId){return trayDoodle;}}
return null;},render:function(){var itemContainer=new Element('div',{id:this.domId,style:'position: relative;'});itemContainer.setStyle({width:this.unitWidth+'px',height:this.unitHeight+'px'});for(var i=0;i<this.trayDoodles.length;i++){var trayDoodle=this.trayDoodles[i];var originalDoodleImage=trayDoodle.productDoodle.colors[trayDoodle.associatedDoodle.doodleColorId].image;var doodleAspectRatio=originalDoodleImage.width/originalDoodleImage.height;var adjustedWidth=trayDoodle.height*doodleAspectRatio+10;this.totalDoodlesWidth+=adjustedWidth;var trayItem=new Element('div',{style:'width: '+adjustedWidth+'px; height:'+this.unitHeight+'px; float: left;'});trayItem.insert(trayDoodle.render());itemContainer.insert(trayItem);}
itemContainer.setStyle({width:(this.totalDoodlesWidth)+'px',height:this.unitHeight+'px'});this.containerDom=itemContainer;return this.containerDom;}};var MonogramTrayImageSpace=function(spaceDomId){this.domId=spaceDomId;this.trayDoodles=[];};MonogramTrayImageSpace.prototype=TP.extendObject(new DoodleTrayImageSpace(),{noMonogram:function(){for(var dropAreaId in personalizePersonalize.dropAreas){var dropArea=personalizePersonalize.dropAreas[dropAreaId];if(typeof dropArea.doodles!=='undefined'){for(var i=0;i<dropArea.doodles.length;i++){var panelDoodle=dropArea.doodles[i];panelDoodle.remove();dropArea.visible=true;dropArea.hide();}}}
$('noMonogramImage').addClassName('doodleSelected');},render:function(){var itemContainer=new Element('div',{id:this.domId,style:'position: relative;'});itemContainer.setStyle({width:this.unitWidth+'px',height:this.unitHeight+'px'});var trayItem=new Element('div',{style:'width: 94px; height:'+this.unitHeight+'px; float: left;mrgin-left: 6px;'});var image=new Element('img',{'class':'clickable'});var imageContainer=new Element('div',{id:'noMonogramImage','class':'doodleSelected',style:'width: 90px; height: 90px;'});image.src=Personalize.hosts.textv2Cache+'personalize/textbox/restrictSize/0/width/90/height/90/fontName/NeutraText/fontSize/9/fontColor/3EAFDD/verticalAlignment/center/horizontalAlignment/center/text/'+encodeURIComponent(encodeURIComponent(JSON.stringify('no\nmotif')))+'.png';image.observe('click',this.noMonogram.bind(this));imageContainer.insert(image);trayItem.insert(imageContainer);itemContainer.insert(trayItem);for(var i=0;i<this.trayDoodles.length;i++){var trayItem=new Element('div',{style:'width: '+this.unitWidth+'px; height:'+this.unitHeight+'px; float: left;'});var trayDoodle=this.trayDoodles[i];trayItem.insert(trayDoodle.render());itemContainer.insert(trayItem);}
itemContainer.setStyle({width:(this.unitWidth*(this.trayDoodles.length+1))+'px',height:this.unitHeight+'px'});this.containerDom=itemContainer;return this.containerDom;},scrollRight:function(){this.scrollRightFlag=true;var parent=this.containerDom.up();var parentOffset=parent.positionedOffset();var offSet=Personalize.pxToNumber(this.containerDom.style.left);var containerWidth=Personalize.pxToNumber(this.containerDom.style.width);if(!offSet){offSet=0;}
if(!this.maxRightTo){this.maxRightTo=-(containerWidth-parent.getWidth());}
if(offSet<=this.maxRightTo){return;}
this.parent.setScrollLeftAvailable();var numberOfItemsToScroll=(this.trayDoodles.length+1)-((Math.abs(offSet)+parent.getWidth())/this.unitWidth);var duration=numberOfItemsToScroll*this.scrollDuration;this.scrollRightEffect=new Effect.Move(this.domId,{x:this.maxRightTo-offSet,duration:duration,mode:'relative',transition:Effect.Transitions.linear,beforeUpdate:this.scrollRightUpdate.bind(this),afterFinish:this.scrollRightFinish.bind(this)});}});var TrayDoodle=function(associatedDoodle){this.associatedDoodle=associatedDoodle;this.elementDom=null;this.selected=false;this.usageCount=0;this.width=Personalize.defaultDoodleSize;this.height=Personalize.defaultDoodleSize;this.productDoodle=Personalize.product.doodles[associatedDoodle.doodleColorImage.doodleId];this.panel=personalizePersonalize.currentPanel;};TrayDoodle.prototype={render:function(){this.elementDom=new Element('div',{style:'width: 90px; height: 90px; text-align: center;'});var image=new Element('img',{'class':'trayDoodleImageDraggable',src:this.getUrl(),style:'cursor: move; position: relative; top: 10px;'});image.identify();image.trayDoodle=this;new SuperDraggable(image,{ghosting:true,revert:true,scroll:window,reverteffect:Personalize.effects.reverts.instantRevert,change:this.showDropAreas.bind(this),onStart:this.makeSelected.bind(this),onEnd:this.dragEnd.bind(this)});this.elementDom.insert(image);return this.elementDom;},dragEnd:function(){if(!this.usageCount){this.makeDeselected(this);}
this.hideDropAreas(this);},showDropAreas:function(){personalizePersonalize.showDropAreas();},hideDropAreas:function(){personalizePersonalize.hideDropAreas();},getUrl:function(){return Personalize.hosts.images+'image/doodle/'+this.associatedDoodle.doodleColorImage.imageId+'/width/'+this.width+'/height/'+this.height+'.png';},makeSelected:function(){this.selected=true;try{this.elementDom.addClassName('doodleSelected');if($('noMonogramImage')){$('noMonogramImage').removeClassName('doodleSelected');}}catch(e){}},makeDeselected:function(){this.selected=false;this.elementDom.removeClassName('doodleSelected');},unregister:function(){this.usageCount--;if(!this.usageCount){this.makeDeselected();}},register:function(){this.usageCount++;if(this.usageCount){this.makeSelected();}},toggleSelected:function(){if(!this.selected){this.elementDom.addClassName('doodleSelected');}else{this.elementDom.removeClassName('doodleSelected');}
this.selected=!this.selected;},setUsageCount:function(usageCount){this.usageCount=usageCount;}};var TrayMonogram=function(){};TrayMonogram.prototype={render:function(){this.elementDom=new Element('div',{style:'width: 90px; height: 90px; text-align: center;'});var image=new Element('img',{'class':'clickable trayDoodleImageDraggable',src:this.getUrl(),style:'position: relative; top: 10px;'});image.identify();image.trayDoodle=this;image.observe('click',this.monogramSelect.bind(this));this.elementDom.insert(image);return this.elementDom;},monogramSelect:function(event){if(this.selected){return;}
for(var dropAreaIndex=0;dropAreaIndex<personalizePersonalize.dropAreas.length;dropAreaIndex++){var dropArea=personalizePersonalize.dropAreas[dropAreaIndex];for(var i=0;i<dropArea.doodles.length;i++){var panelDoodle=dropArea.doodles[i];panelDoodle.remove();}
dropArea.addDoodle(this,0,0);dropArea.visible=true;dropArea.hide();break;}},getUrl:function(){if(this.productDoodle.type==2){return Personalize.hosts.images+'image/doodle/'+this.associatedDoodle.doodleColorImage.imageId+'/width/'+this.width+'/height/'+this.height+'/textoptions/default/doodlecolor/'+this.associatedDoodle.doodleColorId+'.png';}
return Personalize.hosts.images+'image/doodle/'+this.associatedDoodle.doodleColorImage.imageId+'/width/'+this.width+'/height/'+this.height+'.png';}};var personalizeDoodle=function(doodle,panel){this.doodle=doodle;this.panel=panel;this.trayDoodle=doodle.trayDoodle;this.productDoodle=this.trayDoodle.productDoodle;this.associatedDoodle=this.trayDoodle.associatedDoodle;this.doodleHandle=null;this.doodleElement=null;this.available=true;this.rotateAmount=90;this.loadedVar=false;this.resolution=null;this.rotateDegree=this.doodle.rotateDegree;this.isMirror=this.doodle.mirror;this.currentLayout=null;this.trayDoodle.register();this.options={resizable:(typeof this.productDoodle.options[2]!=='undefined'&&parseInt(this.productDoodle.options[2].value))?1:0,movable:(typeof this.productDoodle.options[3]!=='undefined'&&parseInt(this.productDoodle.options[3].value))?1:0,mirror:(typeof this.productDoodle.options[5]!=='undefined'&&parseInt(this.productDoodle.options[5].value))?1:0,rotation:(typeof this.productDoodle.options[1]!=='undefined'&&parseInt(this.productDoodle.options[1].value))?1:0,textOption:(typeof this.productDoodle.options[4]!=='undefined'&&parseInt(this.productDoodle.options[4].value))?1:0}
this.productColors={};this.productColors[Personalize.product.color.id]=this.associatedDoodle;this.isMonogram=false;if(this.productDoodle.type==2){this.isMonogram=true;}
this.isMotif=false;if(this.productDoodle.type==1){this.isMotif=true;}
this.isDoodle=false;if(this.productDoodle.type==0){this.isDoodle=true;}
this.doodle.textboxes={};this.doodle.designBoxTextboxes={};this.doodle.textOptions={doodleId:this.productDoodle.id,designboxes:{},textboxes:{}}
if(this.isMonogram){var doodleTextboxCount=0;var designBoxTextboxCount=0;if(typeof personalizePersonalize.textOptions!=='undefined'){this.restoreMonogramText();}
for(var textboxId in this.productDoodle.textboxes){var textbox=this.productDoodle.textboxes[textboxId];for(var fontId in textbox.fonts){var font=textbox.fonts[fontId];if(parseFloat(font['default'])==1){break;}}
for(var fontSizeId in textbox.fontSizes){var fontSize=textbox.fontSizes[fontSizeId];if(parseFloat(fontSize['default'])==1){break;}}
var doodleColorFontColor=textbox.doodleColorFontColors[this.associatedDoodle.doodleColorId];if(typeof textbox.productDoodleColorFontColors[Personalize.product.color.colorId]!=='undefined'){doodleColorFontColor=textbox.productDoodleColorFontColors[Personalize.product.color.colorId][this.associatedDoodle.doodleColorId];}
for(var fontColorId in doodleColorFontColor){var fontColor=doodleColorFontColor[fontColorId];if(parseFloat(fontColor['default'])==1){break;}}
textbox.fontColorId=fontColorId;var content=textbox.content.length?textbox.content.substr(0,1):'';var cookieString=decodeURIComponent(Personalize.getLocalVariable('templateCodeValues'));if(typeof personalizePersonalize.textOptions!=='undefined'){if(typeof textbox.designBox!=='undefined'){if(this.savedDesignBoxTextboxes[designBoxTextboxCount]){content=this.savedDesignBoxTextboxes[designBoxTextboxCount];}}else{if(this.savedDoodleTextboxes[doodleTextboxCount]){content=this.savedDoodleTextboxes[doodleTextboxCount];}}}else if(cookieString){var cookieVarContents=cookieString.evalJSON();for(var variableId in textbox.variables){var variableName=textbox.variables[variableId];var cookieVariable=cookieVarContents[variableName];if(cookieVariable){var cookieName=cookieVariable.name;if(cookieName.length){content=cookieName.substr(0,1);break;}}}}
if(typeof textbox.designBox!=='undefined'){if(!this.doodle.textOptions.designboxes[textbox.designBox.id]){var personalizeDesignBox=TP.extendObject(new DoodleDesignBox(),textbox.designBox);personalizeDesignBox.id=null;personalizeDesignBox.doodleId=this.productDoodle.id;personalizeDesignBox.designBoxId=textbox.designBox.id;personalizeDesignBox.textboxes={};this.doodle.textOptions.designboxes[textbox.designBox.id]=personalizeDesignBox;}
var personalizationTextbox=TP.extendObject(new DoodleDesignBoxTextbox(),textbox);personalizationTextbox.id=null;personalizationTextbox.designBoxId=textbox.designBox.id;personalizationTextbox.textboxId=textbox.id;personalizationTextbox.fontId=fontId;personalizationTextbox.fontColorId=fontColorId;personalizationTextbox.fontSize=fontSizeId;personalizationTextbox.content=content;this.doodle.textOptions.designboxes[textbox.designBox.id].textboxes[textboxId]=personalizationTextbox;++designBoxTextboxCount;}else{var personalizationTextbox=TP.extendObject(new DoodleTextbox(),textbox);personalizationTextbox.id=null;personalizationTextbox.doodleId=this.productDoodle.id;personalizationTextbox.textboxId=textbox.id;personalizationTextbox.fontId=fontId;personalizationTextbox.fontColorId=fontColorId;personalizationTextbox.fontSize=fontSizeId;personalizationTextbox.content=content;this.doodle.textOptions.textboxes[textboxId]=personalizationTextbox;++doodleTextboxCount;}}}
this.validate();};personalizeDoodle.prototype={render:function(resolution,handlesContainer){this.resolution=resolution;this.doodleElement=new Element('img',{'class':'panelDoodle','style':'margin:0; padding:0; border: 0;'});this.doodleHandle=new Element('div',{'class':'clickable'});this.doodleHandle.identify();this.doodleElement.setStyle({position:'relative',zIndex:parseFloat(Personalize.doodleZIndex++)});try{this.doodle.z=parseFloat(Personalize.doodleZIndex);this.doodleHandle.setStyle({position:'absolute',top:Personalize.resolutionConvert(this.doodle.y,144,this.resolution)+'px',left:Personalize.resolutionConvert(this.doodle.x,144,this.resolution)+'px',zIndex:12000});}catch(e){}
this.doodleElement.onload=this.loaded.bind(this);this.doodleElement.src=this.getUrl();this.aspectRatio=this.doodle.width/this.doodle.height;if(this.isDoodle){}
this.doodleHandle.observe('click',this.startEditing.bind(this));this.doodleHandle.insert(this.doodleElement);if($('deleteAllDoodles')){$('deleteAllDoodles').show();}
return this.doodleHandle;},getUrl:function(){var rotation='';var mirror='';var textoptions='';var resolution='';if(this.isMonogram){textoptions='/textoptions/'+this.getTextOptionsJsonString();resolution='/resolution/'+this.resolution;}else{if(this.isMirror){mirror='/effects/flipVertical';rotation='/rotate/'+(180-this.rotateDegree);}else{rotation='/rotate/'+this.rotateDegree;}}
if(this.doodle.width&&this.doodle.height){return Personalize.hosts.images+'image/doodle/'+this.associatedDoodle.doodleColorImage.imageId+resolution+'/width/'+Personalize.resolutionConvert(this.doodle.width,144,this.resolution)+'/height/'+Personalize.resolutionConvert(this.doodle.height,144,this.resolution)+rotation+mirror+textoptions+'.png';}else{return Personalize.hosts.images+'image/doodle/'+this.associatedDoodle.doodleColorImage.imageId+'/resolution/'+this.resolution+rotation+mirror+'.png';}},getTextOptionsJsonString:function(){if(!this.isMonogram){return'';}
var textOptions={doodleId:this.productDoodle.id,designboxes:{},textboxes:{}}
for(var textboxId in this.doodle.textOptions.textboxes){var textbox=this.doodle.textOptions.textboxes[textboxId];textOptions.textboxes[textboxId]={textboxId:textbox.textboxId,fontId:textbox.fontId,fontColorId:textbox.fontColorId,fontSize:textbox.fontSize,content:JSON.stringify(textbox.content)};}
for(var designBoxId in this.doodle.textOptions.designboxes){var designBox=this.doodle.textOptions.designboxes[designBoxId];textOptions.designboxes[designBoxId]={textboxes:{}};for(var textboxId in designBox.textboxes){var textbox=designBox.textboxes[textboxId];textOptions.designboxes[designBoxId].textboxes[textboxId]={textboxId:textbox.textboxId,fontId:textbox.fontId,fontColorId:textbox.fontColorId,fontSize:textbox.fontSize,content:JSON.stringify(textbox.content)};}}
return encodeURIComponent(encodeURIComponent(Object.toJSON(textOptions)));},updateDoodle:function(associatedDoodle){this.associatedDoodle=associatedDoodle;this.productColors[Personalize.product.color.id]=this.associatedDoodle;if(this.isMonogram){this.updateMonogramFontColors();}
this.newDoodleImg=new Image();this.newDoodleImg.onload=this.swapImage.bind(this);this.newDoodleImg.src=this.getUrl();},changeColor:function(){var associatedDoodle=this.productColors[Personalize.product.color.id];var trayDoodle=null;if(associatedDoodle){trayDoodle=personalizePersonalize.doodleTray.getTrayDoodle(associatedDoodle.id);}else{trayDoodle=personalizePersonalize.doodleTray.getTrayDoodleByImageId(this.associatedDoodle.doodleColorImage.imageId);if(!trayDoodle){trayDoodle=personalizePersonalize.doodleTray.getDefaultTrayDoodle(this.associatedDoodle.doodleColorImage.doodleId);}}
if(trayDoodle){this.trayDoodle=trayDoodle;this.setAvailable(true);this.updateDoodle(trayDoodle.associatedDoodle);this.validate();this.trayDoodle.register();}else{this.setAvailable(false);this.trayDoodle.unregister();}},updateMonogramFontColors:function(){for(var textboxId in this.doodle.textOptions.textboxes){var textbox=this.doodle.textOptions.textboxes[textboxId];var doodleColorFontColor=textbox.doodleColorFontColors[this.associatedDoodle.doodleColorId];if(typeof textbox.productDoodleColorFontColors[Personalize.product.color.colorId]!=='undefined'){doodleColorFontColor=textbox.productDoodleColorFontColors[Personalize.product.color.colorId][this.associatedDoodle.doodleColorId];}
for(var fontColorId in doodleColorFontColor){var fontColor=doodleColorFontColor[fontColorId];if(parseFloat(fontColor['default'])==1){break;}}
textbox.fontColorId=fontColorId;}
for(var designboxId in this.doodle.textOptions.designboxes){for(textboxId in this.doodle.textOptions.designboxes[designboxId].textboxes){var textbox=this.doodle.textOptions.designboxes[designboxId].textboxes[textboxId];var doodleColorFontColor=textbox.doodleColorFontColors[this.associatedDoodle.doodleColorId];if(typeof textbox.productDoodleColorFontColors[Personalize.product.color.colorId]!=='undefined'){doodleColorFontColor=textbox.productDoodleColorFontColors[Personalize.product.color.colorId][this.associatedDoodle.doodleColorId];}
for(var fontColorId in doodleColorFontColor){var fontColor=doodleColorFontColor[fontColorId];if(parseFloat(fontColor['default'])==1){break;}}
textbox.fontColorId=fontColorId;}}},loaded:function(){if(this.loadedVar)return;this.loadedVar=true;if(!this.doodle.width||!this.doodle.height){this.doodle.baseWidth=this.doodleElement.width;this.doodle.baseHeight=this.doodleElement.height;this.doodle.width=Personalize.resolutionConvert(this.doodleElement.width,this.resolution,144);this.doodle.height=Personalize.resolutionConvert(this.doodleElement.height,this.resolution,144);}
this.aspectRatio=this.doodleElement.width/this.doodleElement.height;this.doodleHandle.setStyle({width:this.doodleElement.width+'px',height:this.doodleElement.height+'px'});if(this.isMonogram||this.isMotif){var top=parseInt(((this.doodle.dropArea.height-this.doodleElement.height)/2));var left=parseInt(((this.doodle.dropArea.width-this.doodleElement.width)/2));this.doodleHandle.setStyle({top:top+'px',left:left+'px'});this.doodle.y=Personalize.resolutionConvert(top,this.resolution,144);this.doodle.x=Personalize.resolutionConvert(left,this.resolution,144);}},startEditing:function(ev){document.body.appendChild(this.renderEditor());if(ev&&(typeof ev.stop=="function")){ev.stop();}
this.editorLoseFocusHandle=this.stopEditing.bindAsEventListener(this)
$(document).observe('click',this.editorLoseFocusHandle);},stopEditing:function(ev){try{var ancestors=ev.element().ancestors();for(var i=0;i<ancestors.length;i++){var ancestor=ancestors[i];if(ancestor==this.editor||ancestor==this.target){ev.stop();return;}}
$(document).stopObserving('click',this.editorLoseFocusHandle);this.editor.remove();}catch(e){}
if($('showHideDropAreas')!=ev.element()){this.doodle.dropArea.hide();}},remove:function(){try{if(this.doodleElement){this.doodleElement.remove();}
if(this.doodleHandle){this.doodleHandle.remove();}
if(this.editor){this.editor.remove();}}catch(e){}
this.doodle.dropArea.removeDoodle(this);},rotate:function(){this.rotateDegree=(this.rotateDegree+this.rotateAmount)%360;this.doodle.rotateDegree=this.rotateDegree;this.newDoodleImg=new Image();this.newDoodleImg.onload=this.swapImage.bind(this);this.newDoodleImg.src=this.getUrl();},mirrorCurrentImage:function(){this.isMirror=!this.isMirror;this.doodle.mirror=this.isMirror?1:0;this.newDoodleImg=new Image();this.newDoodleImg.onload=this.swapImage.bind(this);this.newDoodleImg.src=this.getUrl();},renderEditor:function(){if(this.isDoodle){this.doodle.dropArea.show();}
try{if(typeof this.editor!=='undefined'&&this.editor){this.editor.remove();}}catch(e){}
this.editor=new Element('div',{'class':'doodleEditor moveable',style:'background: url('+Personalize.hosts['staticCache']+'image/blank.gif) repeat; overflow:hidden;'});var doodlePlacement=Personalize.actualPosition(this.doodleElement);var edWidth=this.doodleElement.getWidth()+10;var edHeight=this.doodleElement.getHeight()+10;if(edWidth<80){edWidth=80;}
if(edHeight<80){edHeight=80;}
this.editor.setStyle({top:doodlePlacement[1]-5+'px',left:doodlePlacement[0]-5+'px',width:edWidth+'px',height:edHeight+'px',position:'absolute',zIndex:1200000000,overflow:'visible'});this.borderElement=new Element('div',{'class':'doodleEditorBorder'});this.borderElement.setStyle({top:'0px',left:'0px',width:edWidth+'px',height:edHeight+'px'});if(this.isDoodle){this.editor.insert(this.borderElement);}
this.drag=new Element('div',{'class':'doodleEditorDragger clickable',style:'position: absolute; top : '+(edHeight-3)+'px; left: '+(edWidth-3)+'px;'});this.mirrorBtn=new Element('div',{'class':'clickable sprite-icon-flip',style:'margin-top: 5px;'});this.rotateBtn=new Element('div',{'class':'clickable sprite-icon-rotate',style:'margin-top: 5px;'});this.zBackBtn=new Element('div',{'class':'clickable',style:'margin-top: 5px;'});this.zFwdBtn=new Element('div',{'class':'clickable',style:'margin-top: 5px;'});this.removeBtn=new Element('div',{'class':'clickable sprite-icon-deletedoodles'});this.mirrorBtn.observe('click',this.mirrorCurrentImage.bind(this));this.rotateBtn.observe('click',this.rotate.bind(this));this.removeBtn.observe('click',this.remove.bind(this));this.zFwdBtn.observe('click',this.bringForward.bind(this));this.zBackBtn.observe('click',this.sendBackward.bind(this));Personalize.makeHover(this.zBackBtn,'sprite-icon-backward');Personalize.makeHover(this.zFwdBtn,'sprite-icon-forward');this.btnContainer=new Element('div',{'class':'doodleEditorButtons'});if(this.isDoodle){this.btnContainer.insert(this.removeBtn);this.btnContainer.insert(this.zBackBtn);this.btnContainer.insert(this.zFwdBtn);}
if(this.options.rotation){this.btnContainer.insert(this.rotateBtn);}
if(this.options.mirror){this.btnContainer.insert(this.mirrorBtn);}
this.zFwdBtn.hide();this.btnContainer.setStyle({position:'relative',top:'-5px',left:'-20px',width:'20px',height:'60px'});this.editor.insert(this.btnContainer);if(this.options.resizable){this.editor.insert(this.drag);new Draggable(this.drag,{change:this.pull.bind(this),onEnd:this.resizeEnd.bind(this)});}
if(this.options.movable){new Draggable(this.editor,{change:this.move.bind(this),onEnd:this.resizeEnd.bind(this)});}else{this.editor.setStyle({cursor:'pointer'});}
this.currentLayout={top:this.editor.style.top,left:this.editor.style.left,width:this.editor.style.width,height:this.editor.style.height}
if(this.isMonogram){this.renderMonogramEditor();}
return this.editor;},renderMonogramEditor:function(){if(this.monogramEditor){this.monogramEditor.hidePopup();}
this.monogramEditor=TP.extendObject(new PersonalizePopup('Edit Your Monogram','doodleEditor'),new PersonalizeMonogramEditor());var content=this.monogramEditor.getPopupElement();var editorContainer=new Element('div',{});var instruction=new Element('div',{style:'color:#53351A; font-family:Arial; font-size:12px; margin-left:5px; text-align:left;'}).update('Click on the letter to edit');var doodleImagePanel=new Element('div',{'class':'doodle-editor-image-panel'});var doodleImageEditor=new Element('div',{});var editorResolution=150;var popupWidth=428;doodleImageEditor.setStyle({position:'relative',border:'2px dashed #cccccc',width:editorResolution+'px',height:editorResolution+'px',left:((popupWidth-editorResolution)/2)+'px',background:'transparent url('+this.getDoodleImageUrl()+') no-repeat'});this.doodleTextboxEditorElements={};var doodleColorImageWidth=this.doodle.colors[this.doodle.doodleColorId].image.width;var aspectRatio=editorResolution/doodleColorImageWidth;for(var designboxId in this.doodle.textOptions.designboxes){var designBox=this.doodle.textOptions.designboxes[designboxId];var designBoxElement=new Element('div',{});designBoxElement.setStyle({position:'absolute',float:'left',left:(designBox.x*aspectRatio)+'px',top:(designBox.y*aspectRatio)+'px',width:(designBox.width*aspectRatio)+'px',height:(designBox.height*aspectRatio)+'px'});for(var textboxId in designBox.textboxes){var textbox=designBox.textboxes[textboxId];var textboxElement=new Element('input',{id:'doodleTextboxEditor_'+textbox.textboxId,type:'text',maxlength:1});textboxElement.parameters={textbox:textbox,content:textbox.content,selected:false,width:(textbox.width*aspectRatio),height:(textbox.height*aspectRatio),font:textbox.fontId,fontSize:textbox.fontSize,fontColor:textbox.fontColorId,textAlign:textbox.horizontalAlignmentId};textboxElement.observe('keydown',this.captureDoodleText.bindAsEventListener(this,textboxElement));textboxElement.observe('focus',this.doodleTextboxFocus.bind(this,textboxElement));var doodleTextboxHandler=new Element('div',{});doodleTextboxHandler.setStyle({position:'absolute',float:'left',left:(textbox.x*aspectRatio)+'px',top:(textbox.y*aspectRatio)+'px',width:(textbox.width*aspectRatio)+'px',height:(textbox.height*aspectRatio)+'px'});textboxElement.setOpacity(0);doodleTextboxHandler.insert(textboxElement);this.renderDoodleTextBox(textboxElement);this.doodleTextboxEditorElements[textboxId]=textboxElement;designBoxElement.insert(doodleTextboxHandler);}
doodleImageEditor.insert(designBoxElement);}
for(var textboxId in this.doodle.textOptions.textboxes){var textbox=this.doodle.textOptions.textboxes[textboxId];var textboxElement=new Element('input',{id:'doodleTextboxEditor_'+textbox.textboxId,type:'text',maxlength:1});textboxElement.parameters={textbox:textbox,selected:false,content:textbox.content,width:(textbox.width*aspectRatio),height:(textbox.height*aspectRatio),font:textbox.fontId,fontSize:textbox.fontSize,fontColor:textbox.fontColorId,textAlign:textbox.horizontalAlignmentId};textboxElement.observe('keydown',this.captureDoodleText.bindAsEventListener(this,textboxElement));textboxElement.observe('focus',this.doodleTextboxFocus.bind(this,textboxElement));var doodleTextboxHandler=new Element('div',{});doodleTextboxHandler.setStyle({position:'absolute',backgroundColor:'#eeeeee',float:'left',left:(textbox.x*aspectRatio)+'px',top:(textbox.y*aspectRatio)+'px',width:(textbox.width*aspectRatio)+'px',height:(textbox.height*aspectRatio)+'px'});textboxElement.setOpacity(0);doodleTextboxHandler.insert(textboxElement);this.renderDoodleTextBox(textboxElement);this.doodleTextboxEditorElements[textboxId]=textboxElement;doodleImageEditor.insert(doodleTextboxHandler);}
doodleImagePanel.insert(doodleImageEditor);var doodleTextPanel=new Element('div',{'class':'doodle-editor-text-panel'});var title=new Element('div',{'class':'doodle-editor-text-panel-title'}).update('Selection Settings:');doodleTextPanel.insert(title);this.styleSelectContainer=new Element('div',{style:'float: left;'});doodleTextPanel.insert(this.styleSelectContainer);this.colorsContainer=new Element('div',{'class':'doodle-editor-text-panel-colors'});doodleTextPanel.insert(this.colorsContainer);this.doneBtn=new Element('div',{'class':'sprite-btn-done clickable',style:'float: left; margin-top: 10px;'});this.doneBtn.observe('click',this.applyStyleHandler.bind(this));doodleTextPanel.insert(this.doneBtn);editorContainer.insert(instruction);editorContainer.insert(doodleImagePanel);editorContainer.insert(doodleTextPanel);editorContainer.insert(new Element('div',{style:'clear: both; line-height: 0px;'}));content.insert(editorContainer);this.monogramEditor.showPopup();this.monogramEditor.setPosition();this.renderDoodleFontStyles(null);this.renderColorSwatch();},renderDoodleFontStyles:function(textbox){this.styleSelect=new Element('select',{id:'monogramEditor'});if(!textbox){for(var textboxId in this.doodle.textOptions.textboxes){var textbox=this.doodle.textOptions.textboxes[textboxId];break;}}
if(!textbox){for(var designboxId in this.doodle.textOptions.designboxes){for(textboxId in this.doodle.textOptions.designboxes[designboxId].textboxes){var textbox=this.doodle.textOptions.designboxes[designboxId].textboxes[textboxId];break;}}}
var textboxElement=$('doodleTextboxEditor_'+textbox.textboxId);var settings=textboxElement.parameters;for(var fontId in textbox.fonts){var font=Personalize.masterFontList[fontId];var option=new Element('option',{value:fontId}).update(font.displayName);this.styleSelect.insert(option);}
this.styleSelectContainer.update(this.styleSelect);var prettySelect=new PrettySelect2('monogramEditor',{renderFn:function(params){var item=new Element('div',{'class':'sprite-font-'+this.value});return item;}});prettySelect.render();prettySelect.select(settings.font);prettySelect.postSelect=this.styleChangeHandler.bind(this);},styleChangeHandler:function(element,fontId){for(var textboxId in this.doodleTextboxEditorElements){var textboxElement=$('doodleTextboxEditor_'+textboxId);if(!textboxElement)break;var settings=textboxElement.parameters;if(settings.selected){settings.font=fontId;this.renderDoodleTextBox(textboxElement);}}},doodleTextboxFocus:function(textboxElement){if(textboxElement){for(var textboxId in this.doodleTextboxEditorElements){var textboxEl=$('doodleTextboxEditor_'+textboxId);if(!textboxEl)break;var settings=textboxEl.parameters;settings.selected=false;this.renderDoodleTextBox(textboxEl);}
var settings=textboxElement.parameters;settings.selected=true;this.renderDoodleTextBox(textboxElement);this.renderDoodleFontStyles(settings.textbox);this.renderColorSwatch(settings.textbox);this.doodleTextboxGroupFocus(settings.textbox);}},doodleTextboxGroupFocus:function(textbox){if(textbox&&textbox.designBoxId){for(var textboxId in this.doodleTextboxEditorElements){var textboxElement=$('doodleTextboxEditor_'+textboxId);if(!textboxElement)break;var settings=textboxElement.parameters;if(settings.textbox.designBoxId==textbox.designBoxId){settings.selected=true;this.renderDoodleTextBox(textboxElement);}}}},renderDoodleTextBox:function(textboxElement){var horizontalAlignmentTypes={1:'left',2:'center',3:'right',4:'justify'};var verticalAlignmentTypes={1:'center',2:'top',3:'center',4:'bottom',5:'illustrator'};if(textboxElement){var settings=textboxElement.parameters;textboxElement.setStyle({position:'absolute',float:'left',left:0+'px',top:0+'px',width:settings.width+'px',height:settings.height+'px',fontSize:settings.fontSize+'pt',textAlign:'center'});if(settings.selected){textboxElement.setStyle({border:'1px solid black',backgroundColor:'#3CB1DD',width:(settings.width-2)+'px'});textboxElement.setOpacity(0.2);}else{textboxElement.setStyle({border:'0px solid white',backgroundColor:'',width:settings.width+'px'});textboxElement.setOpacity(0);}
var fontColors=settings.textbox.doodleColorFontColors[this.associatedDoodle.doodleColorId];if(typeof settings.textbox.productDoodleColorFontColors[Personalize.product.color.colorId]!=='undefined'){fontColors=settings.textbox.productDoodleColorFontColors[Personalize.product.color.colorId][this.associatedDoodle.doodleColorId];}
var fontColorRgb='';if(typeof fontColors[settings.fontColor]!=='undefined'){fontColorRgb=fontColors[settings.fontColor].rgb;}else{for(var fontId in fontColors){var font=fontColors[fontId];if(font['default']==1){settings.fontColor=fontId;fontColorRgb=font.rgb;break;}}}
var handler=textboxElement.up();handler.setStyle({background:'transparent url('+Personalize.hosts['static']+'image/tp/personalize/smallSpinner.gif) center no-repeat'});var imageUrl=Personalize.hosts.text+'personalize/textbox/restrictSize/0/width/'+settings.width+'/height/'+settings.height+'/fontName/'+Personalize.masterFontList[settings.font].name+'/fontSize/'+settings.fontSize+'/fontColor/'+fontColorRgb+'/verticalAlignment/'+verticalAlignmentTypes[settings.textbox.verticalAlignmentId]+'/horizontalAlignment/'+horizontalAlignmentTypes[settings.textbox.horizontalAlignmentId]+'/text/'+encodeURIComponent(encodeURIComponent(JSON.stringify(settings.content)))+'.png';var img=new Image();img.onload=this.swapMonogramImage.bind(this,handler,imageUrl);img.src=imageUrl;}},swapMonogramImage:function(handler,imageUrl){handler.setStyle({background:'transparent url('+imageUrl+') no-repeat'});},captureDoodleText:function(keyDownEvent,textboxElement){if(keyDownEvent.altKey||keyDownEvent.ctrKey){return;}
var delayRenderFn=this.renderDoodleTextboxBackgroundText.bind(this,textboxElement);delayRenderFn.delay(0.1,textboxElement);},renderDoodleTextboxBackgroundText:function(textboxElement){if(textboxElement){if(textboxElement.value){textboxElement.parameters.content=textboxElement.value;textboxElement.value='';}
this.renderDoodleTextBox(textboxElement);}},getDoodleImageUrl:function(){if(!this.isMonogram){return;}
var width=150;var height=150;return Personalize.hosts.images+'image/doodle/'+this.associatedDoodle.doodleColorImage.imageId+'/width/'+width+'/height/'+height+'.png';},applyStyleHandler:function(){for(var textboxId in this.doodle.textOptions.textboxes){var targetTextbox=this.doodle.textOptions.textboxes[textboxId];var sourceTextboxEl=$('doodleTextboxEditor_'+textboxId);if(!sourceTextboxEl||!targetTextbox)continue;var settings=sourceTextboxEl.parameters;targetTextbox.content=settings.content;targetTextbox.fontId=settings.font;targetTextbox.fontColorId=settings.fontColor;}
for(var designBoxId in this.doodle.textOptions.designboxes){var designBox=this.doodle.textOptions.designboxes[designBoxId];for(var textboxId in designBox.textboxes){var targetTextbox=designBox.textboxes[textboxId];var sourceTextboxEl=$('doodleTextboxEditor_'+textboxId);if(!sourceTextboxEl||!targetTextbox)continue;var settings=sourceTextboxEl.parameters;targetTextbox.content=settings.content;targetTextbox.fontId=settings.font;targetTextbox.fontColorId=settings.fontColor;}}
this.monogramEditor.hidePopup();this.newDoodleImg=new Image();this.newDoodleImg.onload=this.swapImage.bind(this);this.newDoodleImg.src=this.getUrl();personalizePersonalize.textOptions=Object.clone(this.doodle.textOptions);},restoreMonogramText:function(){this.savedDoodleTextboxes=new Array();this.savedDesignBoxTextboxes=new Array();for(var sTextboxId in personalizePersonalize.textOptions.textboxes){var targetTextbox=personalizePersonalize.textOptions.textboxes[sTextboxId];this.savedDoodleTextboxes.push(targetTextbox.content.substr(0,1));}
for(var designBoxId in personalizePersonalize.textOptions.designboxes){var designBox=personalizePersonalize.textOptions.designboxes[designBoxId];for(var sTextboxId in designBox.textboxes){var targetTextbox=designBox.textboxes[sTextboxId];this.savedDesignBoxTextboxes.push(targetTextbox.content.substr(0,1));}}},colorChangeHandler:function(selectedColorId){var colorEl=$('doodleEditorColorSelect_'+selectedColorId);if(!colorEl)return;var renderredColorSwatch=false;for(var textboxId in this.doodleTextboxEditorElements){var textboxElement=$('doodleTextboxEditor_'+textboxId);if(!textboxElement)break;var settings=textboxElement.parameters;if(settings.selected){settings.fontColor=selectedColorId;this.renderDoodleTextBox(textboxElement);if(!renderredColorSwatch){this.renderColorSwatch(settings.textbox);renderredColorSwatch=true;}}}},renderColorSwatch:function(textbox){this.colorsSelect=new Element('div',{'class':'doodle-editor-text-panel-colors'});if(!textbox){for(var textboxId in this.doodle.textOptions.textboxes){var textbox=this.doodle.textOptions.textboxes[textboxId];break;}}
if(!textbox){for(var designboxId in this.doodle.textOptions.designboxes){for(textboxId in this.doodle.textOptions.designboxes[designboxId].textboxes){var textbox=this.doodle.textOptions.designboxes[designboxId].textboxes[textboxId];break;}}}
var textboxElement=$('doodleTextboxEditor_'+textbox.textboxId);var settings=textboxElement.parameters;var doodleColorFontColor;if(typeof settings.textbox.productDoodleColorFontColors[Personalize.product.color.colorId]!=='undefined'){doodleColorFontColor=settings.textbox.productDoodleColorFontColors[Personalize.product.color.colorId][this.associatedDoodle.doodleColorId];}else{doodleColorFontColor=settings.textbox.doodleColorFontColors[this.associatedDoodle.doodleColorId];}
for(var colorId in doodleColorFontColor){var color=doodleColorFontColor[colorId];if(typeof color!=='object'){continue;}
var colorEl=new Element('div',{id:'doodleEditorColorSelect_'+colorId,'class':'doodle-editor-text-panel-color'});if(settings.fontColor==colorId){colorEl.addClassName('doodle-editor-text-panel-color-selected');}
var colorDisplayEl=new Element('div',{'class':'doodle-editor-text-panel-color-display',style:'background-color: #'+color.rgb+';'});colorEl.insert(colorDisplayEl);colorEl.observe('click',this.colorChangeHandler.bind(this,colorId));this.colorsSelect.insert(colorEl);}
this.colorsContainer.update(this.colorsSelect);this.adjustWindow();},adjustWindow:function(){if(Personalize.isIe()||Personalize.ie8){var height=220+this.colorsContainer.getHeight();this.monogramEditor.domElement.setStyle({height:height+'px'});}
if(this.colorsContainer.getHeight()>23){this.doneBtn.setStyle({marginTop:(this.colorsContainer.getHeight()-23)+'px'});}},move:function(){var edTop=Personalize.pxToNumber(this.editor.style.top);var edLeft=Personalize.pxToNumber(this.editor.style.left);var panelPosition=Personalize.actualPosition(this.doodleHandle.up());this.doodleHandle.setStyle({top:(edTop-panelPosition[1]+5)+'px',left:(edLeft-panelPosition[0]+5)+'px'});},pull:function(el,ev){var top=-3;var left=-3;var bottom=Personalize.pxToNumber(el.element.style.top);var right=Personalize.pxToNumber(el.element.style.left);var edWidth=(right-left);var edHeight=(bottom-top);var isResizeAllow=true;var doodleElementPositionedOffset=this.doodleHandle.positionedOffset();var doodleElementPositionedOffsetLeft=doodleElementPositionedOffset[0];var doodleElementPositionedOffsetTop=doodleElementPositionedOffset[1];var formattedDropArea=this.doodleHandle.up();var formattedDropAreaWidth=Personalize.pxToNumber(formattedDropArea.style.width);var formattedDropAreaHeight=Personalize.pxToNumber(formattedDropArea.style.height);var editorWidth=Personalize.pxToNumber(this.editor.style.width+edWidth);var editorHeight=Personalize.pxToNumber(this.editor.style.height+edHeight);var editorCenterPointSizes={vertical:parseInt(editorHeight/2),horizontal:parseInt(editorWidth/2)}
if(doodleElementPositionedOffsetLeft+editorWidth>formattedDropAreaWidth){isResizeAllow=false;}
if(doodleElementPositionedOffsetTop+editorHeight>formattedDropAreaHeight){isResizeAllow=false;}
if(!isResizeAllow){this.drag.style.left=(Personalize.pxToNumber(this.borderElement.style.width)-3)+'px';this.drag.style.top=(Personalize.pxToNumber(this.borderElement.style.height)-3)+'px';return;}
if((edWidth/edHeight)!=this.aspectRatio){edWidth=this.aspectRatio*edHeight;}
edWidth=Math.max(edWidth,30);edHeight=Math.max(edHeight,30);var edTop=Personalize.pxToNumber(this.editor.style.top)+top;var edLeft=Personalize.pxToNumber(this.editor.style.left)+left;this.drag.style.left=(edWidth-3)+'px';this.drag.style.top=(edHeight-3)+'px';this.editor.setStyle({top:(edTop+3)+'px',left:(edLeft+3)+'px',width:(edWidth)+'px',height:(edHeight)+'px'});this.borderElement.setStyle({top:(top+3)+'px',left:(left+3)+'px',width:(edWidth)+'px',height:(edHeight)+'px'});var panelPosition=Personalize.actualPosition(this.doodleHandle.up());this.doodleElement.setStyle({width:edWidth-10+'px',height:edHeight-10+'px'});this.doodleHandle.setStyle({top:(edTop-panelPosition[1]+3+5)+'px',left:(edLeft-panelPosition[0]+3+5)+'px',width:edWidth-10+'px',height:edHeight-10+'px'});},sendBackward:function(){this.zFwdBtn.show();this.zBackBtn.hide();this.doodleElement.setStyle({zIndex:parseFloat(Personalize.textboxZIndex-10)});this.doodle.z=parseFloat(Personalize.textboxZIndex-10);},bringForward:function(){this.zFwdBtn.hide();this.zBackBtn.show();this.doodleElement.setStyle({zIndex:parseFloat(Personalize.doodleZIndex)});this.doodle.z=parseFloat(Personalize.doodleZIndex);},resizeEnd:function(){var doodleElementPositionedOffset=this.doodleHandle.positionedOffset();var doodleElementPositionedOffsetLeft=doodleElementPositionedOffset[0];var doodleElementPositionedOffsetTop=doodleElementPositionedOffset[1];var formattedDropArea=this.doodleHandle.up();var formattedDropAreaWidth=Personalize.pxToNumber(formattedDropArea.style.width);var formattedDropAreaHeight=Personalize.pxToNumber(formattedDropArea.style.height);var editorWidth=Personalize.pxToNumber(this.editor.style.width);var editorHeight=Personalize.pxToNumber(this.editor.style.height);var editorCenterPointSizes={vertical:parseInt(editorHeight/2),horizontal:parseInt(editorWidth/2)}
var revert=false;if(doodleElementPositionedOffsetLeft+editorWidth>formattedDropAreaWidth+5){revert=true;}else if(doodleElementPositionedOffsetLeft-5<0){revert=true;}
if(doodleElementPositionedOffsetTop+editorHeight>formattedDropAreaHeight+6){revert=true;}else if(doodleElementPositionedOffsetTop-7<0){revert=true;}
if(revert){this.revertPosition();}else{this.doodle.y=Personalize.resolutionConvert(Personalize.pxToNumber(this.doodleHandle.style.top),this.resolution,144);this.doodle.x=Personalize.resolutionConvert(Personalize.pxToNumber(this.doodleHandle.style.left),this.resolution,144);this.doodle.width=Personalize.resolutionConvert(this.doodleHandle.getWidth(),this.resolution,144);this.doodle.height=Personalize.resolutionConvert(this.doodleHandle.getHeight(),this.resolution,144);this.currentLayout={top:this.editor.style.top,left:this.editor.style.left,width:this.editor.style.width,height:this.editor.style.height}}
this.newDoodleImg=new Image();this.newDoodleImg.onload=this.swapImage.bind(this);this.newDoodleImg.src=this.getUrl();},swapImage:function(){var url=this.getUrl();this.doodleElement.src=url;},revertPosition:function(){new Effect.Move(this.editor,{x:Personalize.pxToNumber(this.currentLayout.left),y:Personalize.pxToNumber(this.currentLayout.top),duration:1.0,mode:'absolute',transition:Effect.Transitions.spring,afterFinish:this.revertEffectEnd.bind(this)});},revertEffectEnd:function(){this.editor.setStyle({top:this.currentLayout.top,left:this.currentLayout.left,width:this.currentLayout.width,height:this.currentLayout.height});this.move();},setAvailable:function(available){this.available=available;if(this.available){this.doodleElement.show();}else{this.doodleElement.hide();if(typeof this.editor!=='undefined'){this.editor.remove();}}},validate:function(){this.doodle.doodleColorId=this.associatedDoodle.doodleColorId;this.doodle.doodleId=this.productDoodle.id;this.doodle.imageId=this.associatedDoodle.doodleColorImage.imageId;try{if(typeof this.doodle.dropArea.dropArea!=='undefined'&&this.doodle.dropArea.dropArea){this.doodle.dropAreaId=this.doodle.dropArea.dropArea.dropAreaId;}}catch(e){}}};var personalizeDoodleGlobal=function(){};personalizeDoodleGlobal.prototype={pull:function(el,ev){var top=-3;var left=-3;var bottom=Personalize.pxToNumber(el.element.style.top);var right=Personalize.pxToNumber(el.element.style.left);var edWidth=(right-left);var edHeight=(bottom-top);var isResizeAllow=true;var doodleElementPositionedOffset=this.doodleHandle.positionedOffset();var doodleElementPositionedOffsetLeft=doodleElementPositionedOffset[0];var doodleElementPositionedOffsetTop=doodleElementPositionedOffset[1];var formattedDropArea=this.doodleHandle.up();var formattedDropAreaWidth=Personalize.pxToNumber(formattedDropArea.style.width);var formattedDropAreaHeight=Personalize.pxToNumber(formattedDropArea.style.height);var editorWidth=Personalize.pxToNumber(this.editor.style.width+edWidth);var editorHeight=Personalize.pxToNumber(this.editor.style.height+edHeight);var editorCenterPointSizes={vertical:parseInt(editorHeight/2),horizontal:parseInt(editorWidth/2)}
if(doodleElementPositionedOffsetLeft+editorWidth>formattedDropAreaWidth+editorCenterPointSizes.horizontal){isResizeAllow=false;}else if(doodleElementPositionedOffsetLeft<-editorCenterPointSizes.horizontal){isResizeAllow=false;}
if(doodleElementPositionedOffsetTop+editorHeight>formattedDropAreaHeight+editorCenterPointSizes.vertical){isResizeAllow=false;}else if(doodleElementPositionedOffsetTop<-editorCenterPointSizes.vertical){isResizeAllow=false;}
if(!isResizeAllow){this.drag.style.left=(Personalize.pxToNumber(this.borderElement.style.width)-3)+'px';this.drag.style.top=(Personalize.pxToNumber(this.borderElement.style.height)-3)+'px';return;}
if((edWidth/edHeight)!=this.aspectRatio){edWidth=this.aspectRatio*edHeight;}
edWidth=Math.max(edWidth,30);edHeight=Math.max(edHeight,30);var edTop=Personalize.pxToNumber(this.editor.style.top)+top;var edLeft=Personalize.pxToNumber(this.editor.style.left)+left;this.drag.style.left=(edWidth-3)+'px';this.drag.style.top=(edHeight-3)+'px';this.editor.setStyle({top:(edTop+3)+'px',left:(edLeft+3)+'px',width:(edWidth)+'px',height:(edHeight)+'px'});this.borderElement.setStyle({top:(top+3)+'px',left:(left+3)+'px',width:(edWidth)+'px',height:(edHeight)+'px'});var panelPosition=Personalize.actualPosition(this.doodleHandle.up());this.doodleElement.setStyle({width:edWidth-10+'px',height:edHeight-10+'px'});this.doodleHandle.setStyle({top:(edTop-panelPosition[1]+3+5)+'px',left:(edLeft-panelPosition[0]+3+5)+'px',width:edWidth-10+'px',height:edHeight-10+'px'});},resizeEnd:function(){var doodleElementPositionedOffset=this.doodleHandle.positionedOffset();var doodleElementPositionedOffsetLeft=doodleElementPositionedOffset[0];var doodleElementPositionedOffsetTop=doodleElementPositionedOffset[1];var formattedDropArea=this.doodleHandle.up();var formattedDropAreaWidth=Personalize.pxToNumber(formattedDropArea.style.width);var formattedDropAreaHeight=Personalize.pxToNumber(formattedDropArea.style.height);var editorWidth=Personalize.pxToNumber(this.editor.style.width);var editorHeight=Personalize.pxToNumber(this.editor.style.height);var editorCenterPointSizes={vertical:parseInt(editorHeight/2),horizontal:parseInt(editorWidth/2)}
var revert=false;if(doodleElementPositionedOffsetLeft+editorWidth>formattedDropAreaWidth+editorCenterPointSizes.horizontal){revert=true;}else if(doodleElementPositionedOffsetLeft<-editorCenterPointSizes.horizontal){revert=true;}
if(doodleElementPositionedOffsetTop+editorHeight>formattedDropAreaHeight+editorCenterPointSizes.vertical){revert=true;}else if(doodleElementPositionedOffsetTop<-editorCenterPointSizes.vertical){revert=true;}
if(revert){this.revertPosition();}else{this.doodle.y=Personalize.resolutionConvert(Personalize.pxToNumber(this.doodleHandle.style.top),this.resolution,144);this.doodle.x=Personalize.resolutionConvert(Personalize.pxToNumber(this.doodleHandle.style.left),this.resolution,144);this.doodle.width=Personalize.resolutionConvert(this.doodleHandle.getWidth(),this.resolution,144);this.doodle.height=Personalize.resolutionConvert(this.doodleHandle.getHeight(),this.resolution,144);this.currentLayout={top:this.editor.style.top,left:this.editor.style.left,width:this.editor.style.width,height:this.editor.style.height}}
this.newDoodleImg=new Image();this.newDoodleImg.onload=this.swapImage.bind(this);this.newDoodleImg.src=this.getUrl();}};var PersonalizeDropArea=function(dropArea,resolution){this.dropArea=dropArea;this.domElement=null;this.resolution=resolution;this.panel=personalizePersonalize.currentPanel;this.doodles=[];this.visible=false;this.handlesContainer=null;this.top=0;this.left=0;this.width=0;this.height=0;};PersonalizeDropArea.prototype={render:function(parentElement){this.top=Personalize.roundForRendering(Personalize.resolutionConvert(parseFloat(this.dropArea.y),144,this.resolution));this.left=Personalize.roundForRendering(Personalize.resolutionConvert(parseFloat(this.dropArea.x),144,this.resolution));this.width=Personalize.roundForRendering(Personalize.resolutionConvert(parseFloat(this.dropArea.width),144,this.resolution));this.height=Personalize.roundForRendering(Personalize.resolutionConvert(parseFloat(this.dropArea.height),144,this.resolution));this.domElement=new Element('div',{'class':'personalize-doodle-droparea'});this.domElement.setOpacity(0.8);this.domElement.dropArea=this;this.domElement.identify();this.domElement.setStyle({position:'absolute',top:this.top+'px',left:this.left+'px',width:this.width+'px',height:this.height+'px',backgroundColor:'',zIndex:199});this.handlesContainer=new Element('div',{'class':'panelHandleContainer'});this.handlesContainer.identify();this.handlesContainer.setStyle({position:'absolute',top:0,left:0,width:this.width+'px',height:this.height+'px'});this.domElement.insert(this.handlesContainer);parentElement.insert(this.domElement);Droppables.add(this.domElement,{accept:'trayDoodleImageDraggable',hoverClass:'',onDrop:function(element,droppable,event){var droppableOfs=droppable.cumulativeOffset();try{var scroll=droppable.cumulativeScrollOffset();}catch(e){var scroll={top:0,left:0};}
var panelX=event.clientX-droppableOfs.left-35+scroll.left;var panelY=event.clientY-droppableOfs.top-35+scroll.top;this.addDoodle(element.trayDoodle,panelX,panelY);}.bind(this)});this.populate();},populate:function(){var doodleTray=personalizePersonalize.doodleTray;for(var doodleId in this.panel.doodles){var sDoodle=this.panel.doodles[doodleId];var trayDoodle=doodleTray.getTrayDoodleByImageId(sDoodle.imageId);if(trayDoodle&&sDoodle.dropAreaId==this.dropArea.dropAreaId){sDoodle.dropArea=this;sDoodle.trayDoodle=trayDoodle;var personalizationDoodle=TP.extendObject(new Doodle(),trayDoodle.productDoodle);personalizationDoodle=TP.extendObject(personalizationDoodle,sDoodle);personalizationDoodle.id=null;var panelDoodle=new personalizeDoodle(personalizationDoodle,this.panel);panelDoodle.panelDoodleId=doodleId;this.doodles.push(panelDoodle);this.domElement.insert(panelDoodle.render(this.resolution,this.handlesContainer));this.visible=true;this.hide();}}},addBackgroundDropImageText:function(){var dilimeter=' ';if(this.width<80){dilimeter='\n';}
this.handlesContainer.setStyle({backgroundImage:'url('+Personalize.hosts.textv2Cache+'personalize/textbox/restrictSize/0/width/'+this.width+'/height/'+this.height+'/fontName/NeutraText/fontSize/5/fontColor/000000/verticalAlignment/center/horizontalAlignment/center/text/'+encodeURIComponent(encodeURIComponent(JSON.stringify('DROP'+dilimeter+'ACCENTS'+dilimeter+'HERE')))+'.png)'});},removeBackgroundDropHere:function(){this.handlesContainer.setStyle({backgroundImage:'url()'});},removeDoodle:function(panelDoodle){for(var i=0;i<this.doodles.length;i++){if(this.doodles[i]==panelDoodle){delete this.doodles[i];this.doodles.splice(i,1);delete this.panel.doodles[panelDoodle.panelDoodleId];panelDoodle.trayDoodle.unregister();if(!this.doodles.length){this.addBackgroundDropImageText();}}}},show:function(){if(!this.visible){this.domElement.setStyle({backgroundColor:'#f2f3ee',border:'2px dashed #7e7e72'});this.validateBackgroundDropImageText();this.domElement.setOpacity(0.8);this.visible=true;}},hide:function(){if(this.visible){this.domElement.setStyle({backgroundColor:'',backgroundImage:'',border:''});this.removeBackgroundDropHere();this.domElement.setOpacity(1);this.visible=false;}},validateBackgroundDropImageText:function(){var availableDoodleCount=0;for(var i=0;i<this.doodles.length;i++){var personalizeDoodle=this.doodles[i];if(personalizeDoodle.available){availableDoodleCount++;}}
if(availableDoodleCount){this.removeBackgroundDropHere();}else{this.addBackgroundDropImageText();}},addDoodle:function(trayDoodle,x,y,noEditing){var tolerance=0;var personalizationDoodle=TP.extendObject(new Doodle(),trayDoodle.productDoodle);personalizationDoodle.id=null;var newWidth=Personalize.defaultDoodleSize;var newHeight=Personalize.defaultDoodleSize;if(newWidth>this.width||newHeight>this.height){var aspectRatio=(this.width>this.height)?(this.height/this.width):(this.width/this.height);if(this.width>this.height){newHeight=this.height-tolerance;newWidth=newWidth*aspectRatio-tolerance;}else{newWidth=this.width-tolerance;newHeight=newHeight*aspectRatio-tolerance;}}
personalizationDoodle.width=Personalize.resolutionConvert(newWidth,this.resolution,144);personalizationDoodle.height=Personalize.resolutionConvert(newHeight,this.resolution,144);var newX=parseInt(this.width/2)-(newWidth/2);var newY=parseInt(this.height/2)-(newHeight/2);personalizationDoodle.x=Personalize.resolutionConvert(newX,this.resolution,144);personalizationDoodle.y=Personalize.resolutionConvert(newY,this.resolution,144);personalizationDoodle.z=parseFloat(Personalize.doodleZIndex++);personalizationDoodle.dropArea=this;personalizationDoodle.trayDoodle=trayDoodle;this.panel.doodles[personalizePersonalize.lastPanelDoodleId]=personalizationDoodle;var panelDoodle=new personalizeDoodle(personalizationDoodle,this.panel);panelDoodle.panelDoodleId=personalizePersonalize.lastPanelDoodleId++;this.doodles.push(panelDoodle);this.domElement.insert(panelDoodle.render(this.resolution,this.handlesContainer));if(!noEditing){setTimeout(panelDoodle.startEditing.bind(panelDoodle),50);}},changeColor:function(){for(var i=0;i<this.doodles.length;i++){var personalizeDoodle=this.doodles[i];personalizeDoodle.changeColor();}
if(this.visible){this.validateBackgroundDropImageText();}}};var PersonalizeGlobalDropArea=function(){this.dropArea=null;this.productDropArea=null;};PersonalizeGlobalDropArea.prototype={render:function(parentElement){this.top=0;this.left=0;this.width=Personalize.pxToNumber(parentElement.style.width);this.height=Personalize.pxToNumber(parentElement.style.height);this.domElement=new Element('div',{'class':'personalize-doodle-droparea'});this.domElement.dropArea=this;this.domElement.identify();this.domElement.setStyle({position:'absolute',top:this.top+'px',left:this.left+'px',width:this.width+'px',height:this.height+'px',backgroundColor:'',zIndex:199});this.handlesContainer=new Element('div',{'class':'panelHandleContainer'});this.handlesContainer.identify();this.handlesContainer.setStyle({position:'absolute',top:0,left:0,width:this.width+'px',height:this.height+'px'});this.domElement.insert(this.handlesContainer);parentElement.insert(this.domElement);Droppables.add(this.domElement,{accept:'trayDoodleImageDraggable',hoverClass:'',onDrop:function(element,droppable,event){var droppableOfs=droppable.cumulativeOffset();try{var scroll=droppable.cumulativeScrollOffset();}catch(e){var scroll={top:0,left:0};}
var panelX=event.clientX-droppableOfs.left-35+scroll.left;var panelY=event.clientY-droppableOfs.top-35+scroll.top;this.addDoodle(element.trayDoodle,panelX,panelY);}.bind(this)});this.populate();},populate:function(){var doodleTray=personalizePersonalize.doodleTray;for(var doodleId in this.panel.doodles){var sDoodle=this.panel.doodles[doodleId];var trayDoodle=doodleTray.getTrayDoodleByImageId(sDoodle.imageId);if(trayDoodle){sDoodle.dropArea=this;sDoodle.trayDoodle=trayDoodle;var personalizationDoodle=TP.extendObject(new Doodle(),trayDoodle.productDoodle);personalizationDoodle=TP.extendObject(personalizationDoodle,sDoodle);personalizationDoodle.id=null;var panelDoodle=new personalizeDoodle(personalizationDoodle,this.panel);panelDoodle.panelDoodleId=doodleId;this.doodles.push(panelDoodle);this.domElement.insert(panelDoodle.render(this.resolution,this.handlesContainer));}}},addBackgroundDropImageText:function(){},removeBackgroundDropHere:function(){},show:function(){},hide:function(){},validateBackgroundDropImageText:function(){},addDoodle:function(trayDoodle,x,y){var tolerance=16;var personalizationDoodle=TP.extendObject(new Doodle(),trayDoodle.productDoodle);personalizationDoodle.id=null;var newWidth=Personalize.defaultDoodleSize;var newHeight=Personalize.defaultDoodleSize;personalizationDoodle.width=Personalize.resolutionConvert(newWidth,this.resolution,144);personalizationDoodle.height=Personalize.resolutionConvert(newHeight,this.resolution,144);var newX=x;var newY=y;personalizationDoodle.x=Personalize.resolutionConvert(newX,this.resolution,144);personalizationDoodle.y=Personalize.resolutionConvert(newY,this.resolution,144);personalizationDoodle.z=parseFloat(Personalize.doodleZIndex++);personalizationDoodle.dropArea=this;personalizationDoodle.trayDoodle=trayDoodle;this.panel.doodles[personalizePersonalize.lastPanelDoodleId]=personalizationDoodle;var panelDoodle=TP.extendObject(new personalizeDoodle(personalizationDoodle,this.panel),new personalizeDoodleGlobal());panelDoodle.panelDoodleId=personalizePersonalize.lastPanelDoodleId++;this.doodles.push(panelDoodle);this.domElement.insert(panelDoodle.render(this.resolution,this.handlesContainer));setTimeout(panelDoodle.startEditing.bind(panelDoodle),50);}};var PersonalizeMonogramEditor=function(){};PersonalizeMonogramEditor.prototype={showPopup:function(){this.maskElement.style.height=document.viewport.getHeight()+'px';this.maskElement.onclick=this.outsideClick.bind(this);this.maskElement.setOpacity(0);this.maskElement.show();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.setStyle({border:'1px solid black'});this.domElement.show();this.domElement.setStyle({width:this.contentElement.getWidth()+'px'});var width=this.contentElement.getWidth();if(Personalize.isIe()||Personalize.ie8){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'});Event.observe(document,'keypress',this.keyDownHandler);},setPosition:function(){var leftPos=(document.viewport.getWidth()-this.domElement.getWidth())/2;var topPos=(document.viewport.getHeight()-this.domElement.getHeight())/2;leftPos-=50;topPos-=50;this.domElement.setStyle({left:leftPos+'px',top:topPos+'px'});}};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.currentPanel=null;this.saveDialog=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));}
this.reviewStepCheckWarning=$('reviewStepCheckWarning');this.warningTextCheckboxIds={1:'reviewStepDateCheck',2:'reviewStepNamesCheck'};for(var checkboxId in this.warningTextCheckboxIds){var checkboxStringId=this.warningTextCheckboxIds[checkboxId];Event.observe(checkboxStringId,'click',this.updateWarningTextStyle.bind(this,$(checkboxStringId+'Label')));}},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];if(Personalize.isMongoPersonalization()){var parameters=Personalize.personalization.mongoId;}else{var parameters=Personalize.personalization.id;}
this.personalizedPanelUrl=Personalize.hosts.images+'personalization/panel/'+parameters+'/productPanelId/'+productPanel.id;this.shadow=(!(Personalize.product.isMintTin||Personalize.product.isMagnet||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($('reviewStepDateCheck').checked&&$('reviewStepNamesCheck').checked){this.currentPanel.approvalTimestamp=(new Date().getTime());this.currentPanel.approved=true;}else{this.reviewStepCheckWarning.show();for(var checkboxId in this.warningTextCheckboxIds){var checkboxStringId=this.warningTextCheckboxIds[checkboxId];$(checkboxStringId+'Label').setStyle({color:$(checkboxStringId).checked?'':'red'});}}},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;}}},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.resetWarningTexts();}else{this.panelApprovalTitleElement.update('');this.panelApprovalTitleElement.addClassName('approvedText');this.panelApprovalTitleElement.removeClassName('notApprovedText');this.bringBackWarningTexts();}},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'}));Personalize.personalization.savedStep=this.element.id;if(!Personalize.member){this.login(true,name,createNew);return;}else{Personalize.services.savePersonalization(name,this.saveComplete.bind(this),createNew);}},cancelSave:function(){if(this.saveDialog)
this.saveDialog.hidePopup();},login:function(showSave,title,createNew){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;},createNew);},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;},activate:function(fromNext){$('saveButton').show();$('saveButton_bottom').show();$('saveButton').stopObserving('click');$('saveButton_bottom_envelopes').stopObserving('click');this.btnSaveHandler=this.save.bind(this);$('saveButton').observe('click',this.btnSaveHandler);$('saveButton_bottom_envelopes').observe('click',this.btnSaveHandler);if(fromNext){Personalize.services.savePersonalization(Personalize.personalization.name,this.commonActivate.bind(this,fromNext),false);}else{this.commonActivate(fromNext);}
Personalize.trackPageview('/personalize/Review');},clearInitials:function(){for(var i=0;i<this.panels.length;i++){this.panels[i].approved=false;}},commonActivate:function(fromNext){if(fromNext){this.clearInitials();}
var val=Personalize.personalization.instructions;if(val==null)val='';this.specialInstructions.setValue(val);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();if(Personalize.saveLogin){Personalize.saveLogin=0;setTimeout(function(){if(Personalize.activeStep.save()){Personalize.activeStep.saveComplete();}},1000);}},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();},updateWarningTextStyle:function(textObject){textObject.setStyle({color:''});},resetWarningTexts:function(){this.reviewStepCheckWarning.hide();for(var checkboxId in this.warningTextCheckboxIds){var checkboxStringId=this.warningTextCheckboxIds[checkboxId];this.updateWarningTextStyle($(checkboxStringId+'Label'));$(checkboxStringId).checked=false;}},bringBackWarningTexts:function(){this.reviewStepCheckWarning.hide();for(var checkboxId in this.warningTextCheckboxIds){var checkboxStringId=this.warningTextCheckboxIds[checkboxId];this.updateWarningTextStyle($(checkboxStringId+'Label'));$(checkboxStringId).checked=true;}}});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;this.saveDialog=null;},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+Personalize.product.color.id+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){var shadow;for(var idx in Personalize.personalization.panels){var item=Personalize.personalization.panels[idx];var personalizationPanelId=item.id;break;}
if(Personalize.product.isMintTin||Personalize.product.isMagnet){shadow=0;}else{shadow=1;}
if(Personalize.isMongoPersonalization()){var parameters=Personalize.personalization.mongoId;}else{var parameters=Personalize.personalization.id;}
var imgsrc=Personalize.hosts.images+'personalization/panel/'+parameters+'/productPanelId/'+item.panelId+'/width/'+width+'/height/'+height+'/shadow/'+shadow+'.jpg?at='+Personalize.personalization.timestamp;return imgsrc;},activate:function(){$('saveButton').show();$('saveButton_bottom_envelopes').show();$('saveButton').stopObserving('click');$('saveButton_bottom_envelopes').stopObserving('click');this.btnSaveHandler=this.save.bind(this);$('saveButton').observe('click',this.btnSaveHandler);$('saveButton_bottom_envelopes').observe('click',this.btnSaveHandler);$('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;var defaultEnvelope=Personalize.envelopes[this.defaultEnvelopes["selected"][colorId].envelopeId];if(defaultEnvelope&&defaultEnvelope.sizeId&&Personalize.product.color.id==colorId){if(defaultEnvelope.sizeId=="Square"){$('additionalPostageWarning').show();}else{$('additionalPostageWarning').hide();}}
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;}
var linerSuffix=Personalize.product.color.id+this.selectedEnvelopes["mailing"].id;$('linerSuffix').value=linerSuffix;if(typeof this.prettySelects["liner"][linerSuffix]!=="undefined"){$(this.prettySelects["liner"][linerSuffix].container).show();this.visiblePrettySelects["liner"][linerSuffix]=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();if(Personalize.saveLogin){Personalize.saveLogin=0;setTimeout(function(){if(Personalize.activeStep.save()){Personalize.activeStep.saveComplete();}},1000);}
Personalize.trackPageview('/personalize/Envelopes');},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=mailingEnvelope.praColors;var availablePraColors=this.editors["pra_control"].getAvailablePraFontColors();var intersectingColorsCount=0;for(var idx in availablePraColors){if(typeof mailingEnvelope.praColors[idx]!=='undefined'){intersectingColorsCount++;}}
var selectablePraColors=new Array();var firstDefault=null;var lastColorSelectedAvailable=false;for(var idxPraFontColor in mailingEnvelope.praColors){var fontColor=mailingEnvelope.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;}
if(praEnvelope==mailingEnvelope){praEnvelopeImage.update(praEnvelope,false,false,lines);}else{praEnvelopeImage.update(praEnvelope,false,false,false);}
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,"");var defaultEnvelope=Personalize.envelopes[realId];if(defaultEnvelope&&defaultEnvelope.sizeId){if(defaultEnvelope.sizeId=="Square"){$('additionalPostageWarning').show();}else{$('additionalPostageWarning').hide();}}
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();}},save:function(){if(!this.validate()){return false;}
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'}));Personalize.personalization.savedStep=this.element.id;if(!Personalize.member){this.login(true,name,createNew);return;}else{Personalize.services.savePersonalization(name,this.saveComplete.bind(this),createNew);}},cancelSave:function(){if(this.saveDialog)
this.saveDialog.hidePopup();},login:function(showSave,title,createNew){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;},createNew);},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;}});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=Personalize.quantity;if(qty==null||qty==0){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(mailingEnvelope.price).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();},getFirstFontColorId:function(){for(var fontColorId in this.envelope.praColors){return fontColorId;}
return 978;},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'))?$F('praFontColorId'):this.getFirstFontColorId();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:'<div style="margin:20px;"><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></div>',TP_PHOTOCARD_HELP:'<div style="margin:20px;"><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 30 photos. If you already have 30 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></div>',TPC_TEXTCARD_HELP:'<div style="margin:20px;"><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></div>',TP_TEXTCARD_HELP:'<div style="margin:20px;"><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></div>',TPC_LOGOCARD_HELP:'<div style="margin:20px;"><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></div>',TP_PREVIEW_HELP:'<div style = "margin: 20px;"><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="http://www.tinyprints.com/orderinfo.htm" target="_blank">Frequently Asked Questions</a> section for more information.</li></ul></div>',GC_PREVIEW_HELP:'<div style = "margin: 20px;"><ul class="helpText" style="list-style-type: disc;"><li>Please review your order carefully before finalizing it. This product will be printed without any additional editing by the Tiny Prints staff.</li><li>Read our <a href="http://www.tinyprints.com/orderinfo.htm#greeting-cards" target="_blank">Frequently Asked Questions</a> for more information.</li></ul></div>',TP_TRIMOPTIONS_HELP_CONTENT:'<div style = "margin: 20px;">Trim options allow you to customize the edges of your cards</div>',TP_TRIMOPTIONS_HELP_TITLE:'<div style = "margin: 2px;">Trim Options</div>',TP_DOODLES_HELP_TITLE:'<div style = "margin: 2px;">Add Embellishments!</div>',TP_DOODLES_HELP_CONTENT:'<div style = "margin: 20px;"><ul style = "list-style-type:circle;"><li>Drag and drop anywhere you like</li>\
      <li>Resize or remove</li><li>Layer in front of or behind your personalized text</li></ul></div>',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>',GC_HELP:'<div style="margin:20px;"><ul class="helpText"><li>To edit or add text, click on the text area(s) on the card.      </li><li>Hold your mouse over the main text area to see a link for Suggested Messages. Click this link to view our Message Library, where you can browse, filter or search for the perfect message.      </li><li>You can add photos to the tray by clicking the "Add Photo" button.      </li><li>The photo tray can hold up to 30 photos. If you already have 30 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>Visit the <a href="http://www.tinyprints.com/orderinfo.htm#greeting-cards" target="_blank">Frequently Asked Questions</a> section for more information.</li></ul></div>',WPD_HOSTING_HELP:'In accordance with etiquette standards, we\'ll arrange your text differently depending on who is hosting your event. You\'ll have the option to edit the text later in the personalization process.',WPD_FORMAL_HELP:'For formal weddings, we spell out the date and time. For casual weddings, we use numbers to indicate the date and time.',WPD_CASUAL_HELP:'For formal weddings, we spell out the date and time. For casual weddings, we use numbers to indicate the date and time.',WPD_TEXTBOX_HELP:'You can perform font, size, color and alignment changes within the text boxes on the right. When you click into one of the text boxes, the corresponding area of your design will be highlighted. If more than one text box is highlighted, the changes will be applied to multiple areas.',WPD_DOODLE_HELP:'To add Design Accents to your card or invitation, drag your favorite icon onto the design and drop them into place. You can then rotate, mirror or move your Design Accents using the same click and drag method. To resize a Design Accent, click at the bottom right hand corner of the icon\'s outline and drag to increase or reduce the size. To remove a Design Accent, click on the red X next to the icon.',WPD_LAYOUT_HELP:'You have the option of changing the layout of your design. To select a different layout, click on the thumbnails on the right to see the new layout populated in the preview screen.',WPD_PHOTO_HELP:'<ul class="helpText"><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></ul>'};var TP={CHAR_CODE_ENTER:13,PAPER_TYPE_STUDIO_BASIC:18,STORE_NAME_TP:'tp',STORE_NAME_WPD:'wpd',STORE_NAME_TREAT:'gc',STORE_ID_TP:1,STORE_ID_WPD:2,STORE_ID_TREAT:3,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();}}}}},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;},deleteCookie:function(name,path,domain){if(TP.getCookie(name))document.cookie=name+'='+
((path)?';path='+path:'')+
((domain)?';domain='+domain:'')+';expires=Thu, 01-Jan-1970 00:00:01 GMT';},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){try{return string.substring(0,1).toUpperCase()+string.substring(1);}catch(e){return'';}},ucWords:function(string){try{return string.replace(/(^|\s)([a-z])/g,function(m,p1,p2){return p1+p2.toUpperCase();});}catch(e){return'';}},trim:function(string){try{return string.replace(/^\s+|\s+$/g,"");}catch(e){return'';}},sqlTimeStringToDate:function(sqlTimeString){var date_array=sqlTimeString.split(" ");var yyyymmdd_array=date_array[0].split("-");try{var hhmmss_array=date_array[1].split(":");}catch(e){var hhmmss_array=[0,0,0];}
return new Date(yyyymmdd_array[0],yyyymmdd_array[1]-1,yyyymmdd_array[2],hhmmss_array[0],hhmmss_array[1],hhmmss_array[2],0);},Console:{init:function(){this.consoleEnabled=false;},enable:function(){this.consoleEnabled=true;this.setupConsole();},disable:function(){this.consoleEnabled=false;},setupConsole:function(){if(this.consoleEnabled){var id='tpconsole';if($(id)==null){this.spacer='&nbsp;&nbsp;&nbsp;';this.tpConsoleDiv=new Element('div',{'id':id});$(document.body).insert(this.tpConsoleDiv);this.tpConsoleClose=new Element('a').update('X');this.tpConsoleClose.href='javascript: TP.Console.closeConsole()';this.tpConsoleDiv.insert(this.tpConsoleClose);this.tpConsoleClear=new Element('a').update('clear');this.tpConsoleClear.href='javascript: TP.Console.clearConsole()';this.tpConsoleDiv.insert(this.tpConsoleClear);this.tpConsoleToggle=new Element('a').update('hide');this.tpConsoleToggle.href='javascript: TP.Console.toggleConsole()';this.tpConsoleDiv.insert(this.tpConsoleToggle);this.tpConsoleSpan=new Element('span');this.tpConsoleDiv.insert(this.tpConsoleSpan);}}},closeConsole:function(){this.tpConsoleDiv.hide();},showConsole:function(){if(this.consoleEnabled){this.tpConsoleSpan.show();this.tpConsoleDiv.show();}},logObject:function(obj,objKey,level){var cont='';if(objKey){cont+=objKey+' : ';}
for(j=0;j<level;j++){cont+=this.spacer;}
level++;for(key in obj){if(typeof obj[key]==="function"){continue;}
cont+='<br/>';for(j=0;j<level;j++){cont+=this.spacer;}
if(typeof obj[key]==="object"){cont+=this.logObject(obj[key],key,level+1);}else{cont+=key+' : '+obj[key];}}
return cont;},log:function(){if(this.consoleEnabled){var content=this.tpConsoleSpan.innerHTML;content+='<br/>';for(var i=0;i<arguments.length;i++){if(typeof arguments[i]==="object"){content+=this.logObject(arguments[i],null,1)+'<br/>';}else{content+=arguments[i];content+=this.spacer;}}
this.tpConsoleSpan.update(content);this.showConsole();}},clearConsole:function(){this.tpConsoleDiv.remove();this.setupConsole();},toggleConsole:function(){if(this.tpConsoleSpan.visible()){this.tpConsoleSpan.hide();this.tpConsoleToggle.update('show');}else{this.tpConsoleSpan.show();this.tpConsoleToggle.update('hide');}},addLoadEvent:function(func){var oldonload=window.onload;if(typeof window.onload!='function'){window.onload=func;}else{window.onload=function(){if(oldonload){oldonload();}
func();}};}},checkValidDate:function(month,date,year){if(date<=0){return false;}
var isValid=true;month=parseInt(month);if(month==1||month==3||month==5||month==7||month==8||month==10||month==12){if(date>31){isValid=false;}}else if(month==4||month==6||month==9||month==11){if(date>30){isValid=false;}}else{if(((year%4==0)&&(year%100!=0))||(year%400==0)){if(date>29){isValid=false;}}else{if(date>28){isValid=false;}}}
return isValid;},init:function(){this.ie6=(window.external&&typeof window.XMLHttpRequest=='undefined');this.ie7=((navigator.appVersion.indexOf('MSIE 7.')==-1)?false:true);this.ie8=((navigator.appVersion.indexOf('MSIE 8.')==-1)?false:true);this.safari=(/Safari/.test(navigator.userAgent));if(typeof console!=='object'||typeof console.log!=='function'){window.console=TP.Console;window.console.init();}
if(typeof Array.prototype.indexOf==='undefined'){console.log('Needs Array.indexOf');Array.prototype.indexOf=function(obj){for(var i=0;i<this.length;i++){if(this[i]==obj)
return i;}
return-1;}}
TP.Site.EventManager.initEvents();},enableConsole:function(){if(this.isIe()){TP.Console.enable();}},isIe:function(){return(this.ie6||this.ie7||this.ie8);},arrayIntersection:function(array1,array2){var intersectionArray=[];for(var i=0;i<array1.length;i++){if(array2.indexOf(array1[i])!=-1){intersectionArray.push(array1[i]);}}
return intersectionArray;},bin2dec:function(x){if((/[^0-1]/g.test(x))||x==""){return null;}
return parseFloat(x,2);},dec2bin:function(x){if((/[^0-9]/g.test(x))||x==""){return null;}
x=parseFloat(x);return x.toString(2);},arrayMultiIntersection:function(arraySet){var multiIntersection=[];var lookupTable={};var rowCt=arraySet.length;var colCt,pid;for(var i=0;i<rowCt;i++){colCt=arraySet[i].length;for(var j=0;j<colCt;j++){pid=arraySet[i][j];if(!lookupTable[pid]){lookupTable[pid]=[i,1];}else{if(i!=lookupTable[pid][0]){lookupTable[pid][0]=i;lookupTable[pid][1]++;if(lookupTable[pid][1]==rowCt){multiIntersection.push(pid);}}}}}
if(rowCt==1){for(var pId in lookupTable){multiIntersection.push(pId);}}
return multiIntersection;},center:function(element,centerX,centerY){var viewportWidth=document.viewport.getWidth();var viewportHeight=document.viewport.getHeight();if(centerY){if((viewportHeight/2-element.getHeight()/2)<0){element.style.top='0px';}else{element.style.top=viewportHeight/2-element.getHeight()/2+'px';}}
if(centerX){if((viewportWidth/2-element.getWidth()/2)<0){element.style.left='0px';}else{element.style.left=viewportWidth/2-element.getWidth()/2+'px';}}},cookieCheck:function(){var phpSessId=TP.getCookie('PHPSESSID');if(!phpSessId||phpSessId.length<10){alert('Please enable your browser\'s cookies to continue. Need help? Get instructions');window.location='http://answers.tinyprints.com/app/answers/detail/a_id/267/kw/browser';}},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"},{string:navigator.vendor,subString:"Google",identity:"Chrome"},{string:navigator.vendor,subString:"Apple",identity:"Firefox"},{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.5'},{os:'Mac',browser:'Firefox',version:'3.6'},{os:'Mac',browser:'Firefox',version:'4.0'},{os:'Mac',browser:'Firefox',version:'5.0'},{os:'Mac',browser:'Firefox',version:'6.0'},{os:'Mac',browser:'Chrome',version:'5'},{os:'Mac',browser:'Chrome',version:'6'},{os:'Mac',browser:'Chrome',version:'7'},{os:'Mac',browser:'Chrome',version:'8'},{os:'Mac',browser:'Chrome',version:'9'},{os:'Mac',browser:'Chrome',version:'10.0'},{os:'Mac',browser:'Chrome',version:'11.0'},{os:'Mac',browser:'Chrome',version:'12.0'},{os:'Mac',browser:'Chrome',version:'13.0'},{os:'Windows/XP',browser:'Firefox',version:'3.5'},{os:'Windows/XP',browser:'Firefox',version:'3.6'},{os:'Windows/XP',browser:'Firefox',version:'4.0'},{os:'Windows/XP',browser:'Firefox',version:'5.0'},{os:'Windows/XP',browser:'Firefox',version:'6.0'},{os:'Windows/XP',browser:'Chrome',version:'5'},{os:'Windows/XP',browser:'Chrome',version:'6'},{os:'Windows/XP',browser:'Chrome',version:'7'},{os:'Windows/XP',browser:'Chrome',version:'8'},{os:'Windows/XP',browser:'Chrome',version:'9'},{os:'Windows/XP',browser:'Chrome',version:'10.0'},{os:'Windows/XP',browser:'Chrome',version:'11.0'},{os:'Windows/XP',browser:'Chrome',version:'12.0'},{os:'Windows/XP',browser:'Chrome',version:'13.0'},{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.6'},{os:'Windows/Vista',browser:'Firefox',version:'4.0'},{os:'Windows/Vista',browser:'Firefox',version:'5.0'},{os:'Windows/Vista',browser:'Firefox',version:'6.0'},{os:'Windows/Vista',browser:'Chrome',version:'5'},{os:'Windows/Vista',browser:'Chrome',version:'6'},{os:'Windows/Vista',browser:'Chrome',version:'7'},{os:'Windows/Vista',browser:'Chrome',version:'8'},{os:'Windows/Vista',browser:'Chrome',version:'9'},{os:'Windows/Vista',browser:'Chrome',version:'10.0'},{os:'Windows/Vista',browser:'Chrome',version:'11.0'},{os:'Windows/Vista',browser:'Chrome',version:'12.0'},{os:'Windows/Vista',browser:'Chrome',version:'13.0'},{os:'Windows/Vista',browser:'Explorer',version:'7'},{os:'Windows/Vista',browser:'Explorer',version:'8'},{os:'Linux',browser:'Firefox',version:'3.5'},{os:'Linux',browser:'Firefox',version:'3.6'},{os:'Linux',browser:'Firefox',version:'4.0'},{os:'Linux',browser:'Firefox',version:'5.0'},{os:'Linux',browser:'Firefox',version:'6.0'},{os:'Linux',browser:'Chrome',version:'5'},{os:'Linux',browser:'Chrome',version:'6'},{os:'Linux',browser:'Chrome',version:'7'},{os:'Linux',browser:'Chrome',version:'8'},{os:'Linux',browser:'Chrome',version:'9'},{os:'Linux',browser:'Chrome',version:'10.0'},{os:'Linux',browser:'Chrome',version:'11.0'},{os:'Linux',browser:'Chrome',version:'12.0'},{os:'Linux',browser:'Chrome',version:'13.0'},{os:'Windows/7',browser:'Explorer',version:'7'},{os:'Windows/7',browser:'Explorer',version:'8'},{os:'Windows/7',browser:'Chrome',version:'5'},{os:'Windows/7',browser:'Chrome',version:'6'},{os:'Windows/7',browser:'Chrome',version:'7'},{os:'Windows/7',browser:'Chrome',version:'8'},{os:'Windows/7',browser:'Chrome',version:'9'},{os:'Windows/7',browser:'Chrome',version:'10.0'},{os:'Windows/7',browser:'Chrome',version:'11.0'},{os:'Windows/7',browser:'Chrome',version:'12.0'},{os:'Windows/7',browser:'Chrome',version:'13.0'},{os:'Windows/7',browser:'Firefox',version:'3.5'},{os:'Windows/7',browser:'Firefox',version:'3.6'},{os:'Windows/7',browser:'Firefox',version:'4.0'},{os:'Windows/7',browser:'Firefox',version:'5.0'},{os:'Windows/7',browser:'Firefox',version:'6.0'}],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;}
else if(TP.BrowserDetect.browser=='Firefox'){if(parseFloat(TP.BrowserDetect.version)>=3.5){this.supported=true;break;}}
else if(TP.BrowserDetect.browser=='Chrome'){if(parseFloat(TP.BrowserDetect.version)>=5){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.cookieCheck();}}};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));}}}
if(typeof Event.wheel==='undefined'){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);}}
TP.Site={};TP.Site.Widgets={};TP.Site.Widgets.Digital={};TP.Site.Data={};TP.Site.EventManager={eventHandlers:{},requiredEvents:[],providedEvents:[],initEvents:function(){for(var dataStoreName in TP.Site.Data){var dataStore=TP.Site.Data[dataStoreName];this.providedEvents=this.providedEvents.concat(dataStore.providedEvents);}
this.populateEvents(TP.Site.Widgets);var requiredEventsLength=this.requiredEvents.length;for(var eventIdx=0;eventIdx<requiredEventsLength;eventIdx++){var event=this.requiredEvents[eventIdx];if(typeof event==='undefined'){continue;}
if(this.providedEvents.indexOf(event)==-1){throw('Event '+event+' is required, but not provided by any loaded widget');}
if(!this.eventHandlers[event.toLowerCase()]){this.eventHandlers[event.toLowerCase()]=[];}}},populateEvents:function(Widgets){for(var widgetName in Widgets){if(widgetName=='Base'){continue;}else if(typeof Widgets[widgetName]=='object'){this.populateEvents(Widgets[widgetName]);continue;}
var widget=new Widgets[widgetName]({},true);this.requiredEvents=this.requiredEvents.concat(widget.requiredEvents);this.providedEvents=this.providedEvents.concat(widget.providedEvents);}},trigger:function(event){event=event.toLowerCase();var args=[];for(var i=1;i<arguments.length;i++){args.push(arguments[i]);}
for(var handlerId=0;handlerId<this.eventHandlers[event].length;handlerId++){var handler=this.eventHandlers[event][handlerId];handler.apply(handler,args);}},observe:function(event,handler){try{event=event.toLowerCase();this.eventHandlers[event].push(handler);}catch(e){throw('Unknown Event Handler : '+event);}},stopObserving:function(event,handler){event=event.toLowerCase();if(this.eventHandlers[event]){if(!handler){this.eventHandlers[event]=[];}else{}}}};TP.Site.Widgets.Base=Class.create({requiredEvents:[],providedEvents:[],initialize:function(options,probe){if(!probe){this.init(options);}},observe:function(){},trigger:function(){},init:function(){console.log('Base Init');}});TP.Site.Widgets.LiveChatAsk=Class.create(TP.Site.Widgets.Base,{init:function(options)
{this.options={'id':'liveChatAsk','dParent':$$('body')[0],'duration':90000,'lpWidth':475,'lpHeight':400,'isWpd':false,'title':'Have a Question?','desc':'Our customer service specialists are available to answer any questions you may have about our products, personalize process or ordering.','btnNoText':'no thanks','btnYesText':'Chat Now','logoPath':'','chatNowBtnPath':'','serviceCheckPath':'/liveperson-status.html','wpdNeedHelpImgPath':'/images/LivePerson/need_help_on.gif','wpdCloseOnImgPath':'/images/LivePerson/close_on.gif','lpOpenUrl':'http://server.iad.liveperson.net/hc/70313913/?cmd=file&amp;file=visitorWantsToChat&amp;site=70313913'};this.options=Object.extend(this.options,options);this.dEl=new Element('div',{'id':this.options.id});this.options.dParent.insert(this.dEl);this.dEl.hide();this.render();},render:function()
{if(this.options.isWpd){var dBtnYes=new Element('a',{'href':'#'});this.dEl.insert(dBtnYes);var dBtnYesImg=new Element('img',{'src':this.options.wpdNeedHelpImgPath});dBtnYes.insert(dBtnYesImg);var dBtnNo=new Element('a',{'href':'#'});this.dEl.insert(dBtnNo);var dBtnNoImg=new Element('img',{'src':this.options.wpdCloseOnImgPath,'class':'down'});dBtnNo.insert(dBtnNoImg);}else{var dBd=new Element('div',{'class':'bd'});this.dEl.insert(dBd);var dLogo=new Element('img',{'class':'logo','src':this.options.logoPath});dBd.insert(dLogo);var dH2=new Element('h2').update(this.options.title);dBd.insert(dH2);var dP=new Element('p').update(this.options.desc);dBd.insert(dP);var dBtnSet=new Element('div',{'class':'btn-set'});dBd.insert(dBtnSet);var dBtnNo=new Element('a',{'href':'#'}).update(this.options.btnNoText);dBtnSet.insert(dBtnNo);var dBtnYes=new Element('a',{'href':'#'});dBtnSet.insert(dBtnYes);var dBtnChatImg=new Element('input',{'type':'button','class':'tp large btn','value':'chat now'});dBtnYes.insert(dBtnChatImg);}
dBtnYes.observe('click',this.onClickChat.bind(this));dBtnNo.observe('click',this.onClickNo.bind(this));this.toCenter(this.dEl);},onClickNo:function(e)
{Event.stop(e);this.hide();},onClickChat:function(e)
{Event.stop(e);this.hide();var lpScreenX=(window.screenX)?window.screenX:window.screenLeft;var lpScreenY=(window.screenY)?window.screenY:window.screenTop;window.open(this.options.lpOpenUrl,'liveChatWindow','width='+this.options.lpWidth+',height='+this.options.lpHeight+',top='+lpScreenY+',left='+lpScreenX+',resizable=yes');},onResize:function(e)
{this.toCenter(this.dEl);},showChatAsking:function()
{new Ajax.Request(this.options.serviceCheckPath,{method:'get',onSuccess:function(transport){if(transport.responseText=="1"){this.show();}}.bind(this)});},show:function()
{this.toCenter(this.dEl);this.dEl.show();this.dEl.setStyle({'display':'block'});this.onResizeBound=this.onResize.bind(this);Element.observe(window,'resize',this.onResizeBound);},hide:function()
{Element.stopObserving(window,'resize',this.onResizeBound);this.dEl.hide();},toCenter:function(element)
{var x=(this.options.dParent.getWidth()-element.getWidth())/2;var y=(document.viewport.getHeight()-element.getHeight())/2;element.setStyle({'left':x+'px','top':y+'px'});}});
