var Prototype={Version:'1.7',Browser:(function(){var ua=navigator.userAgent;var isOpera=Object.prototype.toString.call(window.opera)=='[object Opera]';return{IE:!!window.attachEvent&&!isOpera,IE9:('documentMode'in document)&&document.documentMode==9,IE10:('documentMode'in document)&&document.documentMode==10,Opera:isOpera,WebKit:ua.indexOf('AppleWebKit/')>-1,Gecko:ua.indexOf('Gecko')>-1&&ua.indexOf('KHTML')===-1,MobileSafari:/Apple.*Mobile/.test(ua)}})(),BrowserFeatures:{XPath:!!document.evaluate,SelectorsAPI:!!document.querySelector,ElementExtensions:(function(){var constructor=window.Element||window.HTMLElement;return!!(constructor&&constructor.prototype);})(),SpecificElementExtensions:(function(){if(typeof window.HTMLDivElement!=='undefined') return true;var div=document.createElement('div'),form=document.createElement('form'),isSupported=false;if(div['__proto__']&&(div['__proto__']!==form['__proto__'])){isSupported=true;} div=form=null;return isSupported;})()},jsInlineEvents:['onabort','onactivate','onafterprint','onafterscriptexecute','onafterupdate','onbeforeactivate','onbeforecopy','onbeforecut','onbeforedeactivate','onbeforeeditfocus','onbeforepaste','onbeforeprint','onbeforescriptexecute','onbeforeunload','onbeforeupdate','onbegin','onblur','onbounce','oncancel','oncanplay','oncanplaythrough','oncellchange','onchange','onclick','onclose','oncontextmenu','oncontrolselect','oncopy','onctextmenu','oncuechange','oncut','ondataavailable','ondatasetchanged','ondatasetcomplete','ondblclick','ondeactivate','ondrag','ondragdrop','ondragend','ondragenter','ondragleave','ondragover','ondragstart','ondrop','ondurationchange','onemptied','onend','onended','onerror','onerrorupdate','onfilterchange','onfinish','onfocus','onfocusin','onfocusout','onhashchange','onhelp','oninput','oninvalid','onkeydown','onkeypress','onkeyup','onlayoutcomplete','onload','onloadeddata','onloadedmetadata','onloadstart','onlosecapture','onmediacomplete','onmediaerror','onmessage','onmousedown','onmouseenter','onmouseleave','onmousemove','onmouseout','onmouseover','onmouseup','onmousewheel','onmove','onmoveend','onmovestart','onoffline','ononline','onoutofsync','onpagehide','onpageshow','onpaste','onpause','onplay','onplaying','onpopstate','onprogress','onpropertychange','onratechange','onreadystatechange','onredo','onrepeat','onreset','onresize','onresizeend','onresizestart','onresume','onreverse','onrowdelete','onrowexit','onrowinserted','onrowsenter','onscroll','onsearch','onseek','onseeked','onseeking','onselect','onselectionchange','onselectstart','onshow','onstalled','onstart','onstop','onstorage','onsubmit','onsuspend','onsyncrestored','ontimeerror','ontimeupdate','ontoggle','ontouchcancel','ontouchend','ontouchmove','ontouchstart','ontrackchange','onundo','onunload','onurlflip','onvolumechange','onwaiting','onwheel'],ScriptFragment:']*>([\\S\\s]*?)<\/script>|prompt\s*[(]|alert\s*[(]|',JSONFilter:/^\/\*-secure-([\s\S]*)\*\/\s*$/,emptyFunction:function(){},K:function(x){return x}};if(Prototype.Browser.MobileSafari) Prototype.BrowserFeatures.SpecificElementExtensions=false;NodeList.prototype.filter=Array.prototype.filter;var Abstract={};var Try={these:function(){var returnValue;for(var i=0,length=arguments.length;i0){if(match=source.match(pattern)){result+=source.slice(0,match.index);result+=String.interpret(replacement(match));source=source.slice(match.index+match[0].length);}else{result+=source,source='';}} return result;} function sub(pattern,replacement,count){replacement=prepareReplacement(replacement);count=Object.isUndefined(count)?1:count;return this.gsub(pattern,function(match){if(--count<0)return match[0];return replacement(match);});} function scan(pattern,iterator){this.gsub(pattern,iterator);return String(this);} function truncate(length,truncation){length=length||30;truncation=Object.isUndefined(truncation)?'...':truncation;return this.length>length?this.slice(0,length-truncation.length)+truncation:String(this);} function strip(){return this.replace(/^\s+/,'').replace(/\s+$/,'');} function stripTags(separator){return this.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi,separator||'');} function stripScripts(){return this.replace(new RegExp(Prototype.ScriptFragment,'img'),'');} function stripEvents(){return this.replace(new RegExp(Prototype.jsInlineEvents.join('|'),'img'),'');} function extractScripts(){var matchAll=new RegExp(Prototype.ScriptFragment,'img'),matchOne=new RegExp(Prototype.ScriptFragment,'im');return(this.match(matchAll)||[]).map(function(scriptTag){return(scriptTag.match(matchOne)||['',''])[1];});} function evalScripts(){return this.extractScripts().map(function(script){return eval(script)});} function escapeHTML(){return this.replace(/&/g,'&').replace(/&amp;/g,'&').replace(//g,'>');} function unescapeHTML(){return this.stripTags().replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');} function toQueryParams(separator){var match=this.strip().match(/([^?#]*)(#.*)?$/);if(!match)return{};return match[1].split(separator||'&').inject({},function(hash,pair){if((pair=pair.split('='))[0]){var key=decodeURIComponent(pair.shift()),value=pair.length>1?pair.join('='):pair[0];if(value!=undefined)try{value=decodeURIComponent(value)}catch(e){value=unescape(value)} if(key in hash){if(!Object.isArray(hash[key]))hash[key]=[hash[key]];hash[key].push(value);} else hash[key]=value;} return hash;});} function toArray(){return this.split('');} function succ(){return this.slice(0,this.length-1)+ String.fromCharCode(this.charCodeAt(this.length-1)+1);} function times(count){return count<1?'':new Array(count+1).join(this);} function camelize(){return this.replace(/-+(.)?/g,function(match,chr){return chr?chr.toUpperCase():'';});} function capitalize(){return this.charAt(0).toUpperCase()+this.substring(1).toLowerCase();} function underscore(){return this.replace(/::/g,'/').replace(/([A-Z]+)([A-Z][a-z])/g,'$1_$2').replace(/([a-z\d])([A-Z])/g,'$1_$2').replace(/-/g,'_').toLowerCase();} function dasherize(){return this.replace(/_/g,'-');} function inspect(useDoubleQuotes){var escapedString=this.replace(/[\x00-\x1f\\]/g,function(character){if(character in String.specialChar){return String.specialChar[character];} return'\\u00'+character.charCodeAt().toPaddedString(2,16);});if(useDoubleQuotes)return'"'+escapedString.replace(/"/g,'\\"')+'"';return"'"+escapedString.replace(/'/g,'\\\'')+"'";} function unfilterJSON(filter){return this.replace(filter||Prototype.JSONFilter,'$1');} function isJSON(){var str=this;if(str.blank())return false;str=str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@');str=str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');str=str.replace(/(?:^|:|,)(?:\s*\[)+/g,'');return(/^[\],:{}\s]*$/).test(str);} function evalJSON(sanitize){var json=this.unfilterJSON(),cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;if(cx.test(json)){json=json.replace(cx,function(a){return'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);});} try{if(!sanitize||json.isJSON())return eval('('+json+')');}catch(e){} throw new SyntaxError('Badly formed JSON string: '+this.inspect());} function parseJSON(){var json=this.unfilterJSON();return JSON.parse(json);} function include(pattern){return this.indexOf(pattern)>-1;} function startsWith(pattern){return this.lastIndexOf(pattern,0)===0;} function endsWith(pattern){var d=this.length-pattern.length;return d>=0&&this.indexOf(pattern,d)===d;} function empty(){return this=='';} function blank(){return /^\s*$/.test(this);} function interpolate(object,pattern){return new Template(this,pattern).evaluate(object);} return{gsub:gsub,sub:sub,scan:scan,truncate:truncate,strip:String.prototype.trim||strip,stripTags:stripTags,stripScripts:stripScripts,stripEvents:stripEvents,extractScripts:extractScripts,evalScripts:evalScripts,escapeHTML:escapeHTML,unescapeHTML:unescapeHTML,toQueryParams:toQueryParams,parseQuery:toQueryParams,toArray:toArray,succ:succ,times:times,camelize:camelize,capitalize:capitalize,underscore:underscore,dasherize:dasherize,inspect:inspect,unfilterJSON:unfilterJSON,isJSON:isJSON,evalJSON:NATIVE_JSON_PARSE_SUPPORT?parseJSON:evalJSON,include:include,startsWith:startsWith,endsWith:endsWith,empty:empty,blank:blank,interpolate:interpolate};})());var Template=Class.create({initialize:function(template,pattern){this.template=template.toString();this.pattern=pattern||Template.Pattern;},evaluate:function(object){if(object&&Object.isFunction(object.toTemplateReplacements)) object=object.toTemplateReplacements();return this.template.gsub(this.pattern,function(match){if(object==null)return(match[1]+'');var before=match[1]||'';if(before=='\\')return match[2];var ctx=object,expr=match[3],pattern=/^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;match=pattern.exec(expr);if(match==null)return before;while(match!=null){var comp=match[1].startsWith('[')?match[2].replace(/\\\\]/g,']'):match[1];ctx=ctx[comp];if(null==ctx||''==match[3])break;expr=expr.substring('['==match[3]?match[1].length:match[0].length);match=pattern.exec(expr);} return before+String.interpret(ctx);});}});Template.Pattern=/(^|.|\r|\n)(#\{(.*?)\})/;var $break={};var Enumerable=(function(){function each(iterator,context){var index=0;try{this._each(function(value){iterator.call(context,value,index++);});}catch(e){if(e!=$break)throw e;} return this;} function eachSlice(number,iterator,context){var index=-number,slices=[],array=this.toArray();if(number<1)return array;while((index+=number)=result) result=value;});return result;} function min(iterator,context){iterator=iterator||Prototype.K;var result;this.each(function(value,index){value=iterator.call(context,value,index);if(result==null||valueb?1:0;}).pluck('value');} function toArray(){return this.map();} function zip(){var iterator=Prototype.K,args=$A(arguments);if(Object.isFunction(args.last())) iterator=args.pop();var collections=[this].concat(args).map($A);return this.map(function(value,index){return iterator(collections.pluck(index));});} function size(){return this.toArray().length;} function inspect(){return'#';} return{each:each,eachSlice:eachSlice,all:all,every:all,any:any,some:any,collect:collect,map:collect,detect:detect,findAll:findAll,select:findAll,filter:findAll,grep:grep,include:include,member:include,inGroupsOf:inGroupsOf,inject:inject,invoke:invoke,max:max,min:min,partition:partition,pluck:pluck,reject:reject,sortBy:sortBy,toArray:toArray,zip:zip,size:size,inspect:inspect,find:detect};})();function $A(iterable){if(typeof window.Set!=='undefined'&&iterable instanceof window.Set){var arr=[];iterable.forEach(function(x){arr.push(x);});return arr;} if(!iterable)return[];if('toArray'in Object(iterable))return iterable.toArray();var length=iterable.length||0,results=new Array(length);while(length--)results[length]=iterable[length];return results;} function $w(string){if(!Object.isString(string))return[];string=string.strip();return string?string.split(/\s+/):[];} if(!Array.from){Array.from=$A;} (function(){var arrayProto=Array.prototype,slice=arrayProto.slice,_each=arrayProto.forEach;function each(iterator,context){for(var i=0,length=this.length>>>0;i>>0;if(length===0)return-1;i=Number(i);if(isNaN(i)){i=0;}else if(i!==0&&isFinite(i)){i=(i>0?1:-1)*Math.floor(Math.abs(i));} if(i>length)return-1;var k=i>=0?i:Math.max(length-Math.abs(i),0);for(;k>>0;if(length===0)return-1;if(!Object.isUndefined(i)){i=Number(i);if(isNaN(i)){i=0;}else if(i!==0&&isFinite(i)){i=(i>0?1:-1)*Math.floor(Math.abs(i));}}else{i=length;} var k=i>=0?Math.min(i,length-1):length-Math.abs(i);for(;k>=0;k--) if(k in array&&array[k]===item)return k;return-1;} function concat(_){var array=[],items=slice.call(arguments,0),item,n=0;items.unshift(this);for(var i=0,length=items.length;i>>0;i>>0;i>>0;i>>0;i';} function clone(){return new Hash(this);} return{initialize:initialize,_each:_each,set:set,get:get,unset:unset,toObject:toObject,toTemplateReplacements:toObject,keys:keys,values:values,index:index,merge:merge,update:update,toQueryString:toQueryString,inspect:inspect,toJSON:toObject,clone:clone};})());Hash.from=$H;Object.extend(Number.prototype,(function(){function toColorPart(){return this.toPaddedString(2,16);} function succ(){return this+1;} function times(iterator,context){$R(0,this,true).each(iterator,context);return this;} function toPaddedString(length,radix){var string=this.toString(radix||10);return'0'.times(length-string.length)+string;} function abs(){return Math.abs(this);} function round(){return Math.round(this);} function ceil(){return Math.ceil(this);} function floor(){return Math.floor(this);} return{toColorPart:toColorPart,succ:succ,times:times,toPaddedString:toPaddedString,abs:abs,round:round,ceil:ceil,floor:floor};})());function $R(start,end,exclusive){return new ObjectRange(start,end,exclusive);} var ObjectRange=Class.create(Enumerable,(function(){function initialize(start,end,exclusive){this.start=start;this.end=end;this.exclusive=exclusive;} function _each(iterator){var value=this.start;while(this.include(value)){iterator(value);value=value.succ();}} function include(value){if(value1&&!((readyState==4)&&this._complete)) this.respondToReadyState(this.transport.readyState);},setRequestHeaders:function(){var headers={'X-Requested-With':'XMLHttpRequest','X-Prototype-Version':Prototype.Version,'Accept':'text/javascript, text/html, application/xml, text/xml, */*'};if(this.method=='post'){headers['Content-type']=this.options.contentType+ (this.options.encoding?'; charset='+this.options.encoding:'');if(this.transport.overrideMimeType&&(navigator.userAgent.match(/Gecko\/(\d{4})/)||[0,2005])[1]<2005) headers['Connection']='close';} if(typeof this.options.requestHeaders=='object'){var extras=this.options.requestHeaders;if(Object.isFunction(extras.push)) for(var i=0,length=extras.length;i=200&&status<300)||status==304;},getStatus:function(){try{if(this.transport.status===1223)return 204;return this.transport.status||0;}catch(e){return 0}},respondToReadyState:function(readyState){var state=Ajax.Request.Events[readyState],response=new Ajax.Response(this);if(state=='Complete'){try{this._complete=true;(this.options['on'+response.status]||this.options['on'+(this.success()?'Success':'Failure')]||Prototype.emptyFunction)(response,response.headerJSON);}catch(e){this.dispatchException(e);} var contentType=response.getHeader('Content-type');if(this.options.evalJS=='force'||(this.options.evalJS&&this.isSameOrigin()&&contentType&&contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i))) this.evalResponse();} try{(this.options['on'+state]||Prototype.emptyFunction)(response,response.headerJSON);Ajax.Responders.dispatch('on'+state,this,response,response.headerJSON);}catch(e){this.dispatchException(e);} if(state=='Complete'){this.transport.onreadystatechange=Prototype.emptyFunction;}},isSameOrigin:function(){var m=this.url.match(/^\s*https?:\/\/[^\/]*/);return!m||(m[0]=='#{protocol}//#{domain}#{port}'.interpolate({protocol:location.protocol,domain:document.domain,port:location.port?':'+location.port:''}));},getHeader:function(name){try{return this.transport.getResponseHeader(name)||null;}catch(e){return null;}},evalResponse:function(){try{return eval((this.transport.responseText||'').unfilterJSON());}catch(e){this.dispatchException(e);}},dispatchException:function(exception){(this.options.onException||Prototype.emptyFunction)(this,exception);Ajax.Responders.dispatch('onException',this,exception);}});Ajax.Request.Events=['Uninitialized','Loading','Loaded','Interactive','Complete'];Ajax.Response=Class.create({initialize:function(request){this.request=request;var transport=this.transport=request.transport,readyState=this.readyState=transport.readyState;if((readyState>2&&!Prototype.Browser.IE)||readyState==4){this.status=this.getStatus();this.statusText=this.getStatusText();this.responseText=String.interpret(transport.responseText);this.headerJSON=this._getHeaderJSON();} if(readyState==4){var xml=transport.responseXML;this.responseXML=Object.isUndefined(xml)?null:xml;this.responseJSON=this._getResponseJSON();}},status:0,statusText:'',getStatus:Ajax.Request.prototype.getStatus,getStatusText:function(){try{return this.transport.statusText||'';}catch(e){return''}},getHeader:Ajax.Request.prototype.getHeader,getAllHeaders:function(){try{return this.getAllResponseHeaders();}catch(e){return null}},getResponseHeader:function(name){return this.transport.getResponseHeader(name);},getAllResponseHeaders:function(){return this.transport.getAllResponseHeaders();},_getHeaderJSON:function(){var json=this.getHeader('X-JSON');if(!json)return null;json=decodeURIComponent(escape(json));try{return json.evalJSON(this.request.options.sanitizeJSON||!this.request.isSameOrigin());}catch(e){this.request.dispatchException(e);}},_getResponseJSON:function(){var options=this.request.options;if(!options.evalJSON||(options.evalJSON!='force'&&!(this.getHeader('Content-type')||'').include('application/json'))||this.responseText.blank()) return null;try{return this.responseText.evalJSON(options.sanitizeJSON||!this.request.isSameOrigin());}catch(e){this.request.dispatchException(e);}}});Ajax.Updater=Class.create(Ajax.Request,{initialize:function($super,container,url,options){this.container={success:(container.success||container),failure:(container.failure||(container.success?null:container))};options=Object.clone(options);var onComplete=options.onComplete;options.onComplete=(function(response,json){this.updateContent(response.responseText);if(Object.isFunction(onComplete))onComplete(response,json);}).bind(this);$super(url,options);},updateContent:function(responseText){var receiver=this.container[this.success()?'success':'failure'],options=this.options;if(!options.evalScripts)responseText=responseText.stripScripts();if(receiver=$(receiver)){if(options.insertion){if(Object.isString(options.insertion)){var insertion={};insertion[options.insertion]=responseText;receiver.insert(insertion);} else options.insertion(receiver,responseText);} else receiver.update(responseText);}}});Ajax.PeriodicalUpdater=Class.create(Ajax.Base,{initialize:function($super,container,url,options){$super(options);this.onComplete=this.options.onComplete;this.frequency=(this.options.frequency||2);this.decay=(this.options.decay||1);this.updater={};this.container=container;this.url=url;this.start();},start:function(){this.options.onComplete=this.updateComplete.bind(this);this.onTimerEvent();},stop:function(){this.updater.options.onComplete=undefined;clearTimeout(this.timer);(this.onComplete||Prototype.emptyFunction).apply(this,arguments);},updateComplete:function(response){if(this.options.decay){this.decay=(response.responseText==this.lastText?this.decay*this.options.decay:1);this.lastText=response.responseText;} this.timer=this.onTimerEvent.bind(this).delay(this.decay*this.frequency);},onTimerEvent:function(){this.updater=new Ajax.Updater(this.container,this.url,this.options);}});function $(element){if(arguments.length>1){for(var i=0,elements=[],length=arguments.length;i');return el.tagName.toLowerCase()==='input'&&el.name==='x';} catch(err){return false;}})();var element=global.Element;global.Element=function(tagName,attributes){attributes=attributes||{};tagName=tagName.toLowerCase();var cache=Element.cache;if(HAS_EXTENDED_CREATE_ELEMENT_SYNTAX&&attributes.name){tagName='<'+tagName+' name="'+attributes.name+'">';delete attributes.name;return Element.writeAttribute(document.createElement(tagName),attributes);} if(!cache[tagName])cache[tagName]=Element.extend(document.createElement(tagName));var node=shouldUseCache(tagName,attributes)?cache[tagName].cloneNode(false):document.createElement(tagName);return Element.writeAttribute(node,attributes);};Object.extend(global.Element,element||{});if(element)global.Element.prototype=element.prototype;})(this);Element.idCounter=1;Element.cache={};Element._purgeElement=function(element){var uid=element._prototypeUID;if(uid){Element.stopObserving(element);element._prototypeUID=void 0;delete Element.Storage[uid];}} Element.Methods={visible:function(element){return $(element).style.display!='none';},toggle:function(element){element=$(element);Element[Element.visible(element)?'hide':'show'](element);return element;},hide:function(element){element=$(element);element.style.display='none';return element;},show:function(element){element=$(element);element.style.display='';return element;},remove:function(element){element=$(element);element.parentNode.removeChild(element);return element;},update:(function(){var SELECT_ELEMENT_INNERHTML_BUGGY=(function(){var el=document.createElement("select"),isBuggy=true;el.innerHTML="";if(el.options&&el.options[0]){isBuggy=el.options[0].nodeName.toUpperCase()!=="OPTION";} el=null;return isBuggy;})();var TABLE_ELEMENT_INNERHTML_BUGGY=(function(){try{var el=document.createElement("table");if(el&&el.tBodies){el.innerHTML="test";var isBuggy=typeof el.tBodies[0]=="undefined";el=null;return isBuggy;}}catch(e){return true;}})();var LINK_ELEMENT_INNERHTML_BUGGY=(function(){try{var el=document.createElement('div');el.innerHTML="";var isBuggy=(el.childNodes.length===0);el=null;return isBuggy;}catch(e){return true;}})();var ANY_INNERHTML_BUGGY=SELECT_ELEMENT_INNERHTML_BUGGY||TABLE_ELEMENT_INNERHTML_BUGGY||LINK_ELEMENT_INNERHTML_BUGGY;var SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING=(function(){var s=document.createElement("script"),isBuggy=false;try{s.appendChild(document.createTextNode(""));isBuggy=!s.firstChild||s.firstChild&&s.firstChild.nodeType!==3;}catch(e){isBuggy=true;} s=null;return isBuggy;})();function htmlEncode(str){return String(str).replace(/[^\w. ]/gi,function(c){return'&#'+c.charCodeAt(0)+';';});};function update(element,content){element=$(element);var purgeElement=Element._purgeElement;var descendants=element.getElementsByTagName('*'),i=descendants.length;while(i--)purgeElement(descendants[i]);if(content&&content.toElement) content=content.toElement();if(Object.isElement(content)) return element.update().insert(content);content=Object.toHTML(content);var tagName=element.tagName.toUpperCase();if(tagName==='SCRIPT'&&SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING){element.text=content;return element;} if(ANY_INNERHTML_BUGGY){if(tagName in Element._insertionTranslations.tags){while(element.firstChild){element.removeChild(element.firstChild);} Element._getContentFromAnonymousElement(tagName,content.stripScripts()).each(function(node){element.appendChild(node)});}else if(LINK_ELEMENT_INNERHTML_BUGGY&&Object.isString(content)&&content.indexOf('-1){while(element.firstChild){element.removeChild(element.firstChild);} var nodes=Element._getContentFromAnonymousElement(tagName,content.stripScripts(),true);nodes.each(function(node){element.appendChild(node)});} else{element.innerHTML=content.stripScripts();}}else{var isOldReportFormTitle=tagName==='H2'&&document.get&&document.get.p==='reports';element.innerHTML=isOldReportFormTitle?htmlEncode(content.stripScripts()):content.stripScripts();} content.innerText;return element;} return update;})(),replace:function(element,content){element=$(element);if(content&&content.toElement)content=content.toElement();else if(!Object.isElement(content)){content=Object.toHTML(content);var range=element.ownerDocument.createRange();range.selectNode(element);content.evalScripts.bind(content).p_defer();content=range.createContextualFragment(content.stripScripts());} element.parentNode.replaceChild(content,element);return element;},insert:function(element,insertions){element=$(element);if(Object.isString(insertions)||Object.isNumber(insertions)||Object.isElement(insertions)||(insertions&&(insertions.toElement||insertions.toHTML))) insertions={bottom:insertions};var content,insert,tagName,childNodes;for(var position in insertions){content=insertions[position];position=position.toLowerCase();insert=Element._insertionTranslations[position];if(content&&content.toElement)content=content.toElement();if(Object.isElement(content)){insert(element,content);continue;} content=Object.toHTML(content);tagName=((position=='before'||position=='after')?element.parentNode:element).tagName.toUpperCase();childNodes=Element._getContentFromAnonymousElement(tagName,content.stripScripts());if(position=='top'||position=='after')childNodes.reverse();childNodes.each(insert.curry(element));content.evalScripts.bind(content).p_defer();} return element;},wrap:function(element,wrapper,attributes){element=$(element);if(Object.isElement(wrapper)) $(wrapper).writeAttribute(attributes||{});else if(Object.isString(wrapper))wrapper=new Element(wrapper,attributes);else wrapper=new Element('div',wrapper);if(element.parentNode) element.parentNode.replaceChild(wrapper,element);wrapper.appendChild(element);return wrapper;},inspect:function(element){element=$(element);var result='<'+element.tagName.toLowerCase();$H({'id':'id','className':'class'}).each(function(pair){var property=pair.first(),attribute=pair.last(),value=(element[property]||'').toString();if(value)result+=' '+attribute+'='+value.inspect(true);});return result+'>';},recursivelyCollect:function(element,property,maximumLength){element=$(element);maximumLength=maximumLength||-1;var elements=[];while(element=element[property]){if(element.nodeType==1) elements.push(Element.extend(element));if(elements.length==maximumLength) break;} return elements;},ancestors:function(element){return Element.recursivelyCollect(element,'parentNode');},descendants:function(element){return Element.select(element,"*");},firstDescendant:function(element){element=$(element).firstChild;while(element&&element.nodeType!=1)element=element.nextSibling;return $(element);},immediateDescendants:function(element){var results=[],child=$(element).firstChild;while(child){if(child.nodeType===1){results.push(Element.extend(child));} child=child.nextSibling;} return results;},previousSiblings:function(element,maximumLength){return Element.recursivelyCollect(element,'previousSibling');},nextSiblings:function(element){return Element.recursivelyCollect(element,'nextSibling');},siblings:function(element){element=$(element);return Element.previousSiblings(element).reverse().concat(Element.nextSiblings(element));},match:function(element,selector){element=$(element);if(Object.isString(selector)) return Prototype.Selector.match(element,selector);return selector.match(element);},up:function(element,expression,index){element=$(element);if(arguments.length==1)return $(element.parentNode);var ancestors=Element.ancestors(element);return Object.isNumber(expression)?ancestors[expression]:Prototype.Selector.find(ancestors,expression,index);},down:function(element,expression,index){element=$(element);if(arguments.length==1)return Element.firstDescendant(element);return Object.isNumber(expression)?Element.descendants(element)[expression]:Element.select(element,expression)[index||0];},previous:function(element,expression,index){element=$(element);if(Object.isNumber(expression))index=expression,expression=false;if(!Object.isNumber(index))index=0;if(expression){return Prototype.Selector.find(element.previousSiblings(),expression,index);}else{return element.recursivelyCollect("previousSibling",index+1)[index];}},next:function(element,expression,index){element=$(element);if(Object.isNumber(expression))index=expression,expression=false;if(!Object.isNumber(index))index=0;if(expression){return Prototype.Selector.find(element.nextSiblings(),expression,index);}else{var maximumLength=Object.isNumber(index)?index+1:1;return element.recursivelyCollect("nextSibling",index+1)[index];}},select:function(element){element=$(element);var expressions=Array.prototype.slice.call(arguments,1).join(', ');return Prototype.Selector.select(expressions,element);},adjacent:function(element){element=$(element);var expressions=Array.prototype.slice.call(arguments,1).join(', ');return Prototype.Selector.select(expressions,element.parentNode).without(element);},identify:function(element){element=$(element);var id=Element.readAttribute(element,'id');if(id)return id;do{id='anonymous_element_'+Element.idCounter++}while($(id));Element.writeAttribute(element,'id',id);return id;},readAttribute:function(element,name){element=$(element);if(Prototype.Browser.IE){var t=Element._attributeTranslations.read;if(t.values[name])return t.values[name](element,name);if(t.names[name])name=t.names[name];if(name.include(':')){return(!element.attributes||!element.attributes[name])?null:element.attributes[name].value;}} return element.getAttribute(name);},writeAttribute:function(element,name,value){element=$(element);var attributes={},t=Element._attributeTranslations.write;if(typeof name=='object')attributes=name;else attributes[name]=Object.isUndefined(value)?true:value;for(var attr in attributes){name=t.names[attr]||attr;value=attributes[attr];if(t.values[attr])name=t.values[attr](element,value);if(value===false||value===null) element.removeAttribute(name);else if(value===true) element.setAttribute(name,name);else element.setAttribute(name,value);} return element;},getHeight:function(element){return Element.getDimensions(element).height;},getWidth:function(element){return Element.getDimensions(element).width;},classNames:function(element){return new Element.ClassNames(element);},hasClassName:function(element,className){if(!(element=$(element)))return;var elementClassName=element.className;return(elementClassName&&elementClassName.length>0&&(elementClassName==className||new RegExp("(^|\\s)"+className+"(\\s|$)").test(elementClassName)));},addClassName:function(element,className){if(!(element=$(element)))return;if(!Element.hasClassName(element,className)) element.className+=(element.className?' ':'')+className;return element;},removeClassName:function(element,className){if(!(element=$(element)))return;element.className=element.className.replace(new RegExp("(^|\\s+)"+className+"(\\s+|$)"),' ').strip();return element;},toggleClassName:function(element,className){if(!(element=$(element)))return;return Element[Element.hasClassName(element,className)?'removeClassName':'addClassName'](element,className);},cleanWhitespace:function(element){element=$(element);var node=element.firstChild;while(node){var nextNode=node.nextSibling;if(node.nodeType==3&&!/\S/.test(node.nodeValue)) element.removeChild(node);node=nextNode;} return element;},empty:function(element){return $(element).innerHTML.blank();},descendantOf:function(element,ancestor){element=$(element),ancestor=$(ancestor);if(element.compareDocumentPosition) return(element.compareDocumentPosition(ancestor)&8)===8;if(ancestor.contains) return ancestor.contains(element)&&ancestor!==element;while(element=element.parentNode) if(element==ancestor)return true;return false;},scrollTo:function(element){element=$(element);var pos=Element.cumulativeOffset(element);window.scrollTo(pos[0],pos[1]);return element;},getStyle:function(element,style){element=$(element);style=style=='float'?'cssFloat':style.camelize();var value=element.style[style];if(!value||value=='auto'){var css=document.defaultView.getComputedStyle(element,null);value=css?css[style]:null;} if(style=='opacity')return value?parseFloat(value):1.0;return value=='auto'?null:value;},getOpacity:function(element){return $(element).getStyle('opacity');},setStyle:function(element,styles){element=$(element);var elementStyle=element.style,match;if(Object.isString(styles)){element.style.cssText+=';'+styles;return styles.include('opacity')?element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]):element;} for(var property in styles) if(property=='opacity')element.setOpacity(styles[property]);else elementStyle[(property=='float'||property=='cssFloat')?(Object.isUndefined(elementStyle.styleFloat)?'cssFloat':'styleFloat'):property]=styles[property];return element;},setOpacity:function(element,value){element=$(element);element.style.opacity=(value==1||value==='')?'':(value<0.00001)?0:value;return element;},makePositioned:function(element){element=$(element);var pos=Element.getStyle(element,'position');if(pos=='static'||!pos){element._madePositioned=true;element.style.position='relative';if(Prototype.Browser.Opera){element.style.top=0;element.style.left=0;}} return element;},undoPositioned:function(element){element=$(element);if(element._madePositioned){element._madePositioned=undefined;element.style.position=element.style.top=element.style.left=element.style.bottom=element.style.right='';} return element;},makeClipping:function(element){element=$(element);if(element._overflow)return element;element._overflow=Element.getStyle(element,'overflow')||'auto';if(element._overflow!=='hidden') element.style.overflow='hidden';return element;},undoClipping:function(element){element=$(element);if(!element._overflow)return element;element.style.overflow=element._overflow=='auto'?'':element._overflow;element._overflow=null;return element;},clonePosition:function(element,source){var options=Object.extend({setLeft:true,setTop:true,setWidth:true,setHeight:true,offsetTop:0,offsetLeft:0},arguments[2]||{});source=$(source);var p=Element.viewportOffset(source),delta=[0,0],parent=null;element=$(element);if(Element.getStyle(element,'position')=='absolute'){parent=Element.getOffsetParent(element);delta=Element.viewportOffset(parent);} if(parent==document.body){delta[0]-=document.body.offsetLeft;delta[1]-=document.body.offsetTop;} if(options.setLeft)element.style.left=(p[0]-delta[0]+options.offsetLeft)+'px';if(options.setTop)element.style.top=(p[1]-delta[1]+options.offsetTop)+'px';if(options.setWidth)element.style.width=source.offsetWidth+'px';if(options.setHeight)element.style.height=source.offsetHeight+'px';return element;}};Object.extend(Element.Methods,{getElementsBySelector:Element.Methods.select,childElements:Element.Methods.immediateDescendants});Element._attributeTranslations={write:{names:{className:'class',htmlFor:'for'},values:{}}};if(Prototype.Browser.Opera){Element.Methods.getStyle=Element.Methods.getStyle.wrap(function(proceed,element,style){switch(style){case'height':case'width':if(!Element.visible(element))return null;var dim=parseInt(proceed(element,style),10);if(dim!==element['offset'+style.capitalize()]) return dim+'px';var properties;if(style==='height'){properties=['border-top-width','padding-top','padding-bottom','border-bottom-width'];} else{properties=['border-left-width','padding-left','padding-right','border-right-width'];} return properties.inject(dim,function(memo,property){var val=proceed(element,property);return val===null?memo:memo-parseInt(val,10);})+'px';default:return proceed(element,style);}});Element.Methods.readAttribute=Element.Methods.readAttribute.wrap(function(proceed,element,attribute){if(attribute==='title')return element.title;return proceed(element,attribute);});} else if(Prototype.Browser.IE){Element.Methods.getStyle=function(element,style){element=$(element);style=(style=='float'||style=='cssFloat')?'styleFloat':style.camelize();var value=element.style[style];if(!value&&element.currentStyle)value=element.currentStyle[style];if(style=='opacity'){if(value=(element.getStyle('filter')||'').match(/alpha\(opacity=(.*)\)/)) if(value[1])return parseFloat(value[1])/100;return 1.0;} if(value=='auto'){if((style=='width'||style=='height')&&(element.getStyle('display')!='none')) return element['offset'+style.capitalize()]+'px';return null;} return value;};Element.Methods.setOpacity=function(element,value){function stripAlpha(filter){return filter.replace(/alpha\([^\)]*\)/gi,'');} element=$(element);var currentStyle=element.currentStyle;if((currentStyle&&!currentStyle.hasLayout)||(!currentStyle&&element.style.zoom=='normal')) element.style.zoom=1;var filter=element.getStyle('filter'),style=element.style;if(value==1||value===''){(filter=stripAlpha(filter))?style.filter=filter:style.removeAttribute('filter');return element;}else if(value<0.00001)value=0;style.filter=stripAlpha(filter)+'alpha(opacity='+(value*100)+')';return element;};Element._attributeTranslations=(function(){var classProp='className',forProp='for',el=document.createElement('div');el.setAttribute(classProp,'x');if(el.className!=='x'){el.setAttribute('class','x');if(el.className==='x'){classProp='class';}} el=null;el=document.createElement('label');el.setAttribute(forProp,'x');if(el.htmlFor!=='x'){el.setAttribute('htmlFor','x');if(el.htmlFor==='x'){forProp='htmlFor';}} el=null;return{read:{names:{'class':classProp,'className':classProp,'for':forProp,'htmlFor':forProp},values:{_getAttr:function(element,attribute){return element.getAttribute(attribute);},_getAttr2:function(element,attribute){return element.getAttribute(attribute,2);},_getAttrNode:function(element,attribute){var node=element.getAttributeNode(attribute);return node?node.value:"";},_getEv:(function(){var el=document.createElement('div'),f;el.onclick=Prototype.emptyFunction;var value=el.getAttribute('onclick');if(String(value).indexOf('{')>-1){f=function(element,attribute){attribute=element.getAttribute(attribute);if(!attribute)return null;attribute=attribute.toString();attribute=attribute.split('{')[1];attribute=attribute.split('}')[0];return attribute.strip();};} else if(value===''){f=function(element,attribute){attribute=element.getAttribute(attribute);if(!attribute)return null;return attribute.strip();};} el=null;return f;})(),_flag:function(element,attribute){return $(element).hasAttribute(attribute)?attribute:null;},style:function(element){return element.style.cssText.toLowerCase();},title:function(element){return element.title;}}}}})();Element._attributeTranslations.write={names:Object.extend({cellpadding:'cellPadding',cellspacing:'cellSpacing'},Element._attributeTranslations.read.names),values:{checked:function(element,value){element.checked=!!value;},style:function(element,value){element.style.cssText=value?value:'';}}};Element._attributeTranslations.has={};$w('colSpan rowSpan vAlign dateTime accessKey tabIndex '+'encType maxLength readOnly longDesc frameBorder').each(function(attr){Element._attributeTranslations.write.names[attr.toLowerCase()]=attr;Element._attributeTranslations.has[attr.toLowerCase()]=attr;});(function(v){Object.extend(v,{href:v._getAttr2,src:v._getAttr2,type:v._getAttr,action:v._getAttrNode,disabled:v._flag,checked:v._flag,readonly:v._flag,multiple:v._flag,onload:v._getEv,onunload:v._getEv,onclick:v._getEv,ondblclick:v._getEv,onmousedown:v._getEv,onmouseup:v._getEv,onmouseover:v._getEv,onmousemove:v._getEv,onmouseout:v._getEv,onfocus:v._getEv,onblur:v._getEv,onkeypress:v._getEv,onkeydown:v._getEv,onkeyup:v._getEv,onsubmit:v._getEv,onreset:v._getEv,onselect:v._getEv,onchange:v._getEv});})(Element._attributeTranslations.read.values);if(Prototype.BrowserFeatures.ElementExtensions){(function(){function _descendants(element){var nodes=element.getElementsByTagName('*'),results=[];for(var i=0,node;node=nodes[i];i++) if(node.tagName!=="!") results.push(node);return results;} Element.Methods.down=function(element,expression,index){element=$(element);if(arguments.length==1)return element.firstDescendant();return Object.isNumber(expression)?_descendants(element)[expression]:Element.select(element,expression)[index||0];}})();}} else if(Prototype.Browser.Gecko&&/rv:1\.8\.0/.test(navigator.userAgent)){Element.Methods.setOpacity=function(element,value){element=$(element);element.style.opacity=(value==1)?0.999999:(value==='')?'':(value<0.00001)?0:value;return element;};} else if(Prototype.Browser.WebKit){Element.Methods.setOpacity=function(element,value){element=$(element);element.style.opacity=(value==1||value==='')?'':(value<0.00001)?0:value;if(value==1) if(element.tagName.toUpperCase()=='IMG'&&element.width){element.width++;element.width--;}else try{var n=document.createTextNode(' ');element.appendChild(n);element.removeChild(n);}catch(e){} return element;};} if('outerHTML'in document.documentElement){Element.Methods.replace=function(element,content){element=$(element);if(content&&content.toElement)content=content.toElement();if(Object.isElement(content)){element.parentNode.replaceChild(content,element);return element;} content=Object.toHTML(content);var parent=element.parentNode,tagName=parent.tagName.toUpperCase();if(Element._insertionTranslations.tags[tagName]){var nextSibling=element.next(),fragments=Element._getContentFromAnonymousElement(tagName,content.stripScripts());parent.removeChild(element);if(nextSibling) fragments.each(function(node){parent.insertBefore(node,nextSibling)});else fragments.each(function(node){parent.appendChild(node)});} else element.outerHTML=content.stripScripts();content.evalScripts.bind(content).p_defer();return element;};} Element._returnOffset=function(l,t){var result=[l,t];result.left=l;result.top=t;return result;};Element._getContentFromAnonymousElement=function(tagName,html,force){var div=new Element('div'),t=Element._insertionTranslations.tags[tagName];var workaround=false;if(t)workaround=true;else if(force){workaround=true;t=['','',0];} if(workaround){div.innerHTML=' '+t[0]+html+t[1];div.removeChild(div.firstChild);for(var i=t[2];i--;){div=div.firstChild;}} else{div.innerHTML=html;} return $A(div.childNodes);};Element._insertionTranslations={before:function(element,node){element.parentNode.insertBefore(node,element);},top:function(element,node){element.insertBefore(node,element.firstChild);},bottom:function(element,node){element.appendChild(node);},after:function(element,node){element.parentNode.insertBefore(node,element.nextSibling);},tags:{TABLE:['','
',1],TBODY:['','
',2],TR:['','
',3],TD:['
','
',4],SELECT:['',1]}};(function(){var tags=Element._insertionTranslations.tags;Object.extend(tags,{THEAD:tags.TBODY,TFOOT:tags.TBODY,TH:tags.TD});})();Element.Methods.Simulated={hasAttribute:function(element,attribute){attribute=Element._attributeTranslations.has[attribute]||attribute;var node=$(element).getAttributeNode(attribute);return!!(node&&node.specified);}};Element.Methods.ByTag={};Object.extend(Element,Element.Methods);(function(div){if(!Prototype.BrowserFeatures.ElementExtensions&&div['__proto__']){window.HTMLElement={};window.HTMLElement.prototype=div['__proto__'];Prototype.BrowserFeatures.ElementExtensions=true;} div=null;})(document.createElement('div'));Element.extend=(function(){function checkDeficiency(tagName){if(typeof window.Element!='undefined'){var proto=window.Element.prototype;if(proto){var id='_'+(Math.random()+'').slice(2),el=document.createElement(tagName);proto[id]='x';var isBuggy=(el[id]!=='x');delete proto[id];el=null;return isBuggy;}} return false;} function extendElementWith(element,methods){for(var property in methods){var value=methods[property];if(Object.isFunction(value)&&!(property in element)) element[property]=value.methodize();}} var HTMLOBJECTELEMENT_PROTOTYPE_BUGGY=checkDeficiency('object');if(Prototype.BrowserFeatures.SpecificElementExtensions){if(HTMLOBJECTELEMENT_PROTOTYPE_BUGGY){return function(element){if(element&&typeof element._extendedByPrototype=='undefined'){var t=element.tagName;if(t&&(/^(?:object|applet|embed)$/i.test(t))){extendElementWith(element,Element.Methods);extendElementWith(element,Element.Methods.Simulated);extendElementWith(element,Element.Methods.ByTag[t.toUpperCase()]);}} return element;}} return Prototype.K;} var Methods={},ByTag=Element.Methods.ByTag;var extend=Object.extend(function(element){if(!element||typeof element._extendedByPrototype!='undefined'||element.nodeType!=1||element==window)return element;var methods=Object.clone(Methods),tagName=element.tagName.toUpperCase();if(ByTag[tagName])Object.extend(methods,ByTag[tagName]);extendElementWith(element,methods);element._extendedByPrototype=Prototype.emptyFunction;return element;},{refresh:function(){if(!Prototype.BrowserFeatures.ElementExtensions){Object.extend(Methods,Element.Methods);Object.extend(Methods,Element.Methods.Simulated);}}});extend.refresh();return extend;})();if(document.documentElement.hasAttribute){Element.hasAttribute=function(element,attribute){return element.hasAttribute(attribute);};} else{Element.hasAttribute=Element.Methods.Simulated.hasAttribute;} Element.addMethods=function(methods){var F=Prototype.BrowserFeatures,T=Element.Methods.ByTag;if(!methods){Object.extend(Form,Form.Methods);Object.extend(Form.Element,Form.Element.Methods);Object.extend(Element.Methods.ByTag,{"FORM":Object.clone(Form.Methods),"INPUT":Object.clone(Form.Element.Methods),"SELECT":Object.clone(Form.Element.Methods),"TEXTAREA":Object.clone(Form.Element.Methods),"BUTTON":Object.clone(Form.Element.Methods)});} if(arguments.length==2){var tagName=methods;methods=arguments[1];} if(!tagName)Object.extend(Element.Methods,methods||{});else{if(Object.isArray(tagName))tagName.each(extend);else extend(tagName);} function extend(tagName){tagName=tagName.toUpperCase();if(!Element.Methods.ByTag[tagName]) Element.Methods.ByTag[tagName]={};Object.extend(Element.Methods.ByTag[tagName],methods);} function copy(methods,destination,onlyIfAbsent){onlyIfAbsent=onlyIfAbsent||false;for(var property in methods){var value=methods[property];if(!Object.isFunction(value))continue;if(!onlyIfAbsent||!(property in destination)) destination[property]=value.methodize();}} function findDOMClass(tagName){var klass;var trans={"OPTGROUP":"OptGroup","TEXTAREA":"TextArea","P":"Paragraph","FIELDSET":"FieldSet","UL":"UList","OL":"OList","DL":"DList","DIR":"Directory","H1":"Heading","H2":"Heading","H3":"Heading","H4":"Heading","H5":"Heading","H6":"Heading","Q":"Quote","INS":"Mod","DEL":"Mod","A":"Anchor","IMG":"Image","CAPTION":"TableCaption","COL":"TableCol","COLGROUP":"TableCol","THEAD":"TableSection","TFOOT":"TableSection","TBODY":"TableSection","TR":"TableRow","TH":"TableCell","TD":"TableCell","FRAMESET":"FrameSet","IFRAME":"IFrame"};if(trans[tagName])klass='HTML'+trans[tagName]+'Element';if(window[klass])return window[klass];klass='HTML'+tagName+'Element';if(window[klass])return window[klass];klass='HTML'+tagName.capitalize()+'Element';if(window[klass])return window[klass];var element=document.createElement(tagName),proto=element['__proto__']||element.constructor.prototype;element=null;return proto;} var elementPrototype=window.HTMLElement?HTMLElement.prototype:Element.prototype;if(F.ElementExtensions){copy(Element.Methods,elementPrototype);copy(Element.Methods.Simulated,elementPrototype,true);} if(F.SpecificElementExtensions){for(var tag in Element.Methods.ByTag){var klass=findDOMClass(tag);if(Object.isUndefined(klass))continue;copy(T[tag],klass.prototype);}} Object.extend(Element,Element.Methods);delete Element.ByTag;if(Element.extend.refresh)Element.extend.refresh();Element.cache={};};document.viewport={getDimensions:function(){return{width:this.getWidth(),height:this.getHeight()};},getScrollOffsets:function(){return Element._returnOffset(window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft,window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop);}};(function(viewport){var B=Prototype.Browser,doc=document,element,property={};function getRootElement(){if(B.WebKit&&!doc.evaluate) return document;if(B.Opera&&window.parseFloat(window.opera.version())<9.5) return document.body;return document.documentElement;} function define(D){if(!element)element=getRootElement();property[D]='client'+D;viewport['get'+D]=function(){return element[property[D]]};return viewport['get'+D]();} viewport.getWidth=define.curry('Width');viewport.getHeight=define.curry('Height');})(document.viewport);Element.Storage={UID:1};Element.addMethods({getStorage:function(element){if(!(element=$(element)))return;var uid;if(element===window){uid=0;}else{if(typeof element._prototypeUID==="undefined") element._prototypeUID=Element.Storage.UID++;uid=element._prototypeUID;} if(!Element.Storage[uid]) Element.Storage[uid]=$H();return Element.Storage[uid];},store:function(element,key,value){if(!(element=$(element)))return;if(arguments.length===2){Element.getStorage(element).update(key);}else{Element.getStorage(element).set(key,value);} return element;},retrieve:function(element,key,defaultValue){if(!(element=$(element)))return;var hash=Element.getStorage(element),value=hash.get(key);if(Object.isUndefined(value)){hash.set(key,defaultValue);value=defaultValue;} return value;},clone:function(element,deep){if(!(element=$(element)))return;var clone=element.cloneNode(deep);clone._prototypeUID=void 0;if(deep){var descendants=Element.select(clone,'*'),i=descendants.length;while(i--){descendants[i]._prototypeUID=void 0;}} return Element.extend(clone);},purge:function(element){if(!(element=$(element)))return;var purgeElement=Element._purgeElement;purgeElement(element);var descendants=element.getElementsByTagName('*'),i=descendants.length;while(i--)purgeElement(descendants[i]);return null;}});(function(){function toDecimal(pctString){var match=pctString.match(/^(\d+)%?$/i);if(!match)return null;return(Number(match[1])/100);} function getPixelValue(value,property,context){var element=null;if(Object.isElement(value)){element=value;value=element.getStyle(property);} if(value===null){return null;} if((/^(?:-)?\d+(\.\d+)?(px)?$/i).test(value)){return window.parseFloat(value);} var isPercentage=value.include('%'),isViewport=(context===document.viewport);if(/\d/.test(value)&&element&&element.runtimeStyle&&!(isPercentage&&isViewport)){var style=element.style.left,rStyle=element.runtimeStyle.left;element.runtimeStyle.left=element.currentStyle.left;element.style.left=value||0;value=element.style.pixelLeft;element.style.left=style;element.runtimeStyle.left=rStyle;return value;} if(element&&isPercentage){context=context||element.parentNode;var decimal=toDecimal(value);var whole=null;var position=element.getStyle('position');var isHorizontal=property.include('left')||property.include('right')||property.include('width');var isVertical=property.include('top')||property.include('bottom')||property.include('height');if(context===document.viewport){if(isHorizontal){whole=document.viewport.getWidth();}else if(isVertical){whole=document.viewport.getHeight();}}else{if(isHorizontal){whole=$(context).measure('width');}else if(isVertical){whole=$(context).measure('height');}} return(whole===null)?0:whole*decimal;} return 0;} function toCSSPixels(number){if(Object.isString(number)&&number.endsWith('px')){return number;} return number+'px';} function isDisplayed(element){var originalElement=element;while(element&&element.parentNode){var display=element.getStyle('display');if(display==='none'){return false;} element=$(element.parentNode);} return true;} var hasLayout=Prototype.K;if('currentStyle'in document.documentElement){hasLayout=function(element){if(!element.currentStyle.hasLayout){element.style.zoom=1;} return element;};} function cssNameFor(key){if(key.include('border'))key=key+'-width';return key.camelize();} Element.Layout=Class.create(Hash,{initialize:function($super,element,preCompute){$super();this.element=$(element);Element.Layout.PROPERTIES.each(function(property){this._set(property,null);},this);if(preCompute){this._preComputing=true;this._begin();Element.Layout.PROPERTIES.each(this._compute,this);this._end();this._preComputing=false;}},_set:function(property,value){return Hash.prototype.set.call(this,property,value);},set:function(property,value){throw"Properties of Element.Layout are read-only.";},get:function($super,property){var value=$super(property);return value===null?this._compute(property):value;},_begin:function(){if(this._prepared)return;var element=this.element;if(isDisplayed(element)){this._prepared=true;return;} var originalStyles={position:element.style.position||'',width:element.style.width||'',visibility:element.style.visibility||'',display:element.style.display||''};element.store('prototype_original_styles',originalStyles);var position=element.getStyle('position'),width=element.getStyle('width');if(width==="0px"||width===null){element.style.display='block';width=element.getStyle('width');} var context=(position==='fixed')?document.viewport:element.parentNode;element.setStyle({position:'absolute',visibility:'hidden',display:'block'});var positionedWidth=element.getStyle('width');var newWidth;if(width&&(positionedWidth===width)){newWidth=getPixelValue(element,'width',context);}else if(position==='absolute'||position==='fixed'){newWidth=getPixelValue(element,'width',context);}else{var parent=element.parentNode,pLayout=$(parent).getLayout();newWidth=pLayout.get('width')- this.get('margin-left')- this.get('border-left')- this.get('padding-left')- this.get('padding-right')- this.get('border-right')- this.get('margin-right');} element.setStyle({width:newWidth+'px'});this._prepared=true;},_end:function(){var element=this.element;var originalStyles=element.retrieve('prototype_original_styles');element.store('prototype_original_styles',null);element.setStyle(originalStyles);this._prepared=false;},_compute:function(property){var COMPUTATIONS=Element.Layout.COMPUTATIONS;if(!(property in COMPUTATIONS)){throw"Property not found.";} return this._set(property,COMPUTATIONS[property].call(this,this.element));},toObject:function(){var args=$A(arguments);var keys=(args.length===0)?Element.Layout.PROPERTIES:args.join(' ').split(' ');var obj={};keys.each(function(key){if(!Element.Layout.PROPERTIES.include(key))return;var value=this.get(key);if(value!=null)obj[key]=value;},this);return obj;},toHash:function(){var obj=this.toObject.apply(this,arguments);return new Hash(obj);},toCSS:function(){var args=$A(arguments);var keys=(args.length===0)?Element.Layout.PROPERTIES:args.join(' ').split(' ');var css={};keys.each(function(key){if(!Element.Layout.PROPERTIES.include(key))return;if(Element.Layout.COMPOSITE_PROPERTIES.include(key))return;var value=this.get(key);if(value!=null)css[cssNameFor(key)]=value+'px';},this);return css;},inspect:function(){return"#";}});Object.extend(Element.Layout,{PROPERTIES:$w('height width top left right bottom border-left border-right border-top border-bottom padding-left padding-right padding-top padding-bottom margin-top margin-bottom margin-left margin-right padding-box-width padding-box-height border-box-width border-box-height margin-box-width margin-box-height cumulative-left cumulative-top'),COMPOSITE_PROPERTIES:$w('padding-box-width padding-box-height margin-box-width margin-box-height border-box-width border-box-height'),COMPUTATIONS:{'height':function(element){if(!this._preComputing)this._begin();var bHeight=this.get('border-box-height');if(bHeight<=0){if(!this._preComputing)this._end();return 0;} var bTop=this.get('border-top'),bBottom=this.get('border-bottom');var pTop=this.get('padding-top'),pBottom=this.get('padding-bottom');if(!this._preComputing)this._end();return bHeight-bTop-bBottom-pTop-pBottom;},'width':function(element){if(!this._preComputing)this._begin();var bWidth=this.get('border-box-width');if(bWidth<=0){if(!this._preComputing)this._end();return 0;} var bLeft=this.get('border-left'),bRight=this.get('border-right');var pLeft=this.get('padding-left'),pRight=this.get('padding-right');if(!this._preComputing)this._end();return bWidth-bLeft-bRight-pLeft-pRight;},'padding-box-height':function(element){var height=this.get('height'),pTop=this.get('padding-top'),pBottom=this.get('padding-bottom');return height+pTop+pBottom;},'padding-box-width':function(element){var width=this.get('width'),pLeft=this.get('padding-left'),pRight=this.get('padding-right');return width+pLeft+pRight;},'border-box-height':function(element){if(!this._preComputing)this._begin();var height=element.offsetHeight;if(!this._preComputing)this._end();return height;},'cumulative-left':function(element){return element.cumulativeOffset().left;},'cumulative-top':function(element){return element.cumulativeOffset().top;},'border-box-width':function(element){if(!this._preComputing)this._begin();var width=element.offsetWidth;if(!this._preComputing)this._end();return width;},'margin-box-height':function(element){var bHeight=this.get('border-box-height'),mTop=this.get('margin-top'),mBottom=this.get('margin-bottom');if(bHeight<=0)return 0;return bHeight+mTop+mBottom;},'margin-box-width':function(element){var bWidth=this.get('border-box-width'),mLeft=this.get('margin-left'),mRight=this.get('margin-right');if(bWidth<=0)return 0;return bWidth+mLeft+mRight;},'top':function(element){var offset=element.positionedOffset();return offset.top;},'bottom':function(element){var offset=element.positionedOffset(),parent=element.getOffsetParent(),pHeight=parent.measure('height');var mHeight=this.get('border-box-height');return pHeight-mHeight-offset.top;},'left':function(element){var offset=element.positionedOffset();return offset.left;},'right':function(element){var offset=element.positionedOffset(),parent=element.getOffsetParent(),pWidth=parent.measure('width');var mWidth=this.get('border-box-width');return pWidth-mWidth-offset.left;},'padding-top':function(element){return getPixelValue(element,'paddingTop');},'padding-bottom':function(element){return getPixelValue(element,'paddingBottom');},'padding-left':function(element){return getPixelValue(element,'paddingLeft');},'padding-right':function(element){return getPixelValue(element,'paddingRight');},'border-top':function(element){return getPixelValue(element,'borderTopWidth');},'border-bottom':function(element){return getPixelValue(element,'borderBottomWidth');},'border-left':function(element){return getPixelValue(element,'borderLeftWidth');},'border-right':function(element){return getPixelValue(element,'borderRightWidth');},'margin-top':function(element){return getPixelValue(element,'marginTop');},'margin-bottom':function(element){return getPixelValue(element,'marginBottom');},'margin-left':function(element){return getPixelValue(element,'marginLeft');},'margin-right':function(element){return getPixelValue(element,'marginRight');}}});if('getBoundingClientRect'in document.documentElement){Object.extend(Element.Layout.COMPUTATIONS,{'right':function(element){var parent=hasLayout(element.getOffsetParent());var rect=element.getBoundingClientRect(),pRect=parent.getBoundingClientRect();return(pRect.right-rect.right).round();},'bottom':function(element){var parent=hasLayout(element.getOffsetParent());var rect=element.getBoundingClientRect(),pRect=parent.getBoundingClientRect();return(pRect.bottom-rect.bottom).round();}});} Element.Offset=Class.create({initialize:function(left,top){this.left=left.round();this.top=top.round();this[0]=this.left;this[1]=this.top;},relativeTo:function(offset){return new Element.Offset(this.left-offset.left,this.top-offset.top);},inspect:function(){return"#".interpolate(this);},toString:function(){return"[#{left}, #{top}]".interpolate(this);},toArray:function(){return[this.left,this.top];}});function getLayout(element,preCompute){return new Element.Layout(element,preCompute);} function measure(element,property){return $(element).getLayout().get(property);} function getDimensions(element){element=$(element);var display=Element.getStyle(element,'display');if(display&&display!=='none'){return{width:element.offsetWidth,height:element.offsetHeight};} var style=element.style;var originalStyles={visibility:style.visibility,position:style.position,display:style.display};var newStyles={visibility:'hidden',display:'block'};if(originalStyles.position!=='fixed') newStyles.position='absolute';Element.setStyle(element,newStyles);var dimensions={width:element.offsetWidth,height:element.offsetHeight};Element.setStyle(element,originalStyles);return dimensions;} function getOffsetParent(element){element=$(element);if(isDocument(element)||isDetached(element)||isBody(element)||isHtml(element)) return $(document.body);var isInline=(Element.getStyle(element,'display')==='inline');if(!isInline&&element.offsetParent)return $(element.offsetParent);while((element=element.parentNode)&&element!==document.body){if(Element.getStyle(element,'position')!=='static'){return isHtml(element)?$(document.body):$(element);}} return $(document.body);} function cumulativeOffset(element){element=$(element);var valueT=0,valueL=0;if(element.parentNode){do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;element=element.offsetParent;}while(element);} return new Element.Offset(valueL,valueT);} function positionedOffset(element){element=$(element);var layout=element.getLayout();var valueT=0,valueL=0;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;element=element.offsetParent;if(element){if(isBody(element))break;var p=Element.getStyle(element,'position');if(p!=='static')break;}}while(element);valueL-=layout.get('margin-top');valueT-=layout.get('margin-left');return new Element.Offset(valueL,valueT);} function cumulativeScrollOffset(element){var valueT=0,valueL=0;if(isBody(element)&&navigator.userAgent.indexOf('Chrome/32')>-1){element=document.documentElement};do{valueT+=element.scrollTop||0;valueL+=element.scrollLeft||0;element=element.parentNode;}while(element);return new Element.Offset(valueL,valueT);} function viewportOffset(forElement){element=$(element);var valueT=0,valueL=0,docBody=document.body;var element=forElement;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;if(element.offsetParent==docBody&&Element.getStyle(element,'position')=='absolute')break;}while(element=element.offsetParent);element=forElement;do{if(element!=docBody){valueT-=element.scrollTop||0;valueL-=element.scrollLeft||0;}}while(element=element.parentNode);return new Element.Offset(valueL,valueT);} function absolutize(element){element=$(element);if(Element.getStyle(element,'position')==='absolute'){return element;} var offsetParent=getOffsetParent(element);var eOffset=element.viewportOffset(),pOffset=offsetParent.viewportOffset();var offset=eOffset.relativeTo(pOffset);var layout=element.getLayout();element.store('prototype_absolutize_original_styles',{left:element.getStyle('left'),top:element.getStyle('top'),width:element.getStyle('width'),height:element.getStyle('height')});element.setStyle({position:'absolute',top:offset.top+'px',left:offset.left+'px',width:layout.get('width')+'px',height:layout.get('height')+'px'});return element;} function relativize(element){element=$(element);if(Element.getStyle(element,'position')==='relative'){return element;} var originalStyles=element.retrieve('prototype_absolutize_original_styles');if(originalStyles)element.setStyle(originalStyles);return element;} if(Prototype.Browser.IE){getOffsetParent=getOffsetParent.wrap(function(proceed,element){element=$(element);if(isDocument(element)||isDetached(element)||isBody(element)||isHtml(element)) return $(document.body);var position=element.getStyle('position');if(position!=='static')return proceed(element);element.setStyle({position:'relative'});var value=proceed(element);element.setStyle({position:position});return value;});positionedOffset=positionedOffset.wrap(function(proceed,element){element=$(element);if(!element.parentNode)return new Element.Offset(0,0);var position=element.getStyle('position');if(position!=='static')return proceed(element);var offsetParent=element.getOffsetParent();if(offsetParent&&offsetParent.getStyle('position')==='fixed') hasLayout(offsetParent);element.setStyle({position:'relative'});var value=proceed(element);element.setStyle({position:position});return value;});}else if(Prototype.Browser.Webkit){cumulativeOffset=function(element){element=$(element);var valueT=0,valueL=0;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;if(element.offsetParent==document.body) if(Element.getStyle(element,'position')=='absolute')break;element=element.offsetParent;}while(element);return new Element.Offset(valueL,valueT);};} Element.addMethods({getLayout:getLayout,measure:measure,getDimensions:getDimensions,getOffsetParent:getOffsetParent,cumulativeOffset:cumulativeOffset,positionedOffset:positionedOffset,cumulativeScrollOffset:cumulativeScrollOffset,viewportOffset:viewportOffset,absolutize:absolutize,relativize:relativize});function isBody(element){return element.nodeName.toUpperCase()==='BODY';} function isHtml(element){return element.nodeName.toUpperCase()==='HTML';} function isDocument(element){return element.nodeType===Node.DOCUMENT_NODE;} function isDetached(element){return element!==document.body&&!Element.descendantOf(element,document.body);} if('getBoundingClientRect'in document.documentElement){Element.addMethods({viewportOffset:function(element){element=$(element);if(isDetached(element))return new Element.Offset(0,0);var rect=element.getBoundingClientRect(),docEl=document.documentElement;return new Element.Offset(rect.left-docEl.clientLeft,rect.top-docEl.clientTop);}});}})();window.$$=function(){var expression=$A(arguments).join(', ');return Prototype.Selector.select(expression,document);};Prototype.Selector=(function(){function select(){throw new Error('Method "Prototype.Selector.select" must be defined.');} function match(){throw new Error('Method "Prototype.Selector.match" must be defined.');} function find(elements,expression,index){index=index||0;var match=Prototype.Selector.match,length=elements.length,matchIndex=0,i;for(i=0;i+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,done=0,toString=Object.prototype.toString,hasDuplicate=false,baseHasDuplicate=true;[0,0].sort(function(){baseHasDuplicate=false;return 0;});var Sizzle=function(selector,context,results,seed){results=results||[];var origContext=context=context||document;if(context.nodeType!==1&&context.nodeType!==9){return[];} if(!selector||typeof selector!=="string"){return results;} var parts=[],m,set,checkSet,check,mode,extra,prune=true,contextXML=isXML(context),soFar=selector;while((chunker.exec(""),m=chunker.exec(soFar))!==null){soFar=m[3];parts.push(m[1]);if(m[2]){extra=m[3];break;}} if(parts.length>1&&origPOS.exec(selector)){if(parts.length===2&&Expr.relative[parts[0]]){set=posProcess(parts[0]+parts[1],context);}else{set=Expr.relative[parts[0]]?[context]:Sizzle(parts.shift(),context);while(parts.length){selector=parts.shift();if(Expr.relative[selector]) selector+=parts.shift();set=posProcess(selector,set);}}}else{if(!seed&&parts.length>1&&context.nodeType===9&&!contextXML&&Expr.match.ID.test(parts[0])&&!Expr.match.ID.test(parts[parts.length-1])){var ret=Sizzle.find(parts.shift(),context,contextXML);context=ret.expr?Sizzle.filter(ret.expr,ret.set)[0]:ret.set[0];} if(context){var ret=seed?{expr:parts.pop(),set:makeArray(seed)}:Sizzle.find(parts.pop(),parts.length===1&&(parts[0]==="~"||parts[0]==="+")&&context.parentNode?context.parentNode:context,contextXML);set=ret.expr?Sizzle.filter(ret.expr,ret.set):ret.set;if(parts.length>0){checkSet=makeArray(set);}else{prune=false;} while(parts.length){var cur=parts.pop(),pop=cur;if(!Expr.relative[cur]){cur="";}else{pop=parts.pop();} if(pop==null){pop=context;} Expr.relative[cur](checkSet,pop,contextXML);}}else{checkSet=parts=[];}} if(!checkSet){checkSet=set;} if(!checkSet){throw"Syntax error, unrecognized expression: "+(cur||selector);} if(toString.call(checkSet)==="[object Array]"){if(!prune){results.push.apply(results,checkSet);}else if(context&&context.nodeType===1){for(var i=0;checkSet[i]!=null;i++){if(checkSet[i]&&(checkSet[i]===true||checkSet[i].nodeType===1&&contains(context,checkSet[i]))){results.push(set[i]);}}}else{for(var i=0;checkSet[i]!=null;i++){if(checkSet[i]&&checkSet[i].nodeType===1){results.push(set[i]);}}}}else{makeArray(checkSet,results);} if(extra){Sizzle(extra,origContext,results,seed);Sizzle.uniqueSort(results);} return results;};Sizzle.uniqueSort=function(results){if(sortOrder){hasDuplicate=baseHasDuplicate;results.sort(sortOrder);if(hasDuplicate){for(var i=1;i":function(checkSet,part,isXML){var isPartStr=typeof part==="string";if(isPartStr&&!/\W/.test(part)){part=isXML?part:part.toUpperCase();for(var i=0,l=checkSet.length;i=0)){if(!inplace) result.push(elem);}else if(inplace){curLoop[i]=false;}}} return false;},ID:function(match){return match[1].replace(/\\/g,"");},TAG:function(match,curLoop){for(var i=0;curLoop[i]===false;i++){} return curLoop[i]&&isXML(curLoop[i])?match[1]:match[1].toUpperCase();},CHILD:function(match){if(match[1]=="nth"){var test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(match[2]=="even"&&"2n"||match[2]=="odd"&&"2n+1"||!/\D/.test(match[2])&&"0n+"+match[2]||match[2]);match[2]=(test[1]+(test[2]||1))-0;match[3]=test[3]-0;} match[0]=done++;return match;},ATTR:function(match,curLoop,inplace,result,not,isXML){var name=match[1].replace(/\\/g,"");if(!isXML&&Expr.attrMap[name]){match[1]=Expr.attrMap[name];} if(match[2]==="~="){match[4]=" "+match[4]+" ";} return match;},PSEUDO:function(match,curLoop,inplace,result,not){if(match[1]==="not"){if((chunker.exec(match[3])||"").length>1||/^\w/.test(match[3])){match[3]=Sizzle(match[3],null,null,curLoop);}else{var ret=Sizzle.filter(match[3],curLoop,inplace,true^not);if(!inplace){result.push.apply(result,ret);} return false;}}else if(Expr.match.POS.test(match[0])||Expr.match.CHILD.test(match[0])){return true;} return match;},POS:function(match){match.unshift(true);return match;}},filters:{enabled:function(elem){return elem.disabled===false&&elem.type!=="hidden";},disabled:function(elem){return elem.disabled===true;},checked:function(elem){return elem.checked===true;},selected:function(elem){elem.parentNode.selectedIndex;return elem.selected===true;},parent:function(elem){return!!elem.firstChild;},empty:function(elem){return!elem.firstChild;},has:function(elem,i,match){return!!Sizzle(match[3],elem).length;},header:function(elem){return /h\d/i.test(elem.nodeName);},text:function(elem){return"text"===elem.type;},radio:function(elem){return"radio"===elem.type;},checkbox:function(elem){return"checkbox"===elem.type;},file:function(elem){return"file"===elem.type;},password:function(elem){return"password"===elem.type;},submit:function(elem){return"submit"===elem.type;},image:function(elem){return"image"===elem.type;},reset:function(elem){return"reset"===elem.type;},button:function(elem){return"button"===elem.type||elem.nodeName.toUpperCase()==="BUTTON";},input:function(elem){return /input|select|textarea|button/i.test(elem.nodeName);}},setFilters:{first:function(elem,i){return i===0;},last:function(elem,i,match,array){return i===array.length-1;},even:function(elem,i){return i%2===0;},odd:function(elem,i){return i%2===1;},lt:function(elem,i,match){return imatch[3]-0;},nth:function(elem,i,match){return match[3]-0==i;},eq:function(elem,i,match){return match[3]-0==i;}},filter:{PSEUDO:function(elem,match,i,array){var name=match[1],filter=Expr.filters[name];if(filter){return filter(elem,i,match,array);}else if(name==="contains"){return(elem.textContent||elem.innerText||"").indexOf(match[3])>=0;}else if(name==="not"){var not=match[3];for(var i=0,l=not.length;i=0);}}},ID:function(elem,match){return elem.nodeType===1&&elem.getAttribute("id")===match;},TAG:function(elem,match){return(match==="*"&&elem.nodeType===1)||elem.nodeName===match;},CLASS:function(elem,match){return(" "+(elem.className||elem.getAttribute("class"))+" ").indexOf(match)>-1;},ATTR:function(elem,match){var name=match[1],result=Expr.attrHandle[name]?Expr.attrHandle[name](elem):elem[name]!=null?elem[name]:elem.getAttribute(name),value=result+"",type=match[2],check=match[4];return result==null?type==="!=":type==="="?value===check:type==="*="?value.indexOf(check)>=0:type==="~="?(" "+value+" ").indexOf(check)>=0:!check?value&&result!==false:type==="!="?value!=check:type==="^="?value.indexOf(check)===0:type==="$="?value.substr(value.length-check.length)===check:type==="|="?value===check||value.substr(0,check.length+1)===check+"-":false;},POS:function(elem,match,i,array){var name=match[2],filter=Expr.setFilters[name];if(filter){return filter(elem,i,match,array);}}}};var origPOS=Expr.match.POS;for(var type in Expr.match){Expr.match[type]=new RegExp(Expr.match[type].source+/(?![^\[]*\])(?![^\(]*\))/.source);Expr.leftMatch[type]=new RegExp(/(^(?:.|\r|\n)*?)/.source+Expr.match[type].source);} var makeArray=function(array,results){array=Array.prototype.slice.call(array,0);if(results){results.push.apply(results,array);return results;} return array;};try{Array.prototype.slice.call(document.documentElement.childNodes,0);}catch(e){makeArray=function(array,results){var ret=results||[];if(toString.call(array)==="[object Array]"){Array.prototype.push.apply(ret,array);}else{if(typeof array.length==="number"){for(var i=0,l=array.length;i";var root=document.documentElement;root.insertBefore(form,root.firstChild);if(!!document.getElementById(id)){Expr.find.ID=function(match,context,isXML){if(typeof context.getElementById!=="undefined"&&!isXML){var m=context.getElementById(match[1]);return m?m.id===match[1]||typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id").nodeValue===match[1]?[m]:undefined:[];}};Expr.filter.ID=function(elem,match){var node=typeof elem.getAttributeNode!=="undefined"&&elem.getAttributeNode("id");return elem.nodeType===1&&node&&node.nodeValue===match;};} root.removeChild(form);root=form=null;})();(function(){var div=document.createElement("div");div.appendChild(document.createComment(""));if(div.getElementsByTagName("*").length>0){Expr.find.TAG=function(match,context){var results=context.getElementsByTagName(match[1]);if(match[1]==="*"){var tmp=[];for(var i=0;results[i];i++){if(results[i].nodeType===1){tmp.push(results[i]);}} results=tmp;} return results;};} div.innerHTML="";if(div.firstChild&&typeof div.firstChild.getAttribute!=="undefined"&&div.firstChild.getAttribute("href")!=="#"){Expr.attrHandle.href=function(elem){return elem.getAttribute("href",2);};} div=null;})();if(document.querySelectorAll)(function(){var oldSizzle=Sizzle,div=document.createElement("div");div.innerHTML="

";if(div.querySelectorAll&&div.querySelectorAll(".TEST").length===0){return;} Sizzle=function(query,context,extra,seed){context=context||document;if(!seed&&context.nodeType===9&&!isXML(context)){try{return makeArray(context.querySelectorAll(query),extra);}catch(e){}} return oldSizzle(query,context,extra,seed);};for(var prop in oldSizzle){Sizzle[prop]=oldSizzle[prop];} div=null;})();if(document.getElementsByClassName&&document.documentElement.getElementsByClassName)(function(){var div=document.createElement("div");div.innerHTML="
";if(div.getElementsByClassName("e").length===0) return;div.lastChild.className="e";if(div.getElementsByClassName("e").length===1) return;Expr.order.splice(1,0,"CLASS");Expr.find.CLASS=function(match,context,isXML){if(typeof context.getElementsByClassName!=="undefined"&&!isXML){return context.getElementsByClassName(match[1]);}};div=null;})();function dirNodeCheck(dir,cur,doneName,checkSet,nodeCheck,isXML){var sibDir=dir=="previousSibling"&&!isXML;for(var i=0,l=checkSet.length;i0){match=elem;break;}} elem=elem[dir];} checkSet[i]=match;}}} var contains=document.compareDocumentPosition?function(a,b){return a.compareDocumentPosition(b)&16;}:function(a,b){return a!==b&&(a.contains?a.contains(b):true);};var isXML=function(elem){return elem.nodeType===9&&elem.documentElement.nodeName!=="HTML"||!!elem.ownerDocument&&elem.ownerDocument.documentElement.nodeName!=="HTML";};var posProcess=function(selector,context){var tmpSet=[],later="",match,root=context.nodeType?[context]:context;while((match=Expr.match.PSEUDO.exec(selector))){later+=match[0];selector=selector.replace(Expr.match.PSEUDO,"");} selector=Expr.relative[selector]?selector+"*":selector;for(var i=0,l=root.length;i=0;}).sortBy(function(element){return element.tabIndex}).first();return firstByIndex?firstByIndex:elements.find(function(element){return /^(?:input|select|textarea)$/i.test(element.tagName);});},focusFirstElement:function(form){form=$(form);var element=form.findFirstElement();if(element)element.activate();return form;},request:function(form,options){form=$(form),options=Object.clone(options||{});var params=options.parameters,action=form.readAttribute('action')||'';if(action.blank())action=window.location.href;options.parameters=form.serialize(true);if(params){if(Object.isString(params))params=params.toQueryParams();Object.extend(options.parameters,params);} if(form.hasAttribute('method')&&!options.method) options.method=form.method;return new Ajax.Request(action,options);}};Form.Element={focus:function(element){$(element).focus();return element;},select:function(element){$(element).select();return element;}};Form.Element.Methods={serialize:function(element){element=$(element);if(!element.disabled&&element.name){var value=element.getValue();if(value!=undefined){var pair={};pair[element.name]=value;return Object.toQueryString(pair);}} return'';},getValue:function(element){element=$(element);var method=element.tagName.toLowerCase();return Form.Element.Serializers[method](element);},setValue:function(element,value){element=$(element);var method=element.tagName.toLowerCase();Form.Element.Serializers[method](element,value);return element;},clear:function(element){$(element).value='';return element;},present:function(element){return $(element).value!='';},activate:function(element){element=$(element);try{element.focus();if(element.select&&(element.tagName.toLowerCase()!='input'||!(/^(?:button|reset|submit)$/i.test(element.type)))) element.select();}catch(e){} return element;},disable:function(element){element=$(element);element.disabled=true;if(element.type==='file'){var deleteUploadBtns=$$('#'+element.closest('li').id+' .qq-upload-delete');deleteUploadBtns.each(function(btn){btn.style.visibility='hidden';});} return element;},enable:function(element){element=$(element);element.disabled=false;if(element.type==='file'){var deleteUploadBtns=$$('#'+element.closest('li').id+' .qq-upload-delete');deleteUploadBtns.each(function(btn){btn.style.visibility='';});} return element;}};var Field=Form.Element;var $F=Form.Element.Methods.getValue;Form.Element.Serializers=(function(){function input(element,value){switch(element.type.toLowerCase()){case'checkbox':case'radio':return inputSelector(element,value);default:return valueSelector(element,value);}} function inputSelector(element,value){if(Object.isUndefined(value)) return element.checked?element.value:null;else element.checked=!!value;} function valueSelector(element,value){if(Object.isUndefined(value))return element.value;else element.value=value;} function select(element,value){if(Object.isUndefined(value)) return(element.type==='select-one'?selectOne:selectMany)(element);var opt,currentValue,single=!Object.isArray(value);for(var i=0,length=element.length;i=0?optionValue(element.options[index]):null;} function selectMany(element){var values,length=element.length;if(!length)return null;for(var i=0,values=[];i=this.offset[1]&&y=this.offset[0]&&x=this.offset[1]&&this.ycomp=this.offset[0]&&this.xcomp0;})._each(iterator);},set:function(className){this.element.className=className;},add:function(classNameToAdd){if(this.include(classNameToAdd))return;this.set($A(this).concat(classNameToAdd).join(' '));},remove:function(classNameToRemove){if(!this.include(classNameToRemove))return;this.set($A(this).without(classNameToRemove).join(' '));},toString:function(){return $A(this).join(' ');}};Object.extend(Element.ClassNames.prototype,Enumerable);(function(){window.Selector=Class.create({initialize:function(expression){this.expression=expression.strip();},findElements:function(rootElement){return Prototype.Selector.select(this.expression,rootElement);},match:function(element){return Prototype.Selector.match(element,this.expression);},toString:function(){return this.expression;},inspect:function(){return"#";}});Object.extend(Selector,{matchElements:function(elements,expression){var match=Prototype.Selector.match,results=[];for(var i=0,length=elements.length;i-1){Prototype=new Proxy(Prototype,{get(target,prop,receiver){console.count('Prototype Call Detected');console.trace({target,prop,receiver});return target[prop];}});};if(window.console===undefined){if(!window.console||!console.firebug){(function(m,i){window.console={};var e=function(){};while(i--){window.console[m[i]]=e;}})('log debug info warn error assert dir dirxml trace group groupEnd time timeEnd profile profileEnd count'.split(' '),16);} window.console.error=function(e){throw(e);};} window.requestAnimFrame=(function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(callback){window.setTimeout(callback,1000/60);};})();if(window.Prototype===undefined){throw("Error:prototype.js is required by protoplus.js. Go to prototypejs.org and download lates version.");} Protoplus={Version:"0.9.9",exec:function(code){return eval(code);},REFIDCOUNT:100,references:{},getIEVersion:function(){var rv=-1;if(navigator.appName=='Microsoft Internet Explorer') {var ua=navigator.userAgent;var re=new RegExp("MSIE ([0-9]{1,}[\\.0-9]{0,})");if(re.exec(ua)!==null){rv=parseFloat(RegExp.$1);}} return rv;},Transitions:{linear:function(x){return x;},sineIn:function(x){return 1-Math.cos(x*Math.PI/2);},sineOut:function(x){return Math.sin(x*Math.PI/2);},sineInOut:function(x){return 0.5-Math.cos(x*Math.PI)/2;},backIn:function(b){var a=1.70158;return(b)*b*((a+1)*b-a);},backOut:function(b){var a=1.70158;return(b=b-1)*b*((a+1)*b+a)+1;},backInOut:function(b){var a=1.70158;if((b/=0.5)<1){return 0.5*(b*b*(((a*=(1.525))+1)*b-a));}return 0.5*((b-=2)*b*(((a*=(1.525))+1)*b+a)+2);},cubicIn:function(x){return Math.pow(x,3);},cubicOut:function(x){return 1+Math.pow(x-1,3);},cubicInOut:function(x){return x<0.5?4*Math.pow(x,3):1+4*Math.pow(x-1,3);},quadIn:function(x){return Math.pow(x,2);},quadOut:function(x){return 1-Math.pow(x-1,2);},quadInOut:function(x){return x<0.5?2*Math.pow(x,2):1-2*Math.pow(x-1,2);},quartIn:function(x){return Math.pow(x,4);},quartOut:function(x){return 1-Math.pow(x-1,4);},quartInOut:function(x){return x<0.5?8*Math.pow(x,4):1-8*Math.pow(x-1,4);},quintIn:function(x){return Math.pow(x,5);},quintOut:function(x){return 1+Math.pow(x-1,5);},quintInOut:function(x){return x<0.5?16*Math.pow(x,5):1+16*Math.pow(x-1,5);},circIn:function(x){return 1-Math.sqrt(1-Math.pow(x,2));},circOut:function(x){return Math.sqrt(1-Math.pow(x-1,2));},circInOut:function(x){return x<0.5?0.5-Math.sqrt(1-Math.pow(2*x,2))*0.5:0.5+Math.sqrt(1-Math.pow(2*x-2,2))*0.5;},expoIn:function(x){return Math.pow(2,10*(x-1));},expoOut:function(x){return 1-Math.pow(2,-10*x);},expoInOut:function(x){x=2*x-1;return x<0?Math.pow(2,10*x)/2:1-Math.pow(2,-10*x)/2;},swingFrom:function(b){var a=1.70158;return b*b*((a+1)*b-a);},swingTo:function(b){var a=1.70158;return(b-=1)*b*((a+1)*b+a)+1;},swingFromTo:function(b){var a=1.70158;return((b/=0.5)<1)?0.5*(b*b*(((a*=(1.525))+1)*b-a)):0.5*((b-=2)*b*(((a*=(1.525))+1)*b+a)+2);},easeFrom:function(a){return Math.pow(a,4);},easeTo:function(a){return Math.pow(a,0.25);},easeFromTo:function(a){if((a/=0.5)<1){return 0.5*Math.pow(a,4);}return-0.5*((a-=2)*Math.pow(a,3)-2);},pulse:function(x,n){if(!n){n=1;}return 0.5-Math.cos(x*n*2*Math.PI)/2;},wobble:function(x,n){if(!n){n=3;}return 0.5-Math.cos((2*n-1)*x*x*Math.PI)/2;},elastic:function(x,e){var a;if(!e){a=30;}else{e=Math.round(Math.max(1,Math.min(10,e)));a=(11-e)*5;}return 1-Math.cos(x*8*Math.PI)/(a*x+1)*(1-x);},bounce:function(x,n){n=n?Math.round(n):4;var c=3-Math.pow(2,2-n);var m=-1,d=0,i=0;while(m/c0){x-=((m-d)+d/2)/c;}return c*c*Math.pow(x,2)+(1-Math.pow(0.25,i-1));},bouncePast:function(a){if(a<(1/2.75)){return(7.5625*a*a);}else{if(a<(2/2.75)){return 2-(7.5625*(a-=(1.5/2.75))*a+0.75);}else{if(a<(2.5/2.75)){return 2-(7.5625*(a-=(2.25/2.75))*a+0.9375);}else{return 2-(7.5625*(a-=(2.625/2.75))*a+0.984375);}}}}},Colors:{colorNames:{"Black":"#000000","MidnightBlue":"#191970","Navy":"#000080","DarkBlue":"#00008B","MediumBlue":"#0000CD","Blue":"#0000FF","DodgerBlue":"#1E90FF","RoyalBlue":"#4169E1","SlateBlue":"#6A5ACD","SteelBlue":"#4682B4","CornflowerBlue":"#6495ED","Teal":"#008080","DarkCyan":"#008B8B","MediumSlateBlue":"#7B68EE","CadetBlue":"#5F9EA0","DeepSkyBlue":"#00BFFF","DarkTurquoise":"#00CED1","MediumAquaMarine":"#66CDAA","MediumTurquoise":"#48D1CC","Turquoise":"#40E0D0","LightSkyBlue":"#87CEFA","SkyBlue":"#87CEEB","Aqua":"#00FFFF","Cyan":"#00FFFF","Aquamarine":"#7FFFD4","PaleTurquoise":"#AFEEEE","PowderBlue":"#B0E0E6","LightBlue":"#ADD8E6","LightSteelBlue":"#B0C4DE","Salmon":"#FA8072","LightSalmon":"#FFA07A","Coral":"#FF7F50","Brown":"#A52A2A","Sienna":"#A0522D","Tomato":"#FF6347","Maroon":"#800000","DarkRed":"#8B0000","Red":"#FF0000","OrangeRed":"#FF4500","Darkorange":"#FF8C00","DarkGoldenRod":"#B8860B","GoldenRod":"#DAA520","Orange":"#FFA500","Gold":"#FFD700","Yellow":"#FFFF00","LemonChiffon":"#FFFACD","LightGoldenRodYellow":"#FAFAD2","LightYellow":"#FFFFE0","DarkOliveGreen":"#556B2F","DarkSeaGreen":"#8FBC8F","DarkGreen":"#006400","MediumSeaGreen":"#3CB371","DarkKhaki":"#BDB76B","Green":"#008000","Olive":"#808000","OliveDrab":"#6B8E23","ForestGreen":"#228B22","LawnGreen":"#7CFC00","Lime":"#00FF00","YellowGreen":"#9ACD32","LimeGreen":"#32CD32","Chartreuse":"#7FFF00","GreenYellow":"#ADFF2F","LightSeaGreen":"#20B2AA","SeaGreen":"#2E8B57","SandyBrown":"#F4A460","DarkSlateGray":"#2F4F4F","DimGray":"#696969","Gray":"#808080","SlateGray":"#708090","LightSlateGray":"#778899","DarkGray":"#A9A9A9","Silver":"#C0C0C0","Indigo":"#4B0082","Purple":"#800080","DarkMagenta":"#8B008B","BlueViolet":"#8A2BE2","DarkOrchid":"#9932CC","DarkViolet":"#9400D3","DarkSlateBlue":"#483D8B","MediumPurple":"#9370D8","MediumOrchid":"#BA55D3","Fuchsia":"#FF00FF","Magenta":"#FF00FF","Orchid":"#DA70D6","Violet":"#EE82EE","DeepPink":"#FF1493","Pink":"#FFC0CB","MistyRose":"#FFE4E1","LightPink":"#FFB6C1","Plum":"#DDA0DD","HotPink":"#FF69B4","SpringGreen":"#00FF7F","MediumSpringGreen":"#00FA9A","LightGreen":"#90EE90","PaleGreen":"#98FB98","RosyBrown":"#BC8F8F","MediumVioletRed":"#C71585","IndianRed":"#CD5C5C","SaddleBrown":"#8B4513","Peru":"#CD853F","Chocolate":"#D2691E","Tan":"#D2B48C","LightGrey":"#D3D3D3","PaleVioletRed":"#D87093","Thistle":"#D8BFD8","Crimson":"#DC143C","FireBrick":"#B22222","Gainsboro":"#DCDCDC","BurlyWood":"#DEB887","LightCoral":"#F08080","DarkSalmon":"#E9967A","Lavender":"#E6E6FA","LavenderBlush":"#FFF0F5","SeaShell":"#FFF5EE","Linen":"#FAF0E6","Khaki":"#F0E68C","PaleGoldenRod":"#EEE8AA","Wheat":"#F5DEB3","NavajoWhite":"#FFDEAD","Moccasin":"#FFE4B5","PeachPuff":"#FFDAB9","Bisque":"#FFE4C4","BlanchedAlmond":"#FFEBCD","AntiqueWhite":"#FAEBD7","PapayaWhip":"#FFEFD5","Beige":"#F5F5DC","OldLace":"#FDF5E6","Cornsilk":"#FFF8DC","Ivory":"#FFFFF0","FloralWhite":"#FFFAF0","HoneyDew":"#F0FFF0","WhiteSmoke":"#F5F5F5","AliceBlue":"#F0F8FF","LightCyan":"#E0FFFF","GhostWhite":"#F8F8FF","MintCream":"#F5FFFA","Azure":"#F0FFFF","Snow":"#FFFAFA","White":"#FFFFFF"},getPalette:function(){var generated={};var cr=['00','44','77','99','BB','EE','FF'];var i=0;for(var r=0;r-1){color=color.replace(/rgb\(|\).*?$/g,"").split(/,\s*/,3);}else{color=color.replace("#","");if(color.length==3){color=color.replace(/(.)/g,function(n){return parseInt(n+n,16)+", ";}).replace(/,\s*$/,"").split(/,\s+/);}else{color=color.replace(/(..)/g,function(n){return parseInt(n,16)+", ";}).replace(/,\s*$/,"").split(/,\s+/);}}} for(var x=0;x "+node[e]);if(stophere){return node[e];}}}});Object.extend(Object,{deepClone:function(obj){if(typeof obj!=='object'||obj===null){return obj;} var clone=Object.isArray(obj)?[]:{};for(var i in obj){var node=obj[i];if(typeof node=='object'){if(Object.isArray(node)){clone[i]=[];for(var j=0;jlength)?closure:"";return sh;},squeeze:function(length){length=length?length:"30";var join="...";if((length-join.length)>=this.length){return this;} var l=Math.floor((length-join.length)/2);var start=this.substr(0,l+1);var end=this.substr(-(l),l);return start+join+end;},printf:function(){var args=arguments;var word=this.toString(),i=0;return word.replace(/(\%(\w))/gim,function(word,match,tag,count){var s=args[i]!==undefined?args[i]:'';i++;switch(tag){case"f":return parseFloat(s).toFixed(2);case"d":return parseInt(s,10);case"x":return s.toString(16);case"X":return s.toString(16).toUpperCase();case"s":return s;default:return match;}});},sanitize:function(){var str=this;return(str+'').replace(/[\\"']/g,'\\$&').replace(/\u0000/g,'\\0');},nl2br:function(is_xhtml){var str=this;var breakTag=(is_xhtml||typeof is_xhtml==='undefined')?'
':'
';return(str+'').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g,'$1'+breakTag+'');},stripslashes:function(){var str=this;return(str+'').replace(/\\(.?)/g,function(s,n1){switch(n1){case'\\':return'\\';case'0':return'\u0000';case'':return'';default:return n1;}});},turkishToUpper:function(){var string=this;var letters={"i":"İ","ş":"Ş","ğ":"Ğ","ü":"Ü","ö":"Ö","ç":"Ç","ı":"I"};string=string.replace(/([iışğüçö])+/g,function(letter){return letters[letter];});return string.toUpperCase();},turkishToLower:function(){var string=this;var letters={"İ":"i","I":"ı","Ş":"ş","Ğ":"ğ","Ü":"ü","Ö":"ö","Ç":"ç"};string=string.replace(/([İIŞĞÜÇÖ])+/g,function(letter){return letters[letter];});return string.toLowerCase();},toCamelCase:function(){var str=this;newStr=str.replace(/\s+/g,'_');strArr=newStr.split('_');if(strArr.length===0){return newStr;} newStr="";for(var i=0;i0){var last_style_node=document.styleSheets[document.styleSheets.length-1];if(typeof(last_style_node.addRule)=="object"){last_style_node.addRule(selector,declaration);}}},selectRadioOption:function(options,value){options.each(function(ele){if(ele.value===value) {ele.checked=true;}});},preloadImages:function(images){var args=arguments;if(Object.isArray(images)){args=images;} var i=0;for(i=0,images=[];(src=args[i]);i++){images.push(new Image());images.last().src=src;}},readRadioOption:function(options){for(var i=0;i","/":"?","\\":"|"};var special_keys={'esc':27,'escape':27,'tab':9,'space':32,'return':13,'enter':13,'backspace':8,'scrolllock':145,'scroll_lock':145,'scroll':145,'capslock':20,'caps_lock':20,'caps':20,'numlock':144,'num_lock':144,'num':144,'pause':19,'break':19,'insert':45,'home':36,'delete':46,'end':35,'pageup':33,'page_up':33,'pu':33,'pagedown':34,'page_down':34,'pd':34,'left':37,'up':38,'right':39,'down':40,'f1':112,'f2':113,'f3':114,'f4':115,'f5':116,'f6':117,'f7':118,'f8':119,'f9':120,'f10':121,'f11':122,'f12':123};var modifiers={shift:{wanted:false,pressed:false},ctrl:{wanted:false,pressed:false},alt:{wanted:false,pressed:false},meta:{wanted:false,pressed:false}};if(e.ctrlKey){modifiers.ctrl.pressed=true;}if(e.shiftKey){modifiers.shift.pressed=true;}if(e.altKey){modifiers.alt.pressed=true;}if(e.metaKey){modifiers.meta.pressed=true;}for(var i=0;i1){if(special_keys[k]==code){kp++;}}else if(opt.keycode){if(opt.keycode==code){kp++;}}else{if(character==k){kp++;}else{if(shift_nums[character]&&e.shiftKey){character=shift_nums[character];if(character==k){kp++;}}}}}if(kp==keys.length&&modifiers.ctrl.pressed==modifiers.ctrl.wanted&&modifiers.shift.pressed==modifiers.shift.wanted&&modifiers.alt.pressed==modifiers.alt.wanted&&modifiers.meta.pressed==modifiers.meta.wanted){callback(e);if(!opt.propagate){e.cancelBubble=true;e.returnValue=false;if(e.stopPropagation){e.stopPropagation();e.preventDefault();}return false;}}};this.all_shortcuts[shortcut_combination]={'callback':func,'target':ele,'event':opt.type};if(ele.addEventListener){ele.addEventListener(opt.type,func,false);}else if(ele.attachEvent){ele.attachEvent('on'+opt.type,func);}else{ele['on'+opt.type]=func;}},'remove':function(shortcut_combination){shortcut_combination=shortcut_combination.toLowerCase();var binding=this.all_shortcuts[shortcut_combination];delete(this.all_shortcuts[shortcut_combination]);if(!binding){return;}var type=binding.event;var ele=binding.target;var callback=binding.callback;if(ele.detachEvent){ele.detachEvent('on'+type,callback);}else if(ele.removeEventListener){ele.removeEventListener(type,callback,false);}else{ele['on'+type]=false;}}};$H(map).each(function(pair){var key=pair.key;var opts=pair.value;shortcut.add(key,opts.handler,{disable_in_input:opts.disableOnInputs});});},checkDocType:function(){if(document.doctype===null){return false;} var publicId=document.doctype.publicId.toLowerCase();return(publicId.indexOf("html 4")>0)||(publicId.indexOf("xhtml")>0);}});Object.extend(Event,{mousewheel:Prototype.Browser.Gecko?'DOMMouseScroll':'mousewheel',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);},isInput:function(e){var element;if(e.target){element=e.target;}else if(e.srcElement){element=e.srcElement;} if(element.nodeType==3){element=element.parentNode;} if(element.tagName=='INPUT'||element.tagName=='TEXTAREA'){return true;} return false;},isRightClick:function(event){var _isButton;if(Prototype.Browser.IE){var buttonMap={0:1,1:4,2:2};_isButton=function(event,code){return event.button===buttonMap[code];};}else if(Prototype.Browser.WebKit){_isButton=function(event,code){switch(code){case 0:return event.which==1&&!event.metaKey;case 1:return event.which==1&&event.metaKey;case 2:return event.which==3&&!event.metaKey;default:return false;}};}else{_isButton=function(event,code){return event.which?(event.which===code+1):(event.button===code);};} return _isButton(event,2);}});Protoplus.utils={cloneElem:function(element){if(Prototype.Browser.IE){var div=document.createElement('div');div.innerHTML=element.outerHTML;return $(div.firstChild);} return element.cloneNode(true);},openInNewTab:function(element,link){element.observe('mouseover',function(e){if(!element.tabLink){var a=new Element('a',{href:link,target:'_blank'}).insert('  ');a.setStyle('opacity:0; z-index:100000; height:5px; width:5px; position:absolute; top:'+(Event.pointerY(e)-2.5)+'px;left:'+(Event.pointerX(e)-2.5)+'px');a.observe('click',function(){element.tabLinked=false;a.remove();});$(document.body).insert(a);element.tabLink=a;element.observe('mousemove',function(e){element.tabLink.setStyle('top:'+(Event.pointerY(e)-2.5)+'px;left:'+(Event.pointerX(e)-2.5)+'px');});}});return element;},hasFixedContainer:function(element){var result=false;element.ancestors().each(function(el){if(result){return;} if(el.style.position=="fixed"){result=true;}});return result;},getCurrentStyle:function(element,name){if(element.style[name]){return element.style[name];}else if(element.currentStyle){return element.currentStyle[name];} else if(document.defaultView&&document.defaultView.getComputedStyle){name=name.replace(/([A-Z])/g,"-$1");name=name.toLowerCase();s=document.defaultView.getComputedStyle(element,"");return s&&s.getPropertyValue(name);}else{return null;}},isOverflow:function(element){if(element.resized){element.hideHandlers();} var curOverflow=element.style.overflow;if(!curOverflow||curOverflow==="visible"){element.style.overflow="hidden";} var leftOverflowing=element.clientWidth=vp.height+window.scrollY){window.scrollTo(window.scrollX,(pos[1]+options.offset[1])-vp.height);}else if(window.scrollY!==0&&(pos[1]+options.offset[1]<=Math.abs(vp.height-window.scrollY))){window.scrollTo(window.scrollX,(pos[1]+options.offset[1])-vp.height);} break;case"top":var height=element.getHeight();if(window.scrollY!==0&&pos[1]<=window.scrollY+options.offset[1]){window.scrollTo(window.scrollX,pos[1]-options.offset[1]);}else if(window.scrollY!==0&&(pos[1]+options.offset[1]<=Math.abs(vp.height-window.scrollY))){window.scrollTo(window.scrollX,pos[1]-options.offset[1]);} break;} return element;},getScroll:function(element){return{x:parseFloat(element.scrollLeft),y:parseFloat(element.scrollTop)};},setText:function(element,value){element.innerHTML=value;return element;},putValue:function(element,value){if(element.clearHint){element.clearHint();} element.value=value;return element;},resetUpload:function(element){if(Prototype.Browser.IE){var p=element.parentNode;var c=element.cloneNode(true);p.replaceChild(c,element);return c;} element.value='';return element;},run:function(element,event){if(event.include(':')){element.fire(event);}else{var evt;var disabled=element.hasClassName('form-dropdown')&&element.disabled?!!(element.enable()):false;if(document.createEventObject&&!Prototype.Browser.IE9&&!Prototype.Browser.IE10){evt=document.createEventObject();element.fireEvent('on'+event,evt);}else{evt=document.createEvent("HTMLEvents");evt.initEvent(event,true,true);if(disabled){setTimeout(function(){element.dispatchEvent(evt);element.disable();},0);}else{element.dispatchEvent(evt);}}} return element;},setCSSBorderRadius:function(element,value){return element.setStyle({MozBorderRadius:value,borderRadius:value,'-webkit-border-radius':value});},getSelected:function(element){if(!element.options){if(element.innerHTML){return element.innerHTML;} else{return element.value;}} var selected=element.selectedIndex>=0?element.options[element.selectedIndex]:element;return selected;},selectOption:function(element,val){if(!val){return element;} var match_found=false;$A(element.options).each(function(option){if(Object.isRegExp(val)&&(val.test(option.value))){option.selected=true;throw $break;} if(val==option.value){option.selected=true;match_found=true;}});if(match_found==false){$A(element.options).each(function(option){if(Object.isRegExp(val)&&(val.test(option.text))){option.selected=true;throw $break;} if(val==option.text){option.selected=true;}});} element.run('change');return element;},stopAnimation:function(element){element.__stopAnimation=true;return element;},shift:function(element,options){options=Object.extend({duration:1,onEnd:Prototype.K,onStart:Prototype.K,onStep:Prototype.K,onCreate:Prototype.K,delay:0,link:'cancel',transparentColor:'#ffffff',remove:false,easingCustom:false,propertyEasings:{},easing:Protoplus.Transitions.sineOut},options||{});if(!element.queue){element.queue=[];} options.onCreate(element,options);if(options.link=="ignore"&&element.timer){return element;}else if((options.link=="chain"||options.link=="queue")&&element.timer){element.queue.push(options);return element;} if(element.timer){clearInterval(element.timer);} if(element.delayTime){clearTimeout(element.delayTime);} if(typeof options.easing=='string'){if(options.easing in Protoplus.Transitions){options.easing=Protoplus.Transitions[options.easing];}else{options.easing=Protoplus.Transitions.sineOut;}}else if(typeof options.easing=='object'){options.propertyEasings=options.easing;options.easing=Protoplus.Transitions.sineOut;}else if(typeof options.easing!='function'){options.easing=Protoplus.Transitions.sineOut;} options.duration*=1000;options.delay*=1000;element.timer=false;var properties={},begin,end,init=function(){begin=new Date().getTime();end=begin+options.duration;options.onStart(element);};for(var x in options){if(!["duration","onStart","onStep","transparentColor","onEnd","onCreate","remove","easing","link","delay","easingCustom","propertyEasings"].include(x)&&options[x]!==false){properties[x]=options[x];}} var unitRex=/\d+([a-zA-Z%]+)$/;for(var i in properties){var okey=i,oval=properties[i];var to,from,key,unit,s=[],easing=options.easing;if(["scrollX","scrollLeft","scrollY","scrollTop"].include(okey)){to=parseFloat(oval);key=(okey=="scrollX")?"scrollLeft":(okey=="scrollY")?"scrollTop":okey;if(element.tagName=="BODY"){from=(okey=="scrollX"||okey=="scrollLeft")?window.scrollX:window.scrollY;}else{from=(okey=="scrollX"||okey=="scrollLeft")?element.scrollLeft:element.scrollTop;} unit='';}else if(okey=="rotate"){to=parseFloat(oval);key="-webkit-transform";from=Element.getStyle(element,'-webkit-transform')?parseInt(Element.getStyle(element,'-webkit-transform').replace(/rotate\(|\)/gim,""),10):0;unit='deg';}else if(["background","color","borderColor","backgroundColor"].include(okey)){if(oval=='transparent'){oval=options.transparentColor;} to=Protoplus.Colors.hexToRgb(oval);key=okey=="background"?"backgroundColor":okey;var bgcolor=Element.getStyle(element,key);if(!bgcolor||bgcolor=='transparent'){bgcolor=options.transparentColor;} from=Protoplus.Colors.getRGBarray(bgcolor);unit='';}else if(okey=="opacity"){to=(typeof oval=="string")?parseInt(oval,10):oval;key=okey;from=Element.getStyle(element,okey);unit='';from=parseFloat(from);}else{to=(typeof oval=="string")?parseInt(oval,10):oval;key=okey;from=Element.getStyle(element,okey.replace("-webkit-","").replace("-moz-",""))||"0px";unit=okey=='opacity'?'':(unitRex.test(from))?from.match(unitRex)[1]:'px';from=parseFloat(from);} if(okey in options.propertyEasings){easing=Protoplus.Transitions[options.propertyEasings[okey]];} if(!to&&to!==0){try{s[key]=oval;element.style[key]=oval;}catch(e){}}else{properties[okey]={key:key,to:to,from:from,unit:unit,easing:easing};}} var fn=function(ease,option,arr){var val=0;if(arr!==false){return Math.round(option.from[arr]+ease*(option.to[arr]-option.from[arr]));} return(option.from+ease*(option.to-option.from));};element.__stopAnimation=false;var step=function(){var time=new Date().getTime(),okey,oval,rgb;if(element.__stopAnimation===true){clearInterval(element.timer);element.timer=false;element.__stopAnimation=false;return;} if(time>=end){clearInterval(element.timer);element.timer=false;var valTo=(options.easing=="pulse"||options.easing==Protoplus.Transitions.pulse)?"from":"to";for(okey in properties){oval=properties[okey];if(["scrollX","scrollLeft","scrollY","scrollTop"].include(okey)){if(element.tagName.toUpperCase()=="BODY"){if(oval.key=="scrollLeft"){window.scrollTo(oval[valTo],window.scrollY);}else{window.scrollTo(window.scrollX,oval[valTo]);}}else{element[oval.key]=oval[valTo]+oval.unit;}}else if(["background","color","borderColor","backgroundColor"].include(okey)){element.style[oval.key]='rgb('+oval[valTo].join(', ')+")";}else if(okey=="opacity"){Element.setOpacity(element,oval[valTo]);}else if(okey=="rotate"){element.style[okey]="rotate("+oval[valTo]+oval.unit+")";}else{element.style[okey]=oval[valTo]+oval.unit;}} if(options.onEnd){options.onEnd(element);} if(options.remove){element.remove();} if(element.queue.length>0){var que=element.queue.splice(0,1);element.shift(que[0]);} return element;} if(options.onStep){options.onStep(element);} for(okey in properties){oval=properties[okey];if(oval.key=="scrollLeft"||oval.key=="scrollTop"){if(element.tagName.toUpperCase()=="BODY"){var scroll=parseInt(fn(oval.easing((time-begin)/options.duration,options.easingCustom),oval,false),10)+oval.unit;if(oval.key=="scrollLeft"){window.scrollTo(scroll,window.scrollY);}else{window.scrollTo(window.scrollX,scroll);}}else{element[oval.key]=parseInt(fn(oval.easing((time-begin)/options.duration,options.easingCustom),oval,false),10)+oval.unit;}}else if(okey=="background"||okey=="color"||okey=="borderColor"||okey=="backgroundColor"){rgb=[];for(var x=0;x<3;x++){rgb[x]=fn(oval.easing((time-begin)/options.duration,options.easingCustom),oval,x);} element.style[oval.key]='rgb('+rgb.join(', ')+')';}else if(okey=="opacity"){Element.setOpacity(element,fn(oval.easing((time-begin)/options.duration,options.easingCustom),oval,false));}else if(okey=="rotate"){element.style[oval.key]="rotate("+fn(oval.easing((time-begin)/options.duration,options.easingCustom),oval,false)+oval.unit+")";}else{element.style[okey]=fn(oval.easing((time-begin)/options.duration,options.easingCustom),oval,false)+oval.unit;}}};if(options.delay){element.delayTime=setTimeout(function(){init();element.timer=setInterval(step,10);},options.delay);}else{init();element.timer=setInterval(step,10);} return element;},fade:function(element,options){options=Object.extend({duration:0.5,onEnd:function(e){e.setStyle({display:"none"});},onStart:Prototype.K,opacity:0},options||{});element.shift(options);},appear:function(element,options){options=Object.extend({duration:0.5,onEnd:Prototype.K,onStart:Prototype.K,opacity:1},options||{});element.setStyle({opacity:0,display:"block"});element.shift(options);},disable:function(element){element=$(element);element.disabled=true;return element;},enable:function(element){element=$(element);element.disabled=false;return element;},setReference:function(element,name,reference){if(!element.REFID){element.REFID=Protoplus.REFIDCOUNT++;} if(!Protoplus.references[element.REFID]){Protoplus.references[element.REFID]={};} Protoplus.references[element.REFID][name]=$(reference);return element;},getReference:function(element,name){if(!element.REFID){return false;} return Protoplus.references[element.REFID][name];},remove:function(element){if(element.REFID){delete Protoplus.references[element.REFID];} if(element.parentNode){element.parentNode.removeChild(element);} return element;}};(function(emile,container){var parseEl=document.createElement('div'),props=('backgroundColor borderBottomColor borderBottomWidth borderLeftColor borderLeftWidth '+'borderRightColor borderRightWidth borderSpacing borderTopColor borderTopWidth bottom color fontSize '+'fontWeight height left letterSpacing lineHeight marginBottom marginLeft marginRight marginTop maxHeight '+'maxWidth minHeight minWidth opacity outlineColor outlineOffset outlineWidth paddingBottom paddingLeft '+'paddingRight paddingTop right textIndent top width wordSpacing zIndex').split(' ');function interpolate(source,target,pos){return(source+(target-source)*pos).toFixed(3);} function s(str,p,c){return str.substr(p,c||1);} function color(source,target,pos){var i=2,j=3,c,tmp,v=[],r=[];j=3;c=arguments[i-1];while(i--){if(s(c,0)=='r'){c=c.match(/\d+/g);while(j--){v.push(~~c[j]);}}else{if(c.length==4){c='#'+s(c,1)+s(c,1)+s(c,2)+s(c,2)+s(c,3)+s(c,3);} while(j--){v.push(parseInt(s(c,1+j*2,2),16));}} j=3;c=arguments[i-1];} while(j--){tmp=~~(v[j+3]+(v[j]-v[j+3])*pos);r.push(tmp<0?0:tmp>255?255:tmp);} return'rgb('+r.join(',')+')';} function parse(prop){var p=parseFloat(prop),q=prop.replace(/^[\-\d\.]+/,'');return isNaN(p)?{v:q,f:color,u:''}:{v:p,f:interpolate,u:q};} function normalize(style){var css,rules={},i=props.length,v;parseEl.innerHTML='
';css=parseEl.childNodes[0].style;while(i--){v=css[props[i]];if(v){rules[props[i]]=parse(v);}} return rules;} container[emile]=function(el,style,opts){el=typeof el=='string'?document.getElementById(el):el;opts=opts||{};var target=normalize(style),comp=el.currentStyle?el.currentStyle:getComputedStyle(el,null),prop,current={},start=+new Date(),dur=opts.duration||200,finish=start+dur,interval,easing=opts.easing||function(pos){return(-Math.cos(pos*Math.PI)/2)+0.5;};for(prop in target){current[prop]=parse(comp[prop]);} interval=setInterval(function(){var time=+new Date(),pos=time>finish?1:(time-start)/dur;for(var prop in target){el.style[prop]=target[prop].f(current[prop].v,target[prop].v,easing(pos))+target[prop].u;} if(time>finish){clearInterval(interval);if(opts.after){opts.after();}}},10);};})('emile',Protoplus.utils);Element.addMethods(Protoplus.utils);Event.observe(window,'unload',function(){Protoplus=null;});Ajax=Object.extend(Ajax,{Jsonp:function(url,options){this.options=Object.extend({method:'post',timeout:60,parameters:'',force:false,onComplete:Prototype.K,onSuccess:Prototype.K,onFail:Prototype.K},options||{});var parameterString=url.match(/\?/)?'&':'?';this.response=false;var callback_id=new Date().getTime();Ajax["callback_"+callback_id]=function(response){this.response=response;}.bind(this);this.callback=Ajax.callback;if(typeof this.options.parameters=="string"){parameterString+=this.options.parameters;}else{$H(this.options.parameters).each(function(p){parameterString+=p.key+'='+encodeURIComponent(p.value)+'&';});} var matches=/^(\w+:)?\/\/([^\/?#]+)/.exec(url);var sameDomain=(matches&&(matches[1]&&matches[1]!=location.protocol||matches[2]!=location.host));if(!sameDomain&&this.options.force===false){return new Ajax.Request(url,this.options);} this.url=url+parameterString+'callbackName=Ajax.callback_'+callback_id+'&nocache='+new Date().getTime();this.script=new Element('script',{type:'text/javascript',src:this.url});var errored=false;this.onError=function(e,b,c){errored=true;this.options.onComplete({success:false,error:e||"Not Found"});this.options.onFail({success:false,error:e||"Not Found",args:[e,b,c]});this.script.remove();window.onerror=null;this.response=false;}.bind(this);this.onLoad=function(e){if(errored){return;} clearTimeout(timer);this.script.onreadystatechange=null;this.script.onload=null;var res=this.script;this.script.remove();window.onerror=null;if(this.response){setTimeout(function(){this.options.onComplete({responseJSON:this.response});this.options.onSuccess({responseJSON:this.response});}.bind(this),20);}else{this.onError({error:'Callback error'});}}.bind(this);this.readyState=function(e){var rs=this.script.readyState;if(rs=='loaded'||rs=='complete'){this.onLoad();}}.bind(this);var timer=setTimeout(this.onError,this.options.timeout*1000);this.script.onreadystatechange=this.readyState;this.script.onload=this.onLoad;window.onerror=function(e,b,c){clearTimeout(timer);this.onError(e,b,c);return true;}.bind(this);$$('head')[0].appendChild(this.script);return this;}});var _alert=window.alert;if(!location.pathname.match(/^\/answers\/.+/)){window.alert=function(){var args=arguments;var i=1;var first=args[0];if(typeof first=="object"){$H(first).debug();return first;}else if(typeof first=="string"){var msg=first.replace(/(\%s)/gim,function(e){return args[i++]||"";});_alert(msg);return true;} _alert(first);};} var rand=function(min,max){return Math.floor(Math.random()*(max-min))+min;};if("__protoinit"in window){document.ready(function(e){$A(__protoinit).each(function(f){f(e);});});};if(window.Protoplus===undefined){throw("Error: ProtoPlus is required by ProtoPlus-UI.js");} Object.extend(document,{getViewPortDimensions:function(){var height;var width;if(typeof window.innerWidth!='undefined') {width=window.innerWidth;height=window.innerHeight;}else if(typeof document.documentElement!='undefined'&&typeof document.documentElement.clientWidth!='undefined'&&document.documentElement.clientWidth!==0){width=document.documentElement.clientWidth;height=document.documentElement.clientHeight;}else{width=document.getElementsByTagName('body')[0].clientWidth;height=document.getElementsByTagName('body')[0].clientHeight;} return{height:height,width:width};},stopTooltips:function(){document.stopTooltip=true;$$(".pp_tooltip_").each(function(t){t.remove();});return true;},startTooltips:function(){document.stopTooltip=false;},windowDefaults:{height:false,width:400,title:' ',titleBackground:'#F5F5F5',buttonsBackground:'#F5F5F5',background:'#FFFFFF',top:'25%',left:'25%',position:'absolute',winZindex:10001,borderWidth:10,borderColor:'#000',titleTextColor:'#777',resizable:false,borderOpacity:0.3,borderRadius:"5px",titleClass:false,contentClass:false,buttonsClass:false,closeButton:'X',fullScreenButton:'',allowFullScreen:false,defaultFullScreen:false,openEffect:true,closeEffect:true,dim:true,modal:true,dimColor:'#fff',dimOpacity:0.8,dimZindex:10000,dynamic:true,contentPadding:'8',closeTo:false,buttons:false,buttonsAlign:'right',hideTitle:false},window:function(options){var topOverridden=("top"in options);options=Object.extend(Object.deepClone(document.windowDefaults),options||{});options=Object.extend({onClose:Prototype.K,onInsert:Prototype.K,onDisplay:Prototype.K,onFullScreen:Prototype.K,onUnFullScreen:Prototype.K},options,{});options.dim=(options.modal!==true)?false:options.dim;options.width=options.width?parseInt(options.width,10):'';options.height=(options.height)?parseInt(options.height,10):false;options.borderWidth=parseInt(options.borderWidth,10);var winWidth=(options.width?(options.width=='auto'?'auto':options.width+'px'):'');var titleStyle={background:options.titleBackground,zIndex:1000,position:'relative',padding:'2px',borderBottom:'1px solid #C27A00',height:'35px',MozBorderRadius:'3px 3px 0px 0px',WebkitBorderRadius:'3px 3px 0px 0px',borderRadius:'3px 3px 0px 0px'};var dimmerStyle={background:options.dimColor,height:'100%',width:'100%',position:'fixed',top:'0px',left:'0px',opacity:options.dimOpacity,zIndex:options.dimZindex};var windowStyle={top:options.top,left:options.left,position:options.position,padding:options.borderWidth+'px',height:"auto",width:winWidth,zIndex:options.winZindex};var buttonsStyle={padding:'0px',display:'inline-block',width:'100%',borderTop:'1px solid #ffffff',background:options.buttonsBackground,zIndex:999,position:'relative',textAlign:options.buttonsAlign,MozBorderRadius:'0 0 3px 3px',WebkitBorderRadius:'0px 0px 3px 3px',borderRadius:'0px 0px 3px 3px'};var contentStyle={zIndex:1000,height:options.height!==false?options.height+'px':"auto",position:'relative',display:'inline-block',width:'100%'};var wrapperStyle={zIndex:600,MozBorderRadius:'3px',WebkitBorderRadius:'3px',borderRadius:'3px'};var titleTextStyle={fontWeight:'bold',color:options.titleTextColor,textShadow:'0 1px 1px rgba(0, 0, 0, 0.5)',paddingLeft:'10px',fontSize:'13px'};var backgroundStyle={height:'100%',width:'100%',background:options.borderColor,position:'absolute',top:'0px',left:'0px',zIndex:-1,opacity:options.borderOpacity};var titleCloseStyle={fontFamily:'Arial, Helvetica, sans-serif',color:'#aaa',cursor:'default'};var contentWrapperStyle={padding:options.contentPadding+'px',background:options.background};var dimmer;var fullScreened=false;if(options.dim){dimmer=new Element('div',{className:'protoplus-dim'});dimmer.observe('click',function(){closebox();}) dimmer.onmousedown=function(){return false;};dimmer.setStyle(dimmerStyle);} var win,tbody,tr,wrapper,background,title,title_table,title_text,title_fullscreen,title_close,content,buttons,contentWrapper,block={};win=new Element('div');win.insert(background=new Element('div'));win.insert(wrapper=new Element('div'));wrapper.insert(title=new Element('div'));title.insert(title_table=new Element('table',{width:'100%',height:'100%'}).insert(tbody=new Element('tbody').insert(tr=new Element('tr'))));tr.insert(title_text=new Element('td',{valign:'middle'}).setStyle('vertical-align: middle;'));tr.insert(title_fullscreen=new Element('td',{width:20,align:'center'}).setStyle('vertical-align: middle;'));tr.insert(title_close=new Element('td',{width:20,align:'center'}).setStyle('vertical-align: middle;'));wrapper.insert(contentWrapper=new Element('div',{className:'window-content-wrapper'}).insert(content=new Element('div')).setStyle(contentWrapperStyle));win.setTitle=function(title){title_text.update(title);return win;};win.blockWindow=function(){wrapper.insert(block=new Element('div').setStyle('position:absolute; top:0px; left:0px; height:100%; width:100%; opacity:0.5; background:#000; z-index:10000'));block.onclick=block.onmousedown=block.onmousemove=function(){return false;};return block;};win.unblockWindow=function(){block.remove();return win;};if(options.hideTitle){title.hide();title_close=new Element('div').setStyle('text-align:center;');wrapper.insert(title_close.setStyle('position:absolute;z-index:1111000; right:15px; top:15px;'));contentWrapper.setStyle({MozBorderRadius:titleStyle.MozBorderRadius,WebkitBorderRadius:titleStyle.WebkitBorderRadius,borderRadius:titleStyle.borderRadius});} win.buttons={};var buttonsDiv;if(options.buttons&&options.buttons.length>0){wrapper.insert(buttons=new Element('div',{className:'window-buttons-wrapper'}));if(!options.buttonsClass){buttons.setStyle(buttonsStyle);}else{buttons.addClassName(options.buttonsClass);} buttons.insert(buttonsDiv=new Element('div').setStyle('padding:12px;height:23px;'));$A(options.buttons).each(function(button,i){var color=button.color||'grey';var but=new Element('button',{className:'big-button buttons buttons-'+color,type:'button',name:button.name||"button-"+i,id:button.id||"button-"+i}).observe('click',function(){button.handler(win,but);});if(button.className){but.addClassName(button.className);} var butTitle=new Element('span').insert(button.title);if(button.icon){button.iconAlign=button.iconAlign||'left';var butIcon=new Element('img',{src:button.icon,align:button.iconAlign=='right'?'absmiddle':'left'}).addClassName("icon-"+button.iconAlign);if(button.iconAlign=='left'){but.insert(butIcon);} but.insert(butTitle);if(button.iconAlign=='right'){but.insert(butIcon);}}else{but.insert(butTitle);} if(button.align=='left'){but.setStyle('float:left');} but.changeTitle=function(title){butTitle.update(title);return but;};but.updateImage=function(options){butIcon.src=options.icon;options.iconAlign=options.iconAlign||button.iconAlign;if(options.iconAlign=='right'){butIcon.removeClassName('icon-left');butIcon.addClassName('icon-right');}else{butIcon.removeClassName('icon-right');butIcon.addClassName('icon-left');}};win.buttons[button.name]=but;if(button.hidden===true){but.hide();} if(button.disabled===true){but.disable();} if(button.style){but.setStyle(button.style);} buttonsDiv.insert(but);});}else{contentWrapper.setStyle({MozBorderRadius:buttonsStyle.MozBorderRadius,WebkitBorderRadius:buttonsStyle.WebkitBorderRadius,borderRadius:buttonsStyle.borderRadius});} win.setStyle(windowStyle);background.setStyle(backgroundStyle).setCSSBorderRadius(options.borderRadius);if(!options.titleClass){title.setStyle(titleStyle);}else{title.addClassName(options.titleClass);} if(!options.contentClass){content.setStyle(contentStyle).addClassName('window-content');}else{content.addClassName(options.contentClass);} wrapper.setStyle(wrapperStyle);title_text.setStyle(titleTextStyle);title_close.setStyle(titleCloseStyle);var closebox=function(key){document._onedit=false;if(options.onClose(win,key)!==false){var close=function(){if(dimmer){dimmer.remove();document.dimmed=false;} win.remove();$(document.body).setStyle({overflow:''});if(fullScreened){window.onresize=null;document.documentElement.style.overflow='visible';document.body.scroll="yes";}};if(options.closeEffect===true){win.shift({opacity:0,duration:0.3,onEnd:close});}else{close();} Event.stopObserving(window,'resize',win.reCenter);document.openWindows=$A(document.openWindows).collect(function(w){if(w!==win){return w;}}).compact();}};if(options.dim){$(document.body).insert(dimmer);document.dimmed=true;} title_text.insert(options.title);title_close.insert(options.closeButton);title_close.onclick=function(){closebox("CROSS");};content.insert(options.content);var fullScreenGeneric=function(){win.setStyle({width:'100%',height:'100%',position:'fixed',left:'-5px',top:'-8px'});win.down('.window-content').setStyle({height:parseInt(document.viewport.getHeight())-(parseInt($$('.window-buttons-wrapper')[0].getHeight())+40)+'px'});document.documentElement.style.overflow='hidden';document.body.scroll="no";window.onresize=function(e){options.onFullScreen();} options.onFullScreen();};var unFullScreenGeneric=function(){var width=options.width?options.width+'px':'auto';win.setStyle({width:width,height:'auto',position:'absolute'});win.down('.window-content').setStyle({height:'auto',position:'relative'});win.reCenter();window.onresize=null;document.documentElement.style.overflow='visible';document.body.scroll="yes";options.onUnFullScreen();};if(options.allowFullScreen){title_fullscreen.insert(options.fullScreenButton);title_fullscreen.onclick=function(){if(fullScreened){unFullScreenGeneric();}else{fullScreenGeneric();} fullScreened=!fullScreened;}} $(document.body).insert(win);if(options.openEffect===true){win.setStyle({opacity:0});win.shift({opacity:1,duration:0.5});} try{document._onedit=true;options.onInsert(win);}catch(e){} win.reCenter=function(){var vp=document.viewport.getDimensions();var vso=$(document.body).cumulativeScrollOffset();var bvp=win.getDimensions();var top=((vp.height-bvp.height)/2)+vso.top;if(top<0)top=0;var left=((vp.width-bvp.width)/2)+vso.left;if(topOverridden){top=options.top.toString();if(top.indexOf('%')===-1&&top.indexOf('px')===-1){top+="px";}}else{top+="px";} win.setStyle({top:top,left:left+"px"});if(dimmer){dimmer.setStyle({height:vp.height+'px',width:vp.width+'px'});}};win.reCenter();options.onDisplay(win);Event.observe(window,'resize',win.reCenter);if(options.resizable){wrapper.resizable({constrainViewport:true,element:content,sensitivity:20,onResize:function(h,w,type){if(type!='vertical'){win.setStyle({width:(w+(options.borderWidth*2)-10)+'px'});} if(content.isOverflow()){content.setStyle({overflow:'auto'});}else{content.setStyle({overflow:''});}}});} win.setDraggable({handler:title_text,constrainViewport:true,dynamic:options.dynamic,dragEffect:false});win.close=closebox;document.openWindows.push(win);if(options.defaultFullScreen){fullScreenGeneric();} return win;}});document.observe('keyup',function(e){e=document.getEvent(e);if(Event.isInput(e)){return;} if(document.openWindows.length>0){if(e.keyCode==27){document.openWindows.pop().close('ESC');}}});document.openWindows=[];document.createNewWindow=document.window;Protoplus.ui={isVisible:function(element){element=$(element);if(!element.parentNode){return false;} if(element&&element.tagName=="BODY"){return true;} if(element.style.display=="none"||element.style.visibility=="hidden"){return false;} return Protoplus.ui.isVisible(element.parentNode);},editable:function(elem,options){elem=$(elem);options=Object.extend({defaultText:" ",onStart:Prototype.K,onEnd:Prototype.K,processAfter:Prototype.K,processBefore:Prototype.K,onBeforeStart:Prototype.K,escapeHTML:false,doubleClick:false,onKeyUp:Prototype.K,className:false,options:[{text:"Please Select",value:"0"}],style:{background:"none",border:"none",color:"#333",fontStyle:"italic",width:"99%"},type:"text"},options||{});elem.onStart=options.onStart;elem.onEnd=options.onEnd;elem.defaultText=options.defaultText;elem.processAfter=options.processAfter;elem.cleanWhitespace();try{elem.innerHTML=elem.innerHTML||elem.defaultText;}catch(e){} var clickareas=[elem];if(options.labelEl){clickareas.push($(options.labelEl));} $A(clickareas).invoke('observe',options.doubleClick?"dblclick":"click",function(e){if(options.onBeforeStart(elem)===false){return;} if(elem.onedit){return;} elem.onedit=true;if(document.stopEditables){return true;} document._onedit=true;document.stopTooltips();var currentValue=elem.innerHTML.replace(/^\s+|\s+$/gim,"");var type=options.type;var op=$A(options.options);var blur=function(e){if(elem.keyEventFired){elem.keyEventFired=false;return;} if(input.colorPickerEnabled){return;} input.stopObserving("blur",blur);elem.stopObserving("keypress",keypress);finish(e,currentValue);};var input="";var keypress=function(e){if(type=="textarea"){return true;} if(e.shiftKey){return true;} if(input.colorPickerEnabled){return;} e=document.getEvent(e);if(e.keyCode==13||e.keyCode==3){elem.keyEventFired=true;elem.stopObserving("keypress",keypress);input.stopObserving("blur",blur);finish(e,currentValue);}};if(type.toLowerCase()=="textarea"){currentValue=currentValue.replace(/
/gi,"<br>");} if(options.className!=="edit-option"){currentValue=currentValue.unescapeHTML();} currentValue=(currentValue==options.defaultText)?"":currentValue;currentValue=options.processBefore(currentValue,elem);if(type.toLowerCase()=="textarea"){input=new Element("textarea");input.value=currentValue;input.observe("blur",blur);input.observe('keyup',options.onKeyUp);try{input.select();}catch(e){}}else if(["select","dropdown","combo","combobox"].include(type.toLowerCase())){input=new Element("select").observe("change",function(e){elem.keyEventFired=true;finish(e,currentValue);});if(typeof op[0]=="string"){op.each(function(text){input.insert(new Element("option").insert(text));});}else{op.each(function(pair,i){input.insert(new Element("option",{value:pair.value?pair.value:i}).insert(pair.text));});} input.selectOption(currentValue);input.observe("blur",blur);}else if(["radio","checkbox"].include(type.toLowerCase())){input=new Element("div");if(typeof op[0]=="string"){op.each(function(text,i){input.insert(new Element("input",{type:type,name:"pp",id:"pl_"+i})).insert(new Element("label",{htmlFor:"pl_"+i,id:"lb_"+i}).insert(text)).insert("
");});}else{op.each(function(pair,i){input.insert(new Element("input",{type:type,name:"pp",value:pair.value?pair.value:i,id:"pl_"+i})).insert(new Element("label",{htmlFor:"pl_"+i,id:"lb_"+i}).insert(pair.text)).insert("
");});}}else{input=new Element("input",{type:type,value:currentValue});input.observe("blur",blur);input.observe('keyup',options.onKeyUp);input.select();} if(options.className!==false){input.addClassName(options.className);}else{input.setStyle(options.style);} elem.update(input);elem.finishEdit=function(){blur({target:input});};document._stopEdit=function(){elem.keyEventFired=true;finish({target:input},currentValue);};elem.onStart(elem,currentValue,input);setTimeout(function(){input.select();},100);elem.observe("keypress",keypress);});var finish=function(e,oldValue){document._stopEdit=false;var elem=$(e.target);var val="";if(!elem.parentNode){return true;} var outer=$(elem.parentNode);outer.onedit=false;if("select"==elem.nodeName.toLowerCase()){val=elem.options[elem.selectedIndex].text;}else if(["checkbox","radio"].include(elem.type&&elem.type.toLowerCase())){outer=$(elem.parentNode.parentNode);val="";$(elem.parentNode).descendants().findAll(function(el){return el.checked===true;}).each(function(ch){if($(ch.id.replace("pl_","lb_"))){val+=$(ch.id.replace("pl_","lb_")).innerHTML+"
";}});}else{val=elem.value;} if(options.escapeHTML===true){val=val.escapeHTML();} try{var selected=elem.getSelected();if(val===""&&outer.defaultText){outer.update(outer.defaultText);}else{outer.update(outer.processAfter(val,outer,elem.getSelected()||val,oldValue));} document._onedit=false;document.startTooltips();setTimeout(function(){if($(outer.parentNode.parentNode).__drag_just_after_add!==true){outer.onEnd(outer,outer.innerHTML,oldValue,selected||val);}else{$(outer.parentNode.parentNode).__drag_just_after_add_on_end_relay=function(){outer.onEnd(outer,outer.innerHTML,oldValue,elem.getSelected()||val);};}},1);}catch(err){}};return elem;},setShadowColor:function(elem,color){elem=$(elem);$A(elem.descendants()).each(function(node){if(node.nodeType==Node.ELEMENT_NODE){node.setStyle({color:color});}});return elem;},cleanShadow:function(elem){elem=$(elem);elem.descendants().each(function(e){if(e.className=="pp_shadow"){e.remove();}});return elem;},getParentContext:function(element){element=$(element);try{if(!element.parentNode){return false;} if(element._contextMenuEnabled){return element;} if(element.tagName=='BODY'){return false;} return $(element.parentNode).getParentContext();}catch(e){alert(e);}},hasContextMenu:function(element){return!!element._contextMenuEnabled;},setContextMenu:function(element,options){element=$(element);options=Object.extend({others:[]},options||{});element._contextMenuEnabled=true;element.items={};$A(options.menuItems).each(function(item,i){if(item=='-'){element.items["seperator_"+i]=item;}else{if(!item.name){element.items["item_"+i]=item;}else{element.items[item.name]=item;}}});element.changeButtonText=function(button,text){element.items[button].title=text;return $(element.items[button].elem).select('.context-menu-item-text')[0].update(text);};element.getButton=function(button){return element.items[button].elem;};element.showButton=function(button){element.items[button].hidden=false;};element.hideButton=function(button){element.items[button].hidden=true;};element.enableButton=function(button){element.items[button].disabled=false;};element.disableButton=function(button){element.items[button].disabled=true;};element.options=options;options.others.push(element);var createListItem=function(context,item){var liItem=new Element('li').observe('contextmenu',Event.stop);if(Object.isString(item)&&item=="-"){liItem.insert("
");liItem.addClassName('context-menu-separator');context.insert(liItem);}else{if(item.icon){var img=new Element('img',{src:item.icon,className:(item.iconClassName||''),align:'left'}).setStyle('margin:0 4px 0 0;');liItem.insert(img);}else{liItem.setStyle('padding-left:24px');} item.handler=item.handler||Prototype.K;if(!item.disabled){liItem.addClassName('context-menu-item');liItem.observe('click',function(e){Event.stop(e);item.handler.bind(element)();$$('.context-menu-all').invoke('remove');});}else{liItem.addClassName('context-menu-item-disabled');} if(item.items){liItem.insert('');createInnerList(liItem,item);} if(item.hidden){liItem.hide();} liItem.insert(new Element('span',{className:'context-menu-item-text'}).update(item.title.shorten(26)));context.insert(liItem);} return liItem;};var getContPosition=function(container){var w=document.viewport.getWidth();var l=container.getLayout();var p=container.up('.context-menu-all');var isNotFit=(l.get('width')+l.get('cumulative-left'))>(w-200);if(!isNotFit&&p&&p.__pos){pos=p.__pos;}else if(isNotFit){pos="left";}else{pos="right";} container.__pos=pos;return pos;};var createInnerList=function(cont,itemConf){var container=new Element('div',{className:'context-menu-all'}).setStyle('z-index:1000000');var backPanel=new Element('div',{className:'context-menu-back'}).setOpacity(0.98);var context=new Element('div',{className:'context-menu'});container.insert(backPanel).insert(context);var title=new Element('div',{className:'context-menu-title'}).observe('contextmenu',Event.stop);title.insert(itemConf.title.shorten(26));context.insert(title);var it=itemConf.items;if(Object.isFunction(itemConf.items)){it=itemConf.items();} $A(it).each(function(item){var liItem=createListItem(context,item);});cont.insert(container.hide());container.setStyle({position:'absolute',top:'0px'});var t;var listopen=false;cont.mouseEnter(function(){if(itemConf.disabled){return;} if(listopen){return;} clearTimeout(t);container.show();listopen=true;var pos=getContPosition(container);container.style[pos]='-'+(container.getWidth()-5)+'px';},function(){clearTimeout(t);container.style.left=container.style.right="";container.hide();listopen=false;});};var openMenu=function(e,local,opt){opt=opt||{};Event.stop(e);if(local||(Prototype.Browser.Opera&&e.ctrlKey)||Event.isRightClick(e)||Prototype.Browser.IE){$$('.context-menu-all').invoke('remove');var element=e.target;element=element.getParentContext();if(element!==false){if(element.options.onStart){element.options.onStart();} var menuItems=element.menuItems;var container=new Element('div',{className:'context-menu-all'}).setStyle('z-index:1000000');var backPanel=new Element('div',{className:'context-menu-back'}).setOpacity(0.98);var context=new Element('div',{className:'context-menu'});container.insert(backPanel).insert(context);if(element.options.title){var title=new Element('div',{className:'context-menu-title'}).observe('contextmenu',Event.stop);title.insert(element.options.title);context.insert(title);} $H(element.items).each(function(pair){var item=pair.value;var liItem=createListItem(context,item);element.items[pair.key].elem=liItem;});$(document.body).insert(container.hide());var x=Event.pointer(e).x;var y=Event.pointer(e).y;var dim=document.viewport.getDimensions();var cDim=context.getDimensions();var sOff=document.viewport.getScrollOffsets();var top=(y-sOff.top+cDim.height)>dim.height&&(y-sOff.top)>cDim.height?(y-cDim.height)-20:y;var left=(x+cDim.width)>dim.width?(dim.width-cDim.width)-20:x;container.setStyle({position:'absolute',top:(opt.top?opt.top:top)+'px',left:(opt.left?opt.left:left)+'px'});if(element.options.onOpen){element.options.onOpen(context);} container.show();}}};element.openMenu=openMenu;$A(options.others).invoke('observe',Prototype.Browser.Opera?'click':'contextmenu',function(e){e.stop();var ev={};if(Prototype.Browser.IE){for(var k in e){ev[k]=e[k];}}else{ev=e;} setTimeout(function(){openMenu(ev);},0);});if(!document.contextMenuHandlerSet){document.contextMenuHandlerSet=true;$(document).observe('click',function(e){$$('.context-menu-all').invoke('remove');});} return element;},textshadow:function(element,options){element=$(element);options=Object.extend({light:"upleft",color:"#666",offset:1,opacity:1,padding:0,glowOpacity:0.1,align:undefined,imageLike:false},options||{});var light=options.light;var color=options.color;var dist=options.offset;var opacity=options.opacity;var textalign=(options.align)?options.align:$(elem).getStyle("textAlign");var padding=(options.padding)?options.padding+"px":$(elem).getStyle("padding");var text=elem.innerHTML;var container=new Element("div");var textdiv=new Element("div");var style={color:color,height:element.getStyle("height"),width:element.getStyle("width"),"text-align":textalign,padding:padding,position:"absolute","z-index":100,opacity:opacity};elem.innerValue=text;elem.update("");container.setStyle({position:"relative"});textdiv.update(text);container.appendChild(textdiv);for(var i=0;i"+options.title+"
"+text:text;element.hover(function(el,evt){var vpd=document.viewport.getDimensions();var getBoxLocation=function(e){var offTop=options.offset.top?options.offset.top:15;var offLeft=options.offset.left?options.offset.left:15;var top=(Event.pointerY(e)+offTop);var left=(Event.pointerX(e)+offLeft);var dim=tooldiv.getDimensions();if(left+dim.width>(vpd.width-20)){left-=dim.width+20+offLeft;} if(top+dim.height>(vpd.height-20)){top-=dim.height+offTop;} return{top:top,left:left};};if(document.stopTooltip){$$(".pp_tooltip_").each(function(t){t.remove();});return true;} outer=new Element("div",{className:'pp_tooltip_'}).setStyle({opacity:options.opacity,position:"absolute",zIndex:options.zIndex});if(options.className){tooldiv=new Element("div",{className:options.className}).setStyle({position:"relative",top:"0px",left:"0px",zIndex:10}).update(text);}else{tooldiv=new Element("div").setStyle({padding:"4px",background:"#eee",width:(options.width=="auto"?"auto":options.width+"px"),border:"1px solid #333",position:"absolute",top:"0px",left:"0px",zIndex:10}).update(text);tooldiv.setCSSBorderRadius('5px');} if(options.shadow){shadTop=options.shadow.top?parseInt(options.shadow.top,10):4;shadLeft=options.shadow.left?parseInt(options.shadow.left,10):4;shadBack=options.shadow.back?options.shadow.back:"#000";shadOp=options.shadow.opacity?options.shadow.opacity:0.2;if(options.className){shadow=new Element("div",{className:options.className||""}).setStyle({position:"absolute",borderColor:"#000",color:"#000",top:shadTop+"px",left:shadLeft+"px",zIndex:9,background:shadBack,opacity:shadOp});shadow.update(text);}else{shadow=new Element("div",{className:options.className||""}).setStyle({padding:"4px",border:"1px solid black",color:"#000",width:options.width+"px",position:"absolute",top:shadTop+"px",left:shadLeft+"px",zIndex:9,background:shadBack,opacity:shadOp});shadow.setCSSBorderRadius('5px');shadow.update(text);} outer.appendChild(shadow);} outer.appendChild(tooldiv);var makeItAppear=function(){if(options.fixed){var fixTop=options.fixed.top?parseInt(options.fixed.top,10):element.getHeight();var fixLeft=options.fixed.left?parseInt(options.fixed.left,10):element.getWidth()-50;outer.setStyle({top:fixTop+"px",left:fixLeft+"px"});}else{element.observe("mousemove",function(e){if(document.stopTooltip){$$(".pp_tooltip_").each(function(t){t.remove();});return true;} var loc=getBoxLocation(e);outer.setStyle({top:loc.top+"px",left:loc.left+"px"});});}};outer.delay=setTimeout(function(){if(options.fadeIn){document.body.appendChild(outer);var fl=getBoxLocation(evt);outer.setStyle({opacity:0,top:fl.top+"px",left:fl.left+"px"});dur=options.fadeIn.duration?options.fadeIn.duration:1;outer.appear({duration:dur,onEnd:makeItAppear()});}else{document.body.appendChild(outer);var l=getBoxLocation(evt);outer.setStyle({top:l.top+"px",left:l.left+"px"});setTimeout(makeItAppear,100);} if(options.duration){outer.duration=setTimeout(function(){if(options.fadeOut){dur=options.fadeOut.duration?options.fadeOut.duration:1;outer.fade({duration:dur,onEnd:function(){if(outer.parentNode){outer.remove();}}});}else{if(outer.parentNode){outer.remove();}}},options.duration*1000||0);}},options.delay*1000||0);},function(){if(document.stopTooltip){$$(".pp_tooltip_").each(function(t){t.remove();});return true;} if(outer){clearTimeout(outer.delay);clearTimeout(outer.duration);} if(options.fadeOut){dur=options.fadeOut.duration?options.fadeOut.duration:0.2;outer.fade({duration:dur,onEnd:function(){if(outer.parentNode){outer.remove();}}});}else{if(outer.parentNode){outer.remove();}}});return element;},softScroll:function(element,options){options=Object.extend({scrollSpeed:50},options||{});var scroll=new Element('div',{className:'scroll-bar'});var scrollStyle=new Element('div',{className:'scroll-style'});var table=new Element('table',{cellpadding:0,cellspacing:0,height:'100%'}).insert(new Element('tbody').insert(new Element('tr').insert(new Element('td',{valign:'top'}).setStyle('height:100%;padding:5px;').insert(scrollStyle))));scroll.insert(table);element.setStyle('overflow:hidden;');scroll.setStyle('position:absolute; top:0px; right:1px; width:16px; opacity:0; height:50%;');var container=element.wrap('div');element.updateScrollSize=function(){var ch;try{ch=container.measure('margin-box-height');}catch(e){ch=container.getHeight()+ (parseInt(container.getStyle('padding-top'),10)||0)+ (parseInt(container.getStyle('padding-bottom'),10)||0)+ (parseInt(container.getStyle('margin-top'),10)||0)+ (parseInt(container.getStyle('margin-bottom'),10)||0);} var sh=element.scrollHeight;if(sh<=0){return;} var per=ch*100/sh;if(per>100){scroll.hide();}else{scroll.show();} scroll.style.height=per+"%";};element.updateScrollSize();scroll.setDraggable({constraint:'vertical',dragClass:'scroll-onpress',onDrag:function(el){var top=parseInt(el.style.top,10);if(top<0){el.style.top="0px";return false;} var h=container.getHeight();var sh=scroll.getHeight();if((top+sh)>h){el.style.top=(h-(sh))+"px";return false;} scrollArea(top);}});function scrollArea(pos){var ch=container.getHeight();var sh=element.scrollHeight;var per=ch*100/sh;var posPer=pos*100/ch;var position=sh*posPer/100;element.scrollTop=Math.round(position);} function updateScrollBar(pos){var sh=element.scrollHeight;var ch=container.getHeight();var per=pos*100/sh;var position=ch*per/100;scroll.style.top=Math.round(position)+"px";} container.hover(function(){element.updateScrollSize();scroll.shift({opacity:1,duration:0.5});},function(){if(scroll.__dragging===true){return;} scroll.shift({opacity:0,duration:0.5});});container.setStyle('position:relative; display:inline-block;');container.insert(scroll);var stime;element.observe(Event.mousewheel,function(e){e.stop();var w=Event.wheel(e);if(w>0){element.scrollTop=element.scrollTop-options.scrollSpeed;}else if(w<0){element.scrollTop=element.scrollTop+options.scrollSpeed;} updateScrollBar(element.scrollTop);});},setDraggable:function(element,options){options=Object.extend({dragClass:"",handler:false,dragFromOriginal:false,onStart:Prototype.K,changeClone:Prototype.K,onDrag:Prototype.K,onDragEnd:Prototype.K,onEnd:Prototype.K,dragEffect:false,revert:false,clone:false,snap:false,cursor:"move",offset:false,constraint:false,constrainLeft:false,constrainRight:false,constrainTop:false,constrainBottom:false,constrainOffset:false,constrainViewport:false,constrainParent:false,dynamic:true},options||{});if(options.snap&&(typeof options.snap=="number"||typeof options.snap=="string")){options.snap=[options.snap,options.snap];} var mouseUp="mouseup",mouseDown="mousedown",mouseMove="mousemove";if(options.constrainOffset){if(options.constrainOffset.length==4){options.constrainTop=options.constrainTop?options.constrainTop:options.constrainOffset[0];options.constrainRight=options.constrainRight?options.constrainRight:options.constrainOffset[1];options.constrainBottom=options.constrainBottom?options.constrainBottom:options.constrainOffset[2];options.constrainLeft=options.constrainLeft?options.constrainLeft:options.constrainOffset[3];}} var handler;var stopDragTimer=false;var drag=function(e){Event.stop(e);if(mouseMove=="touchmove"){e=e.touches[0];} if(options.onDrag(drag_element,handler,e)===false){return;} var top=startY+(Number(Event.pointerY(e)-mouseY));var left=startX+(Number(Event.pointerX(e)-mouseX));if(options.offset){top=options.offset[1]+Event.pointerY(e);left=options.offset[0]+Event.pointerX(e);} if(options.snap){top=(top/options.snap[1]).round()*options.snap[1];left=(left/options.snap[0]).round()*options.snap[0];} top=(options.constrainBottom!==false&&top>=options.constrainBottom)?options.constrainBottom:top;top=(options.constrainTop!==false&&top<=options.constrainTop)?options.constrainTop:top;left=(options.constrainRight!==false&&left>=options.constrainRight)?options.constrainRight:left;left=(options.constrainLeft!==false&&left<=options.constrainLeft)?options.constrainLeft:left;if(options.constraint=="vertical"){drag_element.setStyle({top:top+"px"});}else if(options.constraint=="horizontal"){drag_element.setStyle({left:left+"px"});}else{drag_element.setStyle({top:top+"px",left:left+"px"});} if(stopDragTimer){clearTimeout(stopDragTimer);} options.onDrag(drag_element,handler,e);stopDragTimer=setTimeout(function(){options.onDragEnd(drag_element,handler,e);},50);};var mouseup=function(ev){Event.stop(ev);if(mouseUp=="touchend"){ev=e.touches[0];} if(options.dynamic!==true){document.temp.setStyle({top:element.getStyle('top'),left:element.getStyle('left')});element.parentNode.replaceChild(document.temp,element);document.temp.oldZIndex=element.oldZIndex;element=document.temp;} if(options.onEnd(drag_element,handler,ev)!==false){if(element.oldZIndex){drag_element.setStyle({zIndex:element.oldZIndex});}else{drag_element.setStyle({zIndex:''});} if(options.revert){if(options.revert===true){options.revert={easing:"sineIn",duration:0.5};} options.revert=Object.extend({left:drag_element.startX,top:drag_element.startY,opacity:1,duration:0.5,easing:'sineIn'},options.revert||{});drag_element.shift(options.revert);drag_element.startX=false;drag_element.startY=false;}else{if(options.dragEffect){drag_element.shift({opacity:1,duration:0.2});}}} element.__dragging=false;drag_element.removeClassName(options.dragClass);handler.setSelectable();drag_element.setSelectable();$(document.body).setSelectable();document.stopObserving(mouseMove,drag);document.stopObserving(mouseUp,mouseup);};if(options.handler){if(typeof options.handler=="string"){handler=(options.handler.startsWith("."))?element.descendants().find(function(h){return h.className==options.handler.replace(/^\./,"");}):$(options.handler);}else{handler=$(options.handler);}}else{handler=element;} handler.setStyle({cursor:options.cursor});handler.observe(mouseDown,function(e){Event.stop(e);var evt=e;if(mouseDown=="touchstart"){e=e.touches[0];} element.__dragging=true;if(document.stopDrag){return true;} if(options.dragFromOriginal&&e.target!=handler){return false;} var vdim=false,voff=false;if(options.constrainElement){voff=(Prototype.Browser.IE)?{top:0,left:0}:$(options.constrainElement).cumulativeOffset();vdim=$(options.constrainElement).getDimensions();} if(options.constrainParent){if($(element.parentNode).getStyle('position')=="relative"||$(element.parentNode).getStyle('position')=="absolute"){voff={top:0,left:0};}else{voff=(Prototype.Browser.IE)?{top:0,left:0}:$(element.parentNode).cumulativeOffset();} vdim=$(element.parentNode).getDimensions();} if(options.constrainViewport){voff=$(document.body).cumulativeScrollOffset();vdim=document.viewport.getDimensions();} if(vdim){vdim.height+=voff.top;vdim.width+=voff.left;options.constrainTop=voff.top+1;options.constrainBottom=vdim.height-(element.getHeight()+3);options.constrainRight=vdim.width-(element.getWidth()+3);options.constrainLeft=voff.left+1;} var temp_div;if(options.dynamic!==true){try{document.temp=element;temp_div=new Element('div').setStyle({height:element.getHeight()+"px",width:element.getWidth()+"px",border:'1px dashed black',top:element.getStyle('top')||0,left:element.getStyle('left')||0,zIndex:element.getStyle('zIndex')||0,position:element.getStyle('position'),background:'#f5f5f5',opacity:0.3});}catch(err){} element.parentNode.replaceChild(temp_div,element);element=temp_div;} if(["relative","absolute"].include($(element.parentNode).getStyle('position'))){startX=element.getStyle("left")?parseInt(element.getStyle("left"),10):element.offsetLeft;startY=element.getStyle("top")?parseInt(element.getStyle("top"),10):element.offsetTop;}else{var eloff=element.cumulativeOffset();startX=eloff.left;startY=eloff.top;} mouseX=Number(Event.pointerX(e));mouseY=Number(Event.pointerY(e));if(options.clone){drag_element=options.changeClone(element.cloneNode({deep:true}),startX,startY);$(document.body).insert(drag_element);}else{drag_element=element;} options.onStart(drag_element,handler,e);drag_element.addClassName(options.dragClass);element.oldZIndex=element.getStyle("z-index")||0;if(options.dragEffect){drag_element.shift({opacity:0.7,duration:0.2});} drag_element.setStyle({position:"absolute",zIndex:99998});if(options.revert&&!drag_element.startX&&!drag_element.startY){drag_element.startX=startX;drag_element.startY=startY;} drag_element.setUnselectable();handler.setUnselectable();$(document.body).setUnselectable();document.observe(mouseMove,drag);document.observe(mouseUp,mouseup);});return element;},rating:function(element,options){element=$(element);options=Object.extend({imagePath:"stars.png",onRate:Prototype.K,resetButtonImage:false,resetButtonTitle:'Cancel Your Rating',resetButton:true,inputClassName:'',titles:[],disable:false,disabled:element.getAttribute("disabled")?element.getAttribute("disabled"):false,stars:element.getAttribute("stars")?element.getAttribute("stars"):5,name:element.getAttribute("name")?element.getAttribute("name"):"rating",value:element.getAttribute("value")?element.getAttribute("value"):0,cleanFirst:false,selectedRating:element.getAttribute("value")?(element.getAttribute("value")-element.dataset.lowest+1):0},options||{});if(element.converted){return element;} element.converted=true;element.addClassName('form-star-rating');var image={blank:"0px 0px",over:"-16px 0px",clicked:"-32px 0px",half:"-48px 0px"};var hidden=new Element("input",{type:"hidden",name:options.name,className:options.inputClassName});var stardivs=$A([]);element.disabled=(options.disabled=="true"||options.disabled===true)?true:false;element.setStyle({display:'inline-block',width:((parseInt(options.stars,10)+(options.resetButton?1:0))*20)+"px",cursor:options.disabled?"default":"pointer"});element.setUnselectable();if(options.cleanFirst){element.update();} var setStar=function(i){var elval=i;i=i||0;var desc=$A(element.descendants());desc.each(function(e){e.setStyle({backgroundPosition:image.blank}).removeClassName("rated");});desc.each(function(e,c){if(c0){element.descendants().each(function(e,c){c++;if(c<=options.selectedRating){e.setStyle({backgroundPosition:image.clicked}).addClassName("rated");} if(options.selectedRating>c-1&&options.selectedRating=barWidth)?barWidth:l;sliderButton.setStyle({left:l+"px"});updateValue(l);};var sliderKeys=function(e){e=document.getEvent(e);if(e.keyCode==37){moveLEFT(5);}else if(e.keyCode==39){moveRIGTH(5);}};var sliderWheel=function(e){if(!sliderOut.__hasFocus){return true;} e.stop();sliderOut.focus();var w=Event.wheel(e);if(w>0){moveRIGTH(5);}else if(w<0){moveLEFT(5);}};var updateValue=function(pos){var total=barWidth;if(parseInt(pos,10)<=3){element.value=0;}else{var a=Math.round((parseInt(pos,10)*options.maxValue)/total);element.value=parseInt(a,10);} sliderOut.value=element.value===0?"":element.value;sliderTable.value=sliderOut.value;options.onUpdate(element.value);statTD.innerHTML=element.value;element.run('keyup');return element.value;};sliderOut.setStyle({width:options.width+'px',position:'relative',overflow:'hidden',outline:'none'});sliderBar.setStyle({border:'1px solid #999',background:'#eee',margin:'8px',overflow:'hidden',height:'3px'}).setCSSBorderRadius('4px');sliderButton.setStyle({position:'absolute',height:'13px',width:'13px',background:options.buttonBack,overflow:'hidden',border:'1px solid transparent',top:'3px',left:options.value+'px'}).setCSSBorderRadius('8px');startTD.setStyle({fontFamily:'Verdana',fontSize:'9px'});statTD.setStyle({fontFamily:'Verdana',fontSize:'9px'});endTD.setStyle({fontFamily:'Verdana',fontSize:'9px'});sliderOut.insert(sliderBar).insert(sliderButton);sliderTable.insert(tbody.insert(tr).insert(tr2));sliderTD.insert(sliderOut);tr.insert(sliderTD);tr2.insert(startTD).insert(statTD).insert(endTD);sliderButton.setDraggable({constraint:'horizontal',dragEffect:false,cursor:'default',constrainLeft:3,constrainRight:barWidth,onDrag:function(i){updateValue(i.getStyle('left'));}});sliderOut.observe('focus',function(){sliderOut.__hasFocus=true;sliderOut.setStyle({borderColor:'#333'});}).observe('blur',function(){sliderOut.__hasFocus=false;sliderOut.setStyle({borderColor:'#ccc'});});sliderOut.observe('keypress',sliderKeys).observe(Event.mousewheel,sliderWheel);sliderOut.observe('click',function(e){if(e.target.id==sliderButton.id){return false;} var l=(Event.pointerX(e)-sliderBar.cumulativeOffset().left);l=l<3?3:l;l=l>barWidth?barWidth:l;sliderButton.shift({left:l,duration:0.5});updateValue(l);});var hidden=new Element('input',{type:'hidden',className:'form-slider',name:element.name,value:defaultValue,id:element.id});element.parentNode.replaceChild(hidden,element);element=hidden;$(hidden.parentNode).insert(sliderTable.setUnselectable());hidden.setSliderValue=function(val){var v=valueToPixel(val);sliderButton.shift({left:v,duration:0.5});updateValue(v);};return hidden;},spinner:function(element,options){element=$(element);options=Object.extend({width:60,cssFloat:false,allowNegative:false,addAmount:1,maxValue:false,minValue:false,readonly:false,value:false,allowEmpty:false,size:5,imgPath:'images/',onChange:Prototype.K},options||{});element.size=options.size;if(options.value===false){if(!(options.allowEmpty&&element.value==="")){element.value=parseFloat(element.value)||'0';}}else{element.value=options.value;} if(options.minValue) {if(parseFloat(element.value)=Number(options.maxValue)){return;} element.value=parseFloat(element.value)+parseFloat(options.addAmount);options.onChange(element.value);};var numberDOWN=function(e){if(!parseFloat(element.value)){element.value=0;} var newValue=parseFloat(element.value)-parseFloat(options.addAmount);if(options.minValue){if(Number(newValue)=0){scr=140;} if(sc.y>=colorTable.getHeight()-140){scr=0;}else{scr=sc.y+140;} overFlowDiv.shift({scrollTop:scr,link:'ignore',duration:0.3});});var OK=new Element('input',{type:'button',value:'OK'}).observe('click',function(){if(element.tagName=="INPUT"){element.value=box.value;element.focus();} table.remove();setTimeout(function(){element.colorPickerEnabled=false;options.onComplete(box.value,element,table);},100);});if(options.buttonClass){$(flip,OK).invoke('addClassName',options.buttonClass);}else{$(flip,OK).invoke('setStyle',{padding:'1px',margin:'1px',background:'#f5f5f5',border:'1px solid #ccc'});} element.closeColorPicker=function(){OK.run('click');};selectTD.insert(box).insert(flip).insert(OK);var colorTable=new Element('table',{cellpadding:0,cellspacing:0,border:0,width:140});var colorTbody=new Element('tbody'),colCount=0,colTR;$H(validCSSColors).each(function(color){if(colCount==7){colCount=0;} if(colCount++===0){colTR=new Element('tr');colorTbody.insert(colTR);} var tdSize=20;var pick=function(e){box.value=color.value;box.setStyle({background:box.value,color:Protoplus.Colors.invert(box.value)});options.onPicked(box.value,element,table);};if(color.value===false){colTR.insert(new Element('td',{width:tdSize,height:tdSize}).setStyle({background:'#fff'}).setStyle({}));}else{colTR.insert(new Element('td',{width:tdSize,height:tdSize}).setStyle({background:color.value}).observe('click',pick).tooltip(color.value,{delay:0.6,width:'auto'}));}});colorTable.insert(colorTbody);var overFlowDiv=new Element('div').setStyle({outline:'1px solid #fff',border:'1px solid #666',overflow:'hidden',height:'140px'});var preTable=new Element('table',{cellPadding:0,cellspacing:0,width:40}).setStyle({outline:'1px solid #fff',border:'1px solid #666',overflow:'hidden',height:'140px'});var preTbody=new Element('tbody');preTable.insert(preTbody);colorTD2.insert(preTable);colorTD.insert(overFlowDiv.insert(colorTable));var preColors=[["Black:#000000","Navy:#000080"],["Blue:#0000FF","Magenta:#FF00FF"],["Red:#FF0000","Brown:#A52A2A"],["Pink:#FFC0CB","Orange:#FFA500"],["Green:#008000","Yellow:#FFFF00"],["Gray:#808080","Turquoise:#40E0D0"],["Cyan:#00FFFF","White:#FFFFFF"]];$R(0,6).each(function(i){var tr=new Element('tr');preTbody.insert(tr);tr.insert(new Element('td',{height:20,width:20}).setText(' ').setStyle({background:preColors[i][0].split(':')[1]}).tooltip(preColors[i][0].split(':')[0],{delay:0.6,width:'auto'}).observe('click',function(){box.value=preColors[i][0].split(':')[1];box.setStyle({background:box.value,color:Protoplus.Colors.invert(box.value)});options.onPicked(box.value,element,table);}));tr.insert(new Element('td',{height:20,width:20}).setText(' ').setStyle({background:preColors[i][1].split(':')[1]}).tooltip(preColors[i][1].split(':')[0],{delay:0.6,width:'auto'}).observe('click',function(){box.value=preColors[i][1].split(':')[1];box.setStyle({background:box.value,color:Protoplus.Colors.invert(box.value)});options.onPicked(box.value,element,table);}));});var top=element.cumulativeOffset().top+element.getHeight();var left=element.cumulativeOffset().left;table.setStyle({position:'absolute',top:top+3+"px",left:left+2+'px'});table.setDraggable({handler:table.select('.titleHandler')[0],dragEffect:false});$(document.body).insert(table);options.onEnd(element,table);overFlowDiv.setScroll({y:'0'});element.colorPickerEnabled=true;});return element;},colorPicker2:function(element,options){options=Object.extend({onStart:Prototype.K,onEnd:Prototype.K,trigger:false,onPicked:Prototype.K,onComplete:Prototype.K,hideOnBlur:false,buttonClass:'big-button buttons'},options||{});var customColorHex;$(options.trigger||element).observe('click',function(){var docEvent=false;if(element.colorPickerEnabled){return element;} if(options.onStart()===false){return element;} if(options.hideOnBlur){setTimeout(function(){docEvent=Element.on(document,'click',function(e){var el=Event.findElement(e,'.plugin, ');if(!el){element.closeColorPicker();}});},0);} element.colorPickerEnabled=true;var scrollOffset=element.cumulativeScrollOffset();var stop=1;var top=element.measure('cumulative-top')+2;var left=element.measure('cumulative-left')+1-scrollOffset.left;var height=element.measure('border-box-height');var plugin=new Element('div',{className:'plugin edit-box'});var plugCUR=new Element('div',{className:'plugCUR'});var plugHEX=new Element('input',{type:'text',size:'10',className:'plugHEX'});var SV=new Element('div',{className:'SV'}).setUnselectable();var SVslide=new Element('div',{className:'SVslide'});var H=new Element('form',{className:'H'}).setUnselectable();var Hslide=new Element('div',{className:'Hslide'});var Hmodel=new Element('div',{className:'Hmodel'});var complete=new Element('button',{type:'button',className:''});plugin.insert('
').insert(SV).insert(H);plugin.insert(plugCUR).insert(plugHEX.setValue('#FFFFFF')).insert(complete.update('OK'));SV.insert(SVslide.update('
'));H.insert(Hslide.update('
')).insert(Hmodel);plugin.setStyle({position:'absolute',top:(top+height)+'px',left:left+'px',zIndex:'10000000'});SVslide.setStyle('top:-4px; left:-4px;');Hslide.setStyle('top:0px; left:-8px;');complete.setStyle('float:right;margin-top:8px;').addClassName(options.buttonClass);plugin.observe('mousedown',function(e){HSVslide('drag',plugin,e);});plugHEX.observe('mousedown',function(e){stop=0;setTimeout(function(){stop=1;},100);});plugHEX.observe('keyup',function(){if(plugHEX.value.length>=7){setValue(plugHEX.value);}});plugHEX.observe('click',function(){Form.Element.select(this);});SV.observe('mousedown',function(e){HSVslide(SVslide,plugin,e);});H.observe('mousedown',function(e){HSVslide(Hslide,plugin,e);});complete.observe('click',function(){plugin.remove();element.colorPickerEnabled=false;if(docEvent){docEvent.stop();} customColorHex=plugHEX.value;options.onComplete(plugHEX.value);});element.closeColorPicker=function(){complete.run('click');};function abPos(o){o=(typeof(o)=='object'?o:$(o));var z={X:0,Y:0};while(o!==null){z.X+=o.offsetLeft;z.Y+=o.offsetTop;o=o.offsetParent;} return(z);} function within(v,a,z){return((v>=a&&v<=z)?true:false);} function XY(e,v){var evt=e||window.event;var z=[Event.pointerX(evt),Event.pointerY(evt)];v=parseInt(v,10);return(z[!isNaN(v)?v:0]);} var maxValue={'H':360,'S':100,'V':100};var HSV={H:360,S:100,V:100};var slideHSV={H:360,S:100,V:100};function HSVslide(d,o,e){function tXY(e){tY=XY(e,1)-ab.Y;tX=XY(e)-ab.X;} function mkHSV(a,b,c){return(Math.min(a,Math.max(0,Math.ceil((parseInt(c,10)/b)*a))));} function ckHSV(a,b){if(within(a,0,b)){return(a);} else if(a>b){return(b);} else if(a<0){return('-'+oo);}} function drag(e){if(!stop){if(d!='drag'){tXY(e);} if(d==SVslide){ds.left=ckHSV(tX-oo,162)+'px';ds.top=ckHSV(tY-oo,162)+'px';slideHSV.S=mkHSV(100,162,ds.left);slideHSV.V=100-mkHSV(100,162,ds.top);HSVupdate();}else if(d==Hslide){var ck=ckHSV(tY-oo,163),r='HSV',z={};ds.top=(ck)+'px';slideHSV.H=mkHSV(360,163,ck);z.H=maxValue.H-mkHSV(maxValue.H,163,ck);z.S=HSV.S;z.V=HSV.V;HSVupdate(z);SV.style.backgroundColor='#'+color.HSV_HEX({H:HSV.H,S:100,V:100});}else if(d=='drag'){ds.left=XY(e)+oX-eX+'px';ds.top=XY(e,1)+oY-eY+'px';}}} if(stop){stop='';var ds=$(d!='drag'?d:o).style;if(d=='drag'){var oX=parseInt(ds.left,10),oY=parseInt(ds.top,10),eX=XY(e),eY=XY(e,1);}else{var ab=abPos($(o)),tX,tY,oo=(d==Hslide)?0:4;ab.X+=10;ab.Y+=22;if(d==SVslide){slideHSV.H=HSV.H;}} document.onmousemove=drag;document.onmouseup=function(){stop=1;document.onmousemove='';document.onmouseup='';};drag(e);}} function HSVupdate(v){v=HSV=v?v:slideHSV;v=color.HSV_HEX(v);plugHEX.value='#'+v;plugCUR.style.background='#'+v;if(element.tagName=='BUTTON'){element.__colorvalue='#'+v;}else{element.value='#'+v;} options.onPicked('#'+v,element,plugin);return(v);} function setValue(colorcode){if("transparent".search(colorcode)==-1){var rgb=Protoplus.Colors.getRGBarray(colorcode);var hsv=color.RGB_HSV(rgb[0],rgb[1],rgb[2]);SV.style.backgroundColor='#'+color.HSV_HEX({H:hsv.H,S:100,V:100});Hslide.style.top=Math.abs(Math.ceil((hsv.H*163)/360)-163)+"px";var t=Math.abs((Math.floor((hsv.V*162)/100))-162);var l=Math.abs((Math.floor((hsv.S*162)/100)));if(t<=0){t=t-4;} if(l<=0){l=l-4;} SVslide.style.top=t+"px";SVslide.style.left=l+"px";HSVupdate(hsv);}} element.setColorPickerValue=setValue;function loadSV(){var z='';for(var i=165;i>=0;i--){z+="

<\/div>";} Hmodel.innerHTML=z;} var color={cords:function(W){var W2=W/2,rad=(hsv.H/360)*(Math.PI*2),hyp=(hsv.S+(100-hsv.V))/100*(W2/2);$('mCur').style.left=Math.round(Math.abs(Math.round(Math.sin(rad)*hyp)+W2+3))+'px';$('mCur').style.top=Math.round(Math.abs(Math.round(Math.cos(rad)*hyp)-W2-21))+'px';},HEX:function(o){o=Math.round(Math.min(Math.max(0,o),255));return("0123456789ABCDEF".charAt((o-o%16)/16)+"0123456789ABCDEF".charAt(o%16));},RGB_HSV:function(r,g,b){r=r/255;g=g/255;b=b/255;var max=Math.max(r,g,b),min=Math.min(r,g,b);var h,s,v=max;var d=max-min;s=max===0?0:d/max;if(max==min){h=0;}else{switch(max){case r:h=(g-b)/d+(g0){if(H>=1){H=0;} H=6*H;F=H-Math.floor(H);A=Math.round(255*V*(1-S));B=Math.round(255*V*(1-(S*F)));C=Math.round(255*V*(1-(S*(1-F))));V=Math.round(255*V);switch(Math.floor(H)){case 0:R=V;G=C;B=A;break;case 1:R=B;G=V;B=A;break;case 2:R=A;G=V;B=C;break;case 3:R=A;G=B;B=V;break;case 4:R=C;G=A;B=V;break;case 5:R=V;G=A;B=B;break;} return({'R':R?R:0,'G':G?G:0,'B':B?B:0,'A':1});}else{return({'R':(V=Math.round(V*255)),'G':V,'B':V,'A':1});}},HSV_HEX:function(o){return(color.RGB_HEX(color.HSV_RGB(o)));}};$(document.body).insert(plugin);loadSV();if(customColorHex=='transparent'){plugHEX.value=customColorHex;} else{setValue(element.__colorvalue||element.value||"#FFFFFF");} options.onEnd(element,plugin);return element;});},miniLabel:function(element,label,options){options=Object.extend({position:'bottom',color:'#666',size:9,text:'',nobr:false},options||{});element.wrap('span');span=$(element.parentNode);span.setStyle({whiteSpace:'nowrap',cssFloat:'left',marginRight:'5px'});var labelStyle={paddingLeft:'1px',fontSize:options.size+"px",color:options.color,cursor:'default'};var labelClick=function(){element.focus();};var br='
';if(options.nobr){br='';} if(options.position=="top"){element.insert({before:new Element('span').setText(label+br).setStyle(labelStyle).observe('click',labelClick)}).insert({after:options.text});}else{element.insert({after:new Element('span').setText(br+label).setStyle(labelStyle).observe('click',labelClick)}).insert({after:options.text});} return span;},hint:function(element,value,options){element=$(element);if("placeholder"in element){element.writeAttribute('placeholder',value);return element;} if(element.type=='number'){element.value="0";return element;} if(element.removeHint){return element.hintClear();} options=Object.extend({hintColor:'#bbb'},options||{});var color=element.getStyle('color')||'#000';if(element.value===''){element.setStyle({color:options.hintColor});element.value=value;element.hinted=true;} var focus=function(){if(element.value==value){element.value="";element.setStyle({color:color}).hinted=false;}};var blur=function(){if(element.value===""){element.value=value;element.setStyle({color:options.hintColor}).hinted=true;}};var submit=function(){if(element.value==value){element.value="";element.hinted=false;}};element.observe('focus',focus);element.observe('blur',blur);if(element.form){$(element.form).observe('submit',submit);} element.runHint=blur;element.clearHint=function(){element.value="";element.setStyle({color:color}).hinted=false;};element.hintClear=function(){element.value=value;element.setStyle({color:options.hintColor}).hinted=true;return element;};element.removeHint=function(){element.setStyle({color:color});if(element.value==value){element.value="";} element.hintClear=undefined;element.hinted=undefined;element.removeHint=undefined;element.stopObserving('focus',focus);element.stopObserving('blur',blur);if(element.form){$(element.form).stopObserving('submit',submit);} return element;};return element;},resizable:function(element,options){options=Object.extend({sensitivity:10,overflow:0,onResize:Prototype.K,onResizeEnd:Prototype.K,imagePath:'images/resize.png',element:false,maxHeight:false,minHeight:false,maxWidth:false,minWidth:false,maxArea:false,autoAdjustOverflow:true,constrainViewport:true,constrainParent:false,keepAspectRatio:false,displayHandlers:true},options,{});var handlerElem=$(element);if(options.element){element=$(options.element);}else{element=$(element);} element.resized=true;var elementPos=handlerElem.getStyle('position');if(!elementPos||elementPos=='static'){handlerElem.setStyle({position:'relative'});} var ratio;var firstDim=element.getDimensions();var paddings={top:(parseInt(element.getStyle('padding-top'),10)||0)+(parseInt(element.getStyle('padding-bottom'),10)||0),left:(parseInt(element.getStyle('padding-left'),10)||0)+(parseInt(element.getStyle('padding-right'),10)||0)};var handler=new Element('div'),rightHandler=new Element('div'),bottomHandler=new Element('div');handler.setStyle({height:options.sensitivity+'px',width:options.sensitivity+'px',position:'absolute',bottom:'-'+options.overflow+'px',right:'-'+options.overflow+'px',cursor:'se-resize',zIndex:10000});rightHandler.setStyle({height:'100%',width:options.sensitivity+'px',position:'absolute',top:'0px',right:'-'+options.overflow+'px',cursor:'e-resize',zIndex:10000});bottomHandler.setStyle({height:options.sensitivity+'px',width:'100%',position:'absolute',bottom:'-'+options.overflow+'px',left:'0px',cursor:'s-resize',zIndex:10000});handler.setStyle({background:'url('+options.imagePath+') no-repeat bottom right'});var resize=function(e,type){e.stop();document.stopDrag=true;handlerElem.setUnselectable();$(document.body).setUnselectable();var sDim=$H(element.getDimensions()).map(function(d){if(d.key=="height"){return d.value-paddings.top;}else if(d.key=="width"){return d.value-paddings.left;} return d.value;});var startDim={height:sDim[1],width:sDim[0]};if(options.keepAspectRatio){ratio=Math.abs(startDim.height/startDim.width);} var offs=element.cumulativeOffset();var pdim=$(element.parentNode).getDimensions();var poff=$(element.parentNode).cumulativeOffset();var mouseStart={top:Event.pointerY(e),left:Event.pointerX(e)};var dim=document.viewport.getDimensions();var overflowHeight="";var overflowWidth="";switch(type){case"both":handler.setStyle('height:100%; width:100%');break;case"horizontal":rightHandler.setStyle({width:'100%'});break;case"vertical":bottomHandler.setStyle({height:'100%'});break;} var setElementSize=function(dims){var height=dims.height;var width=dims.width;var type=dims.type||'both';if(height){height=(options.maxHeight&&height>=options.maxHeight)?options.maxHeight:height;height=(options.minHeight&&height<=options.minHeight)?options.minHeight:height;if(options.maxArea){if(height*element.getWidth()>=options.maxArea){return;}} element.setStyle({height:height+"px"});} if(width){width=(options.maxWidth&&width>=options.maxWidth)?options.maxWidth:width;width=(options.minWidth&&width<=options.minWidth)?options.minWidth:width;if(options.maxArea){if(element.getHeight()*width>=options.maxArea){return;}} element.setStyle({width:width+"px"});} options.onResize((height||startDim.height)+paddings.top,(width||startDim.width)+paddings.left,type);};var mousemove=function(e){e.stop();if(type!="horizontal"){var height=startDim.height+(Event.pointerY(e)-mouseStart.top);var hskip=false;if(options.constrainViewport){hskip=((height+offs.top)>=(dim.height-3));} if(options.constrainParent){hskip=((height+offs.top+paddings.top)>=(pdim.height+poff.top-3));if(hskip){setElementSize({height:(pdim.height+poff.top-3)-(offs.top+paddings.top+3),type:type});}} if(!hskip){setElementSize({height:height,type:type});if(options.keepAspectRatio){setElementSize({width:height/ratio,type:type});}}} if(type!="vertical"){var width=startDim.width+(Event.pointerX(e)-mouseStart.left);var wskip=false;if(options.constrainViewport){wskip=((width+offs.left)>=(dim.width-3));} if(options.constrainParent){wskip=((width+offs.left+paddings.left)>=(pdim.width+poff.left-3));if(wskip){setElementSize({width:(pdim.width+poff.left-3)-(offs.left+paddings.left+3),type:type});}} if(!wskip){setElementSize({width:width,type:type});if(options.keepAspectRatio){setElementSize({height:width*ratio,type:type});}}}};var mouseup=function(){handler.setStyle({height:options.sensitivity+'px',width:options.sensitivity+'px'});rightHandler.setStyle({width:options.sensitivity+'px'});bottomHandler.setStyle({height:options.sensitivity+'px'});document.stopObserving('mousemove',mousemove).stopObserving('mouseup',mouseup).stopDrag=false;handlerElem.setSelectable();options.onResizeEnd(element.getHeight(),element.getWidth());$(document.body).setSelectable();};document.observe('mousemove',mousemove).observe('mouseup',mouseup);return false;};handler.observe('mousedown',function(e){resize(e,'both');});rightHandler.observe('mousedown',function(e){resize(e,'horizontal');});bottomHandler.observe('mousedown',function(e){resize(e,'vertical');});element.hideHandlers=function(){handler.hide();rightHandler.hide();bottomHandler.hide();};element.showHandlers=function(){handler.show();rightHandler.show();bottomHandler.show();};handlerElem.insert(bottomHandler).insert(rightHandler).insert(handler);return handlerElem;},positionFixed:function(element,options){element=$(element);options=Object.extend({offset:10,onPinned:Prototype.K,onUnpinned:Prototype.K,onBeforeScroll:Prototype.K,onBeforeScrollFail:Prototype.K,onScroll:Prototype.K},options||{});var off=element.cumulativeOffset();var sOff=element.cumulativeScrollOffset();var top=off.top+sOff.top;var left=off.left+sOff.left;var onScroll=function(){if(element.pinned){return true;} var style={};var bodyOff=$(document.body).cumulativeScrollOffset();if(top<=bodyOff.top+options.offset){style={position:'fixed',top:options.offset+'px'};}else{style={position:'absolute',top:top+'px'};} if(options.onBeforeScroll(element,parseInt(style.top,10),bodyOff.top)!==false){element.setStyle(style);options.onScroll(element,bodyOff.top);}else{if(element.style.position=="fixed"){element.setStyle({position:'absolute',top:bodyOff.top+options.offset+'px'});options.onBeforeScrollFail(element,parseInt(style.top,10),bodyOff.top);}}};element.pin=function(){var bodyOff=$(document.body).cumulativeScrollOffset();element.style.top=bodyOff.top+options.offset+'px';element.style.position='absolute';options.onPinned(element);element.pinned=true;};element.isPinned=function(){options.onPinned(element);return element.pinned;};element.unpin=function(){element.pinned=false;onScroll();options.onUnpinned(element);};element.updateScroll=onScroll;element.updateTop=function(topLimit){top=topLimit;return element;};Event.observe(window,'scroll',onScroll);return element;},positionFixedBottom:function(element,options){element=$(element);options=Object.extend({offset:0,onPinned:Prototype.K,onUnpinned:Prototype.K,onBeforeScroll:Prototype.K,onScroll:Prototype.K},options||{});var off=element.cumulativeOffset();var sOff=element.cumulativeScrollOffset();var top=off.top+sOff.top;var h=element.getHeight();var left=off.left+sOff.left;var onScroll=function(){if(element.pinned){return true;} var style={};var bodyOff=$(document.body).cumulativeScrollOffset();if(top+h>=bodyOff.top+options.offset){style={position:'fixed',bottom:options.offset+'px'};}else{if(element.style.position=="fixed"){element.setStyle({position:'absolute',top:bodyOff.top+options.offset+'px'});options.onBeforeScrollFail(element,parseInt(style.top,10),bodyOff.top);}}};onScroll();element.pin=function(){var bodyOff=$(document.body).cumulativeScrollOffset();element.style.top=bodyOff.top+options.offset+'px';element.style.position='absolute';options.onPinned(element);element.pinned=true;};element.isPinned=function(){options.onPinned(element);return element.pinned;};element.unpin=function(){element.pinned=false;onScroll();options.onUnpinned(element);};element.updateScroll=onScroll;element.updateTop=function(topLimit){top=topLimit;return element;};Event.observe(window,'scroll',onScroll);return element;},keepInViewport:function(element,options){element=$(element);options=Object.extend({offset:[10,10],offsetLeft:false,offsetTop:false,delay:0.1,onPinned:Prototype.K,onUnpinned:Prototype.K,onBeforeScroll:Prototype.K,onScroll:Prototype.K,smooth:false,horzontal:false,vertical:true,animation:{duration:0.2,easing:'sineOut'},topLimit:parseInt(element.getStyle('top')||0,10),leftLimit:parseInt(element.getStyle('left')||0,10)},options||{});options.animation=Object.extend({duration:0.4},options.animation||{});options.delay*=1000;if(typeof options.offset=='number'){options.offsetLeft=options.offset;options.offsetTop=options.offset;}else{options.offsetLeft=options.offset[0];options.offsetTop=options.offset[1];} var timer=false;var onScroll=function(e){if(element.pinned){return true;} if(timer){clearTimeout(timer);} var anim=options.animation;var doScroll=function(){var off=element.cumulativeOffset();var sOff=element.cumulativeScrollOffset();var toff=options.offsetTop;var loff=options.offsetLeft;if(sOff.top=off.top-toff){if(sOff.top>0){anim.top=sOff.top+toff+'px';}}else{if(off.top!=options.topLimit){if(sOff.top+toff>options.topLimit){anim.top=sOff.top+toff+'px';}else{anim.top=options.topLimit+'px';}}}} if(options.horizontal){if(sOff.left>=off.left-loff){if(sOff.left>0){anim.left=sOff.left+loff+'px';}}else{if(off.left!=options.leftLimit){if(sOff.left+loff>options.leftLimit){anim.left=sOff.left+loff+'px';}else{anim.left=options.leftLimit+'px';}}}} if(options.onBeforeScroll(element,parseInt(anim.top,10)||0,parseInt(anim.left,10)||0)!==false){if(options.smooth){anim.onEnd=function(){options.onScroll(element,anim.top,anim.left);};element.shift(anim);}else{element.style.left=anim.left;element.style.top=anim.top;options.onScroll(element,anim.top,anim.left);}}};if(options.smooth===false){doScroll();}else{timer=setTimeout(doScroll,options.delay);} return element;};element.pin=function(){options.onPinned(element);element.pinned=true;};element.isPinned=function(){return element.pinned;};element.unpin=function(){element.pinned=false;onScroll();options.onUnpinned(element);};element.update=onScroll;element.updateLimits=function(top,left){options.topLimit=top||parseInt(element.getStyle('top')||0,10);options.leftLimit=left||parseInt(element.getStyle('left')||0,10);return element;};Event.observe(window,'scroll',onScroll);return element;},bigSelect:function(element,options){element=$(element);if(!Prototype.Browser.IE9&&!Prototype.Browser.IE10&&Prototype.Browser.IE){return element;} options=Object.extend({classpreFix:'big-select',additionalClassName:'',onSelect:function(x){return x;},onComplete:function(x){return x;}},options||{});if(element.selectConverted){element.selectConverted.remove();} var cont=new Element('div',{className:options.classpreFix+' '+options.additionalClassName,tabIndex:'1'}).setStyle({outline:'none',fontSize:element.getStyle('font-size')});var content=new Element('div',{className:options.classpreFix+'-content'});var list=new Element('div',{className:options.classpreFix+'-list'}).setStyle('z-index:2000000').hide();var arrow=new Element('div',{className:options.classpreFix+'-arrow'});var span=new Element('div',{className:options.classpreFix+'-content-span'});element.selectConverted=cont;cont.setUnselectable();if(options.width){cont.setStyle({width:options.width});} if(options.textfield){var textfield;cont.insert(textfield=new Element("input",{type:"text","class":"big-textfield"}).setStyle({width:'168px'}));arrow.setStyle({position:"absolute",top:"1px",right:"0px"});cont.setStyle({border:"none",boxShadow:"none",background:"transparent"});}else{content.update(span);cont.insert(content);} cont.insert(list).insert(arrow);element.insert({before:cont}).hide();element.observe('change',function(){if(options.textfield){textfield.value="{"+element.getSelected().value+"}";}else{span.update(options.onSelect(element.getSelected().text));}});var closeList=function(){cont.removeClassName(options.classpreFix+'-open');list.hide();};$A(element.options).each(function(opt){if(opt.selected){span.update(options.onSelect(opt.text));} var li=document.createElement('li');li.setAttribute("value",opt.value.strip(opt.value.stripTags()));li.innerHTML=opt.text.escapeHTML();if(opt.hasClassName("bold")){li.setStyle('color:#555; font-weight:bold;');} li.hover(function(){li.setStyle('background:#ccc');},function(){li.setStyle({background:''});});li.observe('click',function(){span.update(options.onSelect(li.innerHTML,li.readAttribute('value')));element.selectOption(li.readAttribute('value'));closeList();});list.appendChild(li);});cont.observe('blur',function(){closeList();});list.show();var currentTop=list.getStyle('top');list.hide();var toggleList=function(){if(list.visible()){closeList();}else{list.show();cont.addClassName(options.classpreFix+'-open');list.setStyle({height:'',top:currentTop,overflow:'',bottom:''});var vh=document.viewport.getHeight();var lt=list.getBoundingClientRect().top;var lh=list.getHeight();if(vhlt){h=(lt-10)+'px';} list.setStyle({bottom:content.getHeight()+'px',top:'auto',height:h,overflow:'auto'});}else{list.setStyle({height:(vh-lt-20)+'px',overflow:'auto'});}}}};arrow.observe('click',toggleList);content.observe('click',toggleList);options.onComplete(cont,element);return element;},rotatingText:function(element,text,options){element=$(element);options=Object.extend({delimiter:' - ',duration:150},options||{});var orgText=element.innerHTML.strip();text+=options.delimiter;var orgLength=orgText.length;var initialText=text.substr(0,orgLength);element.innerHTML=initialText;var current=0;var interval=setInterval(function(){if(current==text.length){current=0;element.innerHTML=text.substr(current++,orgLength);} else if(current+orgLength>text.length){var toInsert=text.substr(current,orgLength);toInsert+=text.substr(0,orgLength-(text.length-current));element.innerHTML=toInsert;current++;} else{element.innerHTML=text.substr(current++,orgLength);}},options.duration);element.rotatingStop=function(){clearTimeout(interval);element.innerHTML=orgText;};return element;}};Element.addMethods(Protoplus.ui);;var JotForm={url:"//www.jotform.com/",server:"//www.jotform.com/server.php",APIUrl:"//www.jotform.com/API",conditions:{},calculations:[],condValues:{},couponApplied:false,progressBar:false,forms:[],saveForm:false,imageFiles:["png","jpg","jpeg","ico","tiff","bmp","gif","apng","jp2","jfif"],autoCompletes:{},defaultValues:{},debug:false,highlightInputs:true,noJump:false,initializing:true,lastFocus:false,payment:false,fieldsToPreserve:[],saving:false,loadingPendingSubmission:false,sessionID:null,submissionToken:null,draftID:null,submissionID:null,texts:{},paymentTexts:{couponApply:'Apply',couponChange:'Change',couponEnter:'Enter Coupon',couponExpired:'Coupon is expired. Please try another one.',couponInvalid:'Coupon is invalid. Please try another one.',couponRatelimiter:'You have reached the rate limit. Please try again after one minute.',couponValid:'Coupon is valid.',couponBlank:'Please enter a coupon.',shippingShipping:'Shipping',totalTotal:'Total',totalSubtotal:'Subtotal',taxTax:'Tax',},validationRegexes:{email:/^(?:[\a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[\a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+)*|"(?:[\s\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9]){1,}|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-zA-Z0-9-]*[a-zA-Z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/,alphanumeric:/^[\u00C0-\u1FFF\u2C00-\uD7FFa-zA-Z0-9\s]+$/,numeric:/^(-?\d+[\.\,]?)+$/,numericDotStart:/^([\.]\d+)+$/,currency:/^-?[\$\£\€\₺]?\d*,?\d*,?\d*(\.\d\d)?¥?$/,alphabetic:/^[\u00C0-\u1FFF\u2C00-\uD7FFa-zA-Z\s]+$/,cyrillic:/^[абвгдеёжзийклмнопрстуфхцчшщьыъэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЫЪЭЮЯ\s]*$/,},freeEmailAddresses:['gmail.','aim.com','outlook.','hotmail.','yahoo.','inbox.','gmx.','yandex.','tutanota.','ymail.','mailfence.','hushmail.','protonmail.','rediffmail.','msn.','live.','aol.','currently.','att.','mailinator.','getnada.','abyssmail.','boximail.','clrmail.','dropjar.','getairmail.','givmail.','inboxbear.','tafmail.','vomoto.','zetmail.','sharklasers.','guerrillamail.','grr.','guerrillamailblock.','pokemail.','spam4.','emailcu.','mybx.','fsmilitary.','yopmail.','cool.','jetable.','nospam.','nomail.','monmail.','monemail.','moncourrier.','courriel.','speed.','mega.','icloud.','googlemail.','qq.','mac.','email.com','comcast.net','mail.com','usa.com','myself.com','consultant.com','post.com','europe.com','asia.com','iname.com','writeme.com','dr.com','engineer.com','cheerful.com','mail.vu','mail.ru','mail.pt','mail.pf','mail.org.uk','mail.nu','mail.md','mail.gr','mail.az','mail.be','mail.bg','mail.bulgaria.com','mail.by','mail.byte.it','mail.co.za','mail.com','mail.com.tr','mail.ee',],paymentFields:['control_2co','control_authnet','control_bluepay','control_bluesnap','control_boxpayment','control_braintree','control_cardconnect','control_chargify','control_clickbank','control_dwolla','control_echeck','control_eway','control_firstdata','control_paypalInvoicing','control_gocardless','control_googleco','control_moneris','control_mollie','control_onebip','control_pagseguro','control_payjunction','control_payment','control_paysafe','control_iyzico','control_paypal','control_paypalexpress','control_paypalpro','control_paypalcomplete','control_payu','control_sofort','control_skrill','control_square','control_stripe','control_stripeACH','control_stripeACHManual','control_worldpay','control_sensepass','control_paypalSPB','control_cybersource','control_stripeCheckout','control_payfast'],tempStripeCEForms:['230024636370952','230894369312966','33361556326858','230841251513446','62366391795266','220392206656353','230923831008349','73394165522963','83003904243346','90764025629360','90831342951355','90852034658360','92226427822356','92581787545371','92762018229358','92872381567368','93091396563364','200432081549348','200524754914353','200672628663358','200714281980352','201545466622353','202666382145355','203216090201336','203594925705361','210313694786360','210373149515351','210596520458357','210705631271345','210736300449349','210804961245352','211401327963349','211424822700343','211571514935354','213042959945363','213126472737355','220167135758357','220301706806345','220724495641356','220885098968375','222471409754357','222777403556360','223413865360353','223605826686364','230012143712336','230092900090344','230274621472350','230494425755360','230923288296364','230923831008349','230952526252050'],isEncrypted:false,tempUploadFolderInjected:false,disableSubmitButton:false,disableSubmitButtonMessage:'',isConditionDebugMode:false,encryptAll:function(e,callback){e.stop();var fields=getFieldsToEncrypt();if(JotForm.encryptionProtocol==='JF-CSE-V2'){if(JotForm.isEditMode()){var form=document.querySelector('.jotform-form');var formID=form?form.getAttribute('id'):'';var privateKey=JotCrypto.getEncryptionKey('JF-CSE-V2',formID);var encryptionKey=JotForm.submissionDecryptionKey;if(!privateKey){callback(false);JotForm.error('Missing encryption key!');return;} Promise.all(fields.map(function(field){setUnencryptedValueToForm(field);return JotCrypto.reEncrypt(privateKey,encryptionKey)(field.value).then(function(encVal){return Promise.resolve({field:field,encryptedValue:encVal});});})).then(function(encFields){encFields.map(setEncryptedValue);var submitFormAfterEncrypt=shouldSubmitFormAfterEncrypt();callback(submitFormAfterEncrypt);}).catch(function(err){console.log('Encryption v2 error ',err.message);})}else{JotCrypto.encrypt(JotForm.encryptionPublicKey).then(function(enc){addEncryptionKeyToForm(enc.encryptedAESKey);return Promise.all(fields.map(function(field){setUnencryptedValueToForm(field);return enc.run(field.value).then(function(encVal){return Promise.resolve({field:field,encryptedValue:encVal});});}));}).then(function(encFields){encFields.map(setEncryptedValue);var submitFormAfterEncrypt=shouldSubmitFormAfterEncrypt();callback(submitFormAfterEncrypt);}).catch(function(err){console.log('Encryption v2 error ',err.message);})};}else{fields.forEach(function(field){setUnencryptedValueToForm(field);var encryptedField={field:field,encryptedValue:JotEncrypted.encrypt(field.value)};setEncryptedValue(encryptedField);});var submitFormAfterEncrypt=shouldSubmitFormAfterEncrypt();callback(submitFormAfterEncrypt);}},getServerURL:function(){const form=document.querySelector('.jotform-form');let action;const origin=window.location.origin||(window.location.protocol+'//'+window.location.hostname);if(form){if(origin.includes('.jotform.pro')){this.server=origin+"/server.php";this.url=origin+'/';return;} if((action=form.readAttribute('action'))){if(action.includes('submit.php')||action.includes('server.php')){const n=!action.includes('server.php')?"submit":"server";this.server=action.replace(n+'.php','server.php');this.url=action.replace(n+'.php','');}else{let d=action.replace(/\/submit\/.*?$/,'/');if(action.includes('pci.jotform.com')){d=d.replace('pci.','submit.');} if(typeof JotForm.enterprise!=='undefined'&&JotForm.enterprise){d="https://"+JotForm.enterprise+"/";}else if(typeof JotForm.hipaa!=='undefined'&&JotForm.hipaa){d="https://hipaa.jotform.com/";} this.server=d+'server.php';this.url=d;}}}},checkConditionDebugMode:function(){if(window&&window.location.href.indexOf('conditionDebug')!==-1){this.isConditionDebugMode=true;}},initSentry:function(){const origin=window.location.origin?window.location.origin:window.location.protocol+"//"+window.location.hostname+(window.location.port?':'+window.location.port:'');const isHIPAAEnterprise=typeof JotForm.enterprise!=='undefined'&&JotForm.enterprise&&typeof JotForm.hipaa!=='undefined'&&JotForm.hipaa;if(!window.Sentry&&window.FORM_MODE!=='cardform'&&!origin.includes('jotform.pro')&&!isHIPAAEnterprise){const script=document.createElement('script');script.src='https://browser.sentry-cdn.com/5.19.0/bundle.min.js';script.integrity='sha384-edPCPWtQrj57nipnV3wt78Frrb12XdZsyMbmpIKZ9zZRi4uAxNWiC6S8xtGCqwDG';script.crossOrigin='anonymous';script.addEventListener('load',function(){if(window.Sentry){window.Sentry.init({dsn:'https://fc3f70667fb1400caf8c27ed635bd4e1@sentry.io/4142374',enviroment:'production',whitelistUrls:[/https?:\/\/.*jotform\.com/,/https?:\/\/cdn\.jotfor\.ms/],integrations:[new Sentry.Integrations.GlobalHandlers({onunhandledrejection:false})],denyUrls:[/graph\.facebook\.com/i,/connect\.facebook\.net\/en_US\/all\.js/i,/eatdifferent\.com\.woopra-ns\.com/i,/static\.woopra\.com\/js\/woopra\.js/i,/extensions\//i,/^chrome:\/\//i,/127\.0\.0\.1:4001\/isrunning/i,/webappstoolbarba\.texthelp\.com\//i,/metrics\.itunes\.apple\.com\.edgesuite\.net\//i,/tinymce/i],ignoreErrors:['top.GLOBALS','originalCreateNotification','canvas.contentDocument','MyApp_RemoveAllHighlights','http://tt.epicplay.com','Can\'t find variable: ZiteReader','jigsaw is not defined','ComboSearch is not defined','http://loading.retry.widdit.com/','atomicFindClose','fb_xd_fragment','bmi_SafeAddOnload','EBCallBackMessageReceived','conduitPage','tinymce','GetScreenshotBoundingBox','Can\'t execute code from a freed script','for=','JotForm.handleIFrameHeight','ResizeObserver loop limit exceeded','SB_ModifyLinkTargets','RegisterEvent'],beforeSend:function(event){if(window.parent===window&&event.request&&event.request.url&&!event.request.url.match(/(https?:\/\/.*jotform\.com)|(https?:\/\/cdn\.jotfor\.ms)/)){return null;} if(window.navigator.userAgent.indexOf('FB_IAB')!==-1){return null;} return event;}});}});document.querySelector('head').appendChild(script);}},getAPIEndpoint:function(){if(!this.APIUrl){this.setAPIUrl();} return this.APIUrl;},alterTexts:function(newTexts,payment){if(payment&&!!newTexts){Object.extend(this.paymentTexts,newTexts);this.changePaymentStrings(newTexts);}else{Object.extend(this.texts,newTexts||{});}},ie:function(){var undef,v=3,div=document.createElement('div'),all=div.getElementsByTagName('i');while(div.innerHTML='',all[0]);return v>4?v:undef;},errorCatcherLog:function(err,logTitle){try{if(!location.href.includes('form-templates')){var currFormID=document.getElementsByName('formID')[0].value;var errorData={stack:err.stack||err.message,agent:navigator.userAgent,referrer:location.href} if(logTitle==='VALIDATED_REQUIRED_FIELD_IDS'){errorData={validatedRequiredFieldIDs:err.validatedRequiredFieldIDs,agent:navigator.userAgent,referrer:location.href} if(JotForm.isEditMode()){errorData['submissionID']=document.querySelector('input[name="editSubmission"]').value;}else{errorData['eventID']=document.querySelector('input[name="event_id"]').value;}} var _payload=JSON.stringify({data:errorData,title:logTitle});JotForm.createXHRRequest(JotForm.getAPIEndpoint()+'/formInitCatchLogger/'+currFormID,'post',_payload,function cb(res){console.log(res)},function errCb(err){console.log(err)});}}catch(_err){console.log(_err);}},createConsole:function(){var consoleFunc=['log','info','warn','error'];consoleFunc.forEach(function(c){this[c]=function(){if(JotForm.debug){if('console'in window){try{console[c].apply(this,arguments);}catch(e){if(typeof arguments[0]=="string"){console.log(c.toUpperCase()+": "+arguments.join(', '));}else{if(JotForm.browserIs.ie8AndBelow()){alert(c+": "+arguments[0]);}else{console[c](arguments[0]);}}}}}};}.bind(this));if(JotForm.debug){JotForm.debugOptions=document.readJsonCookie('debug_options');}},generatePaymentTransactionId:function(){var paymentTransactionIdInput=document.getElementById('paymentTransactionId');if(typeof(paymentTransactionIdInput)!='undefined'&&paymentTransactionIdInput!=null){var msTransaction=Date.now();JotForm._xdr(JotForm.getAPIEndpoint()+'/payment/generateTransactionId?ms='+msTransaction,'GET',null,function(responseData){if(responseData.content){paymentTransactionIdInput.value=responseData.content;}},function(err){console.log('err',err);});}},init:function(callback){var firstPerformancePoint=performance.now();var ready=function(){try{if(!this.jsForm&&getQuerystring('jsForm')==='true'){this.jsForm=true;if(window.CardForm){window.CardForm.jsForm=true;}} trackExecution('init-started');if(typeof window.initializeSignaturePad==='function'){window.initializeSignaturePad();} var jotformForm=document.querySelector('.jotform-form');var isPreview=getQuerystring('preview')==='true';var _formID=jotformForm.id;var _uuid=generateUUID(_formID);if(!isPreview){if(location&&location.href&&location.href.indexOf('&nofs')===-1&&location.href.indexOf('&sid')===-1){appendHiddenInput('event_id',_uuid);}} HTMLFormElement.prototype.submit=(function(originalSubmitFn){return function(){try{var directValidationFeatureFlag=!JotForm.payment;if(directValidationFeatureFlag&&!JotForm.ignoreDirectValidation){if(JotForm.validateAll(this)){trackExecution('direct-validation-passed');}else{JotForm.enableButtons();JotForm.showButtonMessage();JotForm.updateErrorNavigation(true);trackExecution('direct-validation-failed');return false;}} trackSubmitSource('direct');}catch(error){console.log(error);} JotForm.ignoreDirectValidation=false;return originalSubmitFn.apply(this,arguments);};})(HTMLFormElement.prototype.submit);if(jotformForm.reset&&jotformForm.autocomplete&&jotformForm.autocomplete==='off'){if(window.navigator.userAgent.indexOf('MSIE ')!==-1||window.navigator.userAgent.indexOf('Trident/')!==-1){jotformForm.reset();}} window.onpageshow=function(e){if(e.persisted){JotForm.fromBFCache=true;if(JotForm.browserIs.ios()){window.location.reload();} else if(JotForm.browserIs.safari()){document.querySelectorAll('.qq-upload-success').forEach(function(fileElement){var fileElementParent=fileElement.parentElement;JotForm.removeFile({fileElement:fileElement,fileName:fileElement.getAttribute('actual-filename'),hiddenTempUploadInput:document.querySelector('[name^="temp_upload["]')});if(fileElementParent){fileElementParent.dispatchEvent(new Event('change',{bubbles:true}));}});}}};this.populateGet();this.debug=document.get.debug==='1';this.createConsole();this.getServerURL();this.checkConditionDebugMode();this.checkJSON();if(callback){try{callback();}catch(error){console.log(error);}} Array.from(document.forms).forEach(function(form){if(form.name==='form_'+form.id||form.name==='q_form_'+form.id){JotForm.forms.push(form);}});if(isIframeEmbedFormPure()){window.addEventListener('load',function(){JotForm.handleIFrameHeight();});if(typeof JotForm.importedPDF!=='undefined'&&typeof MutationObserver!=='undefined'&&typeof ResizeObserver!=='undefined'&&JotForm.importedPDF){const iframeObserver=new MutationObserver(()=>JotForm.handleIFrameHeight());iframeObserver.observe(document.documentElement,{attributes:true,attributeFilter:['data-mode']});const welcomeViewObserver=new MutationObserver(()=>{const welcomeView=document.querySelector('#pdfimporter-root .pdff-welcomeView');if(!welcomeView){return;} const resizeObserver=new ResizeObserver(()=>JotForm.handleIFrameHeight());resizeObserver.observe(welcomeView);welcomeViewObserver.disconnect();});welcomeViewObserver.observe(document.documentElement,{childList:true,subtree:true});}} if(window.location.pathname.indexOf("/edit/")!==-1){var urlParts=window.location.href.split("/");document.get.sid=urlParts[urlParts.indexOf('edit')+1];this.editMode();} if(document.get.sid&&(['edit','inlineEdit','submissionToPDF'].indexOf(document.get.mode)>-1||document.get.offline_forms==='true')){this.editMode();} if(window.JFForm&&window.JFForm.draftID){this.draftID=window.JFForm.draftID;} this.noJump=("nojump"in document.get);this.uniqueID=this.uniqid();this.sessionID=JotForm.validateSessionID(document.get.session);this.submissionToken=document.get.stoken||false;this.submissionID=document.get.sid||false;this.handleSavedForm();this.setHTMLClass();this.getDefaults();if(this.noJump){window.parent.postMessage("removeIframeOnloadAttr",'*');} var inputSimpleFpc=document.querySelector('input[name="simple_fpc"]');if(inputSimpleFpc){this.payment=inputSimpleFpc.getAttribute('data-payment_type');} if(!!document.querySelector('.form-product-custom_price')){this.handleSubscriptionPrice();} if(!!document.querySelector('#payment-category-dropdown')){this.handleProductCategoryDropdown();} if(this.payment==="paypalpro"){this.handlePaypalPro();} if(this.payment==="cybersource"){this.handleCybersource();} if(this.payment==="braintree"){this.handleBraintree();} if(this.payment==="pagseguro"){this.handlePagseguro();} if(this.payment==="square"){this.handleSquare();} if(this.payment==="mollie"){this.handleMollie();} if(this.payment==="sensepass"){this.handleSensepass();} if(this.payment==="stripeACH"){this.handleStripeACH();} if(this.payment==="authnet"){this.handleAuthNet();} if(this.payment==="bluepay"){this.handleBluepay();} if(this.payment==="bluesnap"){this.handleBluesnap();} if(['cardconnect','paysafe','chargify','firstdata','payjunction'].indexOf(this.payment)>-1){this.PCIGatewaysCardInputValidate();} if(this.payment==="paypalexpress"){this.handlePaypalExpress();} if(this.payment==='echeck'){this.handleEcheck();} if(this.payment==="paypalSPB"){if(typeof JotForm.browserInformations==='function'){appendHiddenInput('browserDetails',JotForm.browserInformations());} var interval=setInterval(function(){if(typeof __paypalSPB!=="undefined"&&typeof paypal!=="undefined"){clearInterval(interval);this.handlePaypalSPB();}}.bind(this),100);} if(document.getElementById('coupon-button')){this.handleCoupon();} if(typeof PaymentStock!=='undefined'){setTimeout(function(){PaymentStock.initialize();},0);} if(document.querySelector('.paypal-button')&&document.getElementById('use_paypal_button')){this.handlePaypalButtons();} this.handleFormCollapse();this.handlePages();this.checkEmbed();this.checkPwa();if(document.querySelector('.form-product-has-subproducts')){if(JotForm.newPaymentUI){this.handlePaymentSubProductsV1();}else{this.handlePaymentSubProducts();}} if(window.parent&&window.parent!==window){var queryString=document.referrer&&document.referrer.split('?')[1]||'';if(queryString.indexOf('disableSmartEmbed')>-1||!this.jsForm){document.querySelectorAll('.isSmartEmbed').forEach(el=>el.classList.remove('isSmartEmbed'));} this.setIFrameDeviceType();this.handleIFrameHeight();if(this.isMobileTouchlessModeTestEnv()){this.mobileTouchlessModeTest();} var visibleCaptcha=document.querySelector('li[data-type="control_captcha"]:not(.always-hidden)');if(visibleCaptcha){var count=0;var captchaInterval=setInterval(function(){if(count>5){clearInterval(captchaInterval);} if(visibleCaptcha.querySelectorAll('iframe').length){JotForm.handleIFrameHeight();clearInterval(captchaInterval);} count++;},1000);}}else{document.querySelectorAll('.isSmartEmbed').forEach(el=>el.classList.remove('isSmartEmbed'));} Element.prototype.triggerEvent=function(eventName){var disabled=this.hasClassName('form-dropdown')&&this.disabled?!!(this.enable()):false;if(document.createEvent){var evt=document.createEvent('HTMLEvents');evt.initEvent(eventName,true,true);this.dispatchEvent(evt);}else if(this.fireEvent){this.fireEvent('on'+eventName);} if(disabled){this.disable();}} this.jumpToPage();if(!JotForm.getPrefillToken()){this.highLightLines();}else{document.addEventListener('PrefillCompleted',this.highLightLines);} this.handleWidgetMessage();this.setButtonActions();this.initGradingInputs();this.initSpinnerInputs();this.initNumberInputs();this.handleZeroQuantityProducts();this.initTextboxValidation();this.setAPIUrl();this.initPrefills();this.createManualPrefill();if(document.querySelector('.js-new-sacl-button, .jfFormUser-header-saveAndContinueLater-button')&&!window.JotForm.isNewSACL){JotForm.isNewSACL=true;} if(this.payment==="paypalcomplete"){this.handlePaypalComplete();} if(getQuerystring('jotform_pwa')==='1'){this.setJotFormUserInfo();} if(getQuerystring('asanaTaskID',false)){this.setAsanaTaskID();} this.setConditionEvents();this.setCalculationEvents();this.runAllCalculations();this.setCalculationResultReadOnly();this.prePopulations();JotForm.onTranslationsFetch(function(){if(document.createEvent){try{var event=new CustomEvent('PrepopulationCompleted');document.dispatchEvent(event);}catch(error){console.log(error);}}});this.handleSSOPrefill();this.handleAutoCompletes();this.handleTextareaLimits();this.handleDateTimeChecks();this.handleTimeChecks();this.handleOtherOptions();this.setFocusEvents();this.disableAcceptonChrome();this.handleScreenshot();this.handleSignatureEvents();this.handleSignSignatureInputs();this.handleFITBInputs();if(JotForm.newDefaultTheme||JotForm.extendsNewTheme){this.initTestEnvForNewDefaultTheme();this.initTimev2Inputs();this.initDateV2Inputs();this.getMessageFormTermsAndCondition();this.initOtherV2Options();this.dropDownColorChange();} this.validator();this.fixIESubmitURL();this.disableHTML5FormValidation();this.adjustWorkflowFeatures();this.generatePaymentTransactionId();calculateTimeToSubmit();if(document.getElementById('progressBar')){this.setupProgressBar();} if(document.querySelector('input[id*="_donation"]')){this.handleDonationAmount();} if(getQuerystring('nosubmit')){document.querySelectorAll('.form-submit-button').forEach(function(b){b.disabled=true;b.classList.add('conditionallyDisabled');});} if(getQuerystring('displayAllSections')){document.querySelectorAll('.form-section').forEach(function(section){section.style.display='block';});} if(isPreview){this.handlePreview(getQuerystring('filled')==='true');}else if(this.initializing){this.track(_uuid);} this.additionalActionsFormEmbedded();var constructSubmitBanner=function(){var button=Array.from(document.querySelectorAll('.form-submit-button')).find(function(el){return!(el.classList.contains('form-sacl-button')||el.classList.contains('js-new-sacl-button'))});var brandingText=(JotForm.newDefaultTheme&&JotForm.poweredByText)?JotForm.poweredByText.replace(/Jotform/,'Jotform'):JotForm.poweredByText;if(window&&window.location.href.indexOf('branding21')!==-1){brandingText=brandingText.replace('JotForm','Jotform');} if(button){var buttonWrapper=button.parentNode;var banner=document.createElement('a');banner.target='_blank';banner.href='https://www.jotform.com/?utm_source=powered_by_jotform&utm_medium=banner&utm_term='+_formID+'&utm_content=powered_by_jotform_text&utm_campaign=powered_by_jotform_signup_hp';banner.setText(brandingText);banner.style.display='inline-block';var fontColor='#000000';var fontFamily='';var sampleLabel=document.querySelector('.form-label');if(sampleLabel!==null){var computedStyles=getComputedStyle(sampleLabel);fontColor=computedStyles.color;fontFamily=computedStyles.fontFamily;} banner.style.opacity=0.8;banner.style.webkitFontSmoothing='antialiased';banner.style.color=fontColor;banner.style.fontFamily=fontFamily;banner.style.fontSize=JotForm.newDefaultTheme?'12px':'11px';banner.className='jf-branding';banner.style.paddingTop='10px';if(JotForm.newDefaultTheme){var submitWrapper=document.createElement('div');submitWrapper.className='submitBrandingWrapper';submitWrapper.style.flexDirection='column';submitWrapper.appendChild(button);submitWrapper.appendChild(banner);buttonWrapper.appendChild(submitWrapper);}else{var buttonsParent=buttonWrapper.parentNode buttonsParent.appendChild(banner);buttonsParent.style.display='flex';buttonsParent.style.flexDirection='column';banner.style.textAlign='center';banner.style.paddingBottom='10px';} if(getComputedStyle(buttonWrapper).textAlign!=='center'){var linkDimensions=banner.getBoundingClientRect();var buttonDimensions=button.getBoundingClientRect();var mr=Math.abs((linkDimensions.width-buttonDimensions.width)/2);if(linkDimensions.width>buttonDimensions.width){banner.style.marginLeft='-'+mr+'px';}else{banner.style.marginLeft=mr+'px';}}}} var createBadgeWrapperEl=function(){var div=document.createElement('div');div.setAttribute('class','badge-wrapper');return div;} var appendBadgeWrapperIntoForm=function(){var selectParentPosition=document.querySelector('.form-all') var badgeWrapper=selectParentPosition.querySelector('.badge-wrapper');if(badgeWrapper)return badgeWrapper;var el=createBadgeWrapperEl();selectParentPosition.appendChild(el);return el;} var appendBadgeIntoForm=function(banner){var badgeWrapper=appendBadgeWrapperIntoForm();badgeWrapper.appendChild(banner);banner.addEventListener('load',JotForm.handleIFrameHeight);} var displayBadge=function(badgeUrl,badgeClass,badgeAlt,badgeLink,utmParameter,urlParameter){var formID=document.querySelector('input[name="formID"]').value;var banner=document.createElement('img');banner.className=badgeClass;banner.src=badgeUrl;banner.alt=badgeAlt;banner.style.display='block';banner.style.width='95px';var badgeWrapper=document.createElement('a');badgeWrapper.setAttribute('class','badge-wrapper-button '+badgeClass+'-wrapper');if(!JotForm.enterprise){badgeWrapper.setAttribute('href',badgeLink+'/?utm_source=formfooter&utm_medium=banner&utm_term='+formID+'&utm_content='+utmParameter+'&utm_campaign=form_badges'+urlParameter);badgeWrapper.setAttribute('target','_blank');} badgeWrapper.appendChild(banner);appendBadgeIntoForm(badgeWrapper);} if(JotForm.showHIPAABadge){displayBadge('https://cdn.jotfor.ms/assets/img/uncategorized/hipaa-badge-compliance.png','hipaa-badge','HIPAA Compliance Form','https://www.jotform.com/hipaa','hipaa_compliant','');}else if(JotForm.showJotFormPowered==="old_footer"&&window.JotForm.useJotformSign!=='Yes'){constructSubmitBanner();} if(JotForm.isEncrypted&&window.FORM_MODE!=='cardform'){displayBadge('https://cdn.jotfor.ms/assets/img/uncategorized/encrypted-form-badge.png','encrypted-form-badge','Encrypted Form','https://www.jotform.com/encrypted-forms','encrypted_form','');} if(JotForm.showA11yBadge){var formID=document.querySelector('input[name="formID"]').value;var banner=document.createElement('img');banner.className='accessibility-badge';banner.src='https://cdn.jotfor.ms/assets/img/uncategorized/access-image.png';banner.alt='accessibility badge';banner.style.display='block';banner.style.width='54px';var A11yWrapper=document.createElement('a');A11yWrapper.setAttribute('class','badge-wrapper-button accessibility-badge-wrapper');if(!JotForm.enterprise){A11yWrapper.setAttribute('href','https://www.jotform.com/accessible-forms/?utm_source=formfooter&utm_medium=banner&utm_term='+formID+'&utm_content=accessibility_enabled_form&utm_campaign=form_badges');A11yWrapper.setAttribute('target','_blank');} var A11yContent=document.createElement('div');A11yContent.setAttribute('class','a11y-content');var A11yTitle=document.createElement('div');A11yTitle.setAttribute('class','a11y-title');A11yTitle.textContent='ACCESSIBILITY';var A11ySubTitle=document.createElement('div');A11ySubTitle.setAttribute('class','a11y-subtitle');A11ySubTitle.textContent='ENABLED FORM';A11yContent.appendChild(A11yTitle);A11yContent.appendChild(A11ySubTitle);A11yWrapper.appendChild(banner);A11yWrapper.appendChild(A11yContent);appendBadgeIntoForm(A11yWrapper);} if(typeof JotForm.enterprise!=="undefined"&&JotForm.enterprise){appendHiddenInput('enterprise_server',JotForm.enterprise,{id:'enterprise_server'});} if(JotForm.hipaa){appendHiddenInput('file_server','hipaa-app1',{id:'file_server'});appendHiddenInput('target_env','hipaa',{id:'target_env'});} if(jotformForm){var mobileSubmitBlock=false;if(/Android|iPhone|iPad|iPod|Opera Mini/i.test(navigator.userAgent)){var selectorInputs='form input:not([type="hidden"], [name="website"], [data-age]), form textarea:not([type="hidden"])';var getFields=document.querySelectorAll(selectorInputs);Array.from(getFields).forEach(function(item,index){item.addEventListener('keypress',function(keyEvent){var nextItem=getFields[index+1];if(keyEvent.keyCode===13&&nextItem&&keyEvent.target.type!=='textarea'){keyEvent.preventDefault();mobileSubmitBlock=true;nextItem.focus();}else{mobileSubmitBlock=false;}})});} var convertEmailToASCII=function(e){if(typeof punycode!=="undefined"){document.querySelectorAll('input[type="email"]').forEach(function(field){field.value=punycode.toASCII(field.value);});} if(mobileSubmitBlock&&!e.isTrusted){e.preventDefault();}} jotformForm.addEventListener('submit',convertEmailToASCII);} this.handleWidgetStyles();window.addEventListener('load',function(){JotForm.makeReadyWidgets();if(history.state!==null&&typeof history.state.submitted!=='undefined'&&history.state.submitted){history.replaceState({submitted:false},null,null);var productIndex=null;if(typeof window.CardForm!=='undefined'){CardForm.cards.forEach(function(item,index){if(item.type==='products'){productIndex=index;}});if(productIndex!==null){CardForm.setFormMode('form');CardForm.setCardIndex(productIndex);}}}});}catch(err){trackExecution('init-error');JotForm.error(err);if(!JotForm.validatorExecuted){try{this.errorCatcherLog(err,'FORM_VALIDATION_NOT_ATTACHED');this.validator();this.disableHTML5FormValidation();}catch(err){this.errorCatcherLog(err,'FORM_VALIDATOR_ERROR');}}else{this.errorCatcherLog(err,'FORM_INIT_ERROR');}} this.initializing=false;var event=new CustomEvent('JotformReady');document.dispatchEvent(event);if(window.self!==window.top&&JotForm.isPaymentSelected()&&window.paymentType){JotForm.countTotal(JotForm.prices);} trackExecution('init-complete');}.bind(this);var sourceCodeCompatibilityFixers=function(){var fetchFormTexts=function(){return new Promise((resolve,reject)=>{if(!window.JotForm.texts||Object.keys(window.JotForm.texts).length===0){JotForm.setAPIUrl();JotForm.createXHRRequest(JotForm.getAPIEndpoint()+'/form/staticTexts','GET',null,function cb(res){window.JotForm.texts=(res&&res.content&&typeof res.content==='object')?res.content:{} resolve('Successfully fetched form texts');},function errCb(err){console.log(err) reject('Form texts could not be fetched');})}else{resolve('Form texts already in window');}});} fetchFormTexts().then(ready).catch((err)=>{console.error('An error occurred in source code compatibility fixers:',err);ready();});} if(document.readyState==='complete'||(this.jsForm&&(document.readyState===undefined||document.readyState==='interactive'))){sourceCodeCompatibilityFixers();}else{document.ready(sourceCodeCompatibilityFixers);} const{getLoops,getCalculationMap}=this.conditionDebugger();this.loopMap=getLoops();this.calculationMap=getCalculationMap();this.loopMapExist=this.loopMap&&this.loopMap.size;if(typeof __conditionDebugger_logPerformance==='function'){__conditionDebugger_logPerformance([{title:'Form Initialization',value:(performance.now()-firstPerformancePoint).toFixed(2)}]);}else if(!window.__pushInitDataInterval){window.__pushInitDataTries=0;window.__pushInitDataInterval=setInterval(function(){if(typeof __conditionDebugger_logPerformance==='function'){__conditionDebugger_logPerformance([{title:'Form Initialization',value:(performance.now()-firstPerformancePoint).toFixed(2)}]);clearInterval(__pushInitDataInterval);} if(__pushInitDataTries>30){clearInterval(__pushInitDataInterval);} __pushInitDataTries++;},50);}},browserIs:{userAgent:'navigator'in window&&'userAgent'in navigator&&navigator.userAgent.toLowerCase()||'',vendor:'navigator'in window&&'vendor'in navigator&&navigator.vendor.toLowerCase()||'',appVersion:'navigator'in window&&'appVersion'in navigator&&navigator.appVersion.toLowerCase()||'',chrome:function(){return /chrome|chromium/i.test(this.userAgent)&&/google inc/.test(this.vendor)},firefox:function(){return /firefox/i.test(this.userAgent)},ie:function(){return /msie/i.test(this.userAgent)||"ActiveXObject"in window||/edge\//i.test(this.userAgent)},safari:function(){return /safari/i.test(this.userAgent)&&/apple computer/i.test(this.vendor)},operabrowser:function(){return this.userAgent.indexOf("Opera")>-1},iphone:function(){return /iphone/i.test(this.userAgent)||/iphone/i.test(this.appVersion)},ipad:function(){return /ipad/i.test(this.userAgent)||/ipad/i.test(this.appVersion)},ios:function(){return this.iphone()||this.ipad()},android:function(){return /android/i.test(this.userAgent)},androidPhone:function(){return this.android()&&/mobile/i.test(this.userAgent)},androidTablet:function(){return this.android()&&!this.androidPhone()},blackberry:function(){return /blackberry/i.test(this.userAgent)||/BB10/i.test(this.userAgent)},linux:function(){return /linux/i.test(this.appVersion)},mac:function(){return /mac/i.test(this.appVersion)},windows:function(){return /win/i.test(this.appVersion)},windowsPhone:function(){return this.windows()&&/phone/i.test(this.userAgent)},windowsTablet:function(){return this.windows()&&!this.windowsPhone()&&/touch/i.test(this.userAgent)},mobile:function(){return this.iphone()||this.androidPhone()||this.blackberry()||this.windowsPhone();},tablet:function(){return this.ipad()||this.androidTablet()||this.windowsTablet()},desktop:function(){return!this.mobile()&&!this.tablet()},webkit:function(){return this.userAgent.indexOf('applewebkit')!==-1},ie8AndBelow:function(){return typeof window.addEventListener!=='function'}},hasAccessToLocalStorage:function(){var testItem='test';var testKey='jflocalStorage_test';try{if(!window.localStorage)return false;window.localStorage.setItem(testKey,testItem);if(window.localStorage.getItem(testKey)===testItem){window.localStorage.removeItem(testKey) return true;}} catch(e){console.log('Error: unable to access local storage');return false} return false;},iframeRezizeTimeout:null,iframeHeightCaller:function(){if(window.parent&&window.parent!=window){clearTimeout(this.iframeRezizeTimeout);this.iframeRezizeTimeout=setTimeout((function(){this.handleIFrameHeight();}).bind(this),50);}},setIFrameDeviceType:function(){if(window.FORM_MODE!=='cardform'){return;} window.parent.postMessage('setDeviceType:'+window.CardLayout.layoutParams.deviceType+':','*');},conditionDebugger:function(){let calculationMap=null;let calculationLoops=null;const resolveCalculationMap=()=>{if(!calculationMap){calculationMap=new Map();JotForm.calculations.forEach(calculation=>{const{operands,resultField,baseField}=calculation;const fields=operands?operands.split(','):[baseField].filter(Boolean);if(!fields.length)return;fields.forEach(field=>{if(!calculationMap.has(field))calculationMap.set(field,new Set());calculationMap.get(field).add(resultField);});});}};const resolve=(affectedFields=[],baseField)=>{const isLooped=affectedFields.has(baseField);if(isLooped){calculationLoops.set(baseField,[...calculationLoops.get(baseField),...affectedFields]);return;} affectedFields.forEach(affectedField=>{const relatedAffectedFields=calculationMap.get(affectedField);if(!relatedAffectedFields||relatedAffectedFields.has(affectedField)||calculationLoops.get(baseField).indexOf(affectedField)!==-1)return;calculationLoops.set(baseField,[...calculationLoops.get(baseField),affectedField]);resolve(relatedAffectedFields,baseField);});};const resolveLoops=()=>{if(!calculationLoops)calculationLoops=new Map();calculationMap.forEach((affectedFields,baseField)=>{if(!calculationLoops.has(baseField))calculationLoops.set(baseField,[]);resolve(affectedFields,baseField);});};const getCalculationMap=()=>{return calculationMap;};const getLoops=id=>{if(!calculationMap)resolveCalculationMap();if(!calculationLoops)resolveLoops();calculationLoops.forEach((value,key)=>{if(value.indexOf(key)===-1){calculationLoops.delete(key);}});if(id){return calculationLoops.get(`${id}`);} return calculationLoops;};return{resolveCalculationMap,resolveLoops,getLoops,getCalculationMap};},isMobileTouchlessModeTestEnv:function(){try{return((window.self!==window.top)&&(window.location.href.indexOf("mobileDebugMode")>-1));}catch(e){return false;}},mobileTouchlessModeTest:function(){var touchlessBox='
Contactless Form Scan QR code for fill the form on your device or continue to fill it here.
' var maskWrapper=document.querySelector('.jfForm-background-mask');var welcomeWrapper=document.querySelector('.jfWelcome-wrapper');if(window.FORM_MODE=='cardform'){if(window.CardForm.hasWelcome||document.querySelector('.jfWelcome-wrapper').classList.contains('isHeader')){var welcomePage=document.querySelector('.jfWelcome');var startButton=welcomePage.querySelector('.jfWelcome-buttonWrapper');if(startButton){startButton.insertAdjacentHTML('beforebegin',touchlessBox);}else{welcomePage.insertAdjacentHTML('beforeend',touchlessBox);}}else{var firstCardWrapper=document.querySelector('.form-line:not(.always-hidden) .jfCard-wrapper');var firstCard=firstCardWrapper.querySelector('.jfCard');if(firstCard){firstCardWrapper.classList.add('with-qr') firstCard.insertAdjacentHTML('afterend',touchlessBox);}} window.onload=function(){if(maskWrapper&&welcomeWrapper){maskWrapper.style.width=welcomeWrapper.getBoundingClientRect().width;maskWrapper.style.height=welcomeWrapper.getBoundingClientRect().height;}}}else{var formAll=document.querySelector('.form-all');var firstPage=formAll.querySelector('.form-section');var firstElement=firstPage.querySelector('li');var isFirstElementHead=firstElement.dataset.type==='control_head';if(isFirstElementHead){firstElement.insertAdjacentHTML('afterend',touchlessBox);}else{firstPage.insertAdjacentHTML('afterbegin',touchlessBox);}}},calendarCheck:function(){var section=JotForm.currentSection;if(!section){section=document.querySelector('.form-section');} var formLineCount=section.querySelectorAll('.form-line').length;var calendar=false;section.querySelectorAll('.form-line').forEach(function(element,index){if(index>=formLineCount-2&&element.dataset.type==='control_datetime'){var elementId=element.id.split('_')[1];calendar=JotForm.getCalendar(elementId);}});return calendar;},handleIFrameHeight:function(){var form=document.querySelectorAll('.jotform-form').length>0?document.querySelector('.jotform-form'):document.querySelector('body') var height=Math.max(JotForm.getDimensions(form).height,form.scrollHeight,form.offsetHeight) var isEmbedForm=document.querySelectorAll(".supernova.isEmbeded").length>0;if(isEmbedForm&&JotForm.getDimensions(form).width===0){console.warn('iframe is not visible, so we can\'t calculate the height');return;} var isEmbeddedInPortal=document.querySelectorAll(".supernova.isEmbeddedInPortal").length>0;var formWrapper=document.querySelector('.form-all');var formWrapperComputedStyle=getComputedStyle(formWrapper);var marginTop=parseInt(formWrapperComputedStyle.marginTop,10);var marginBottom=parseInt(formWrapperComputedStyle.marginBottom,10);if(!isNaN(marginTop)){height+=marginTop;} if(!isNaN(marginBottom)&&!isEmbeddedInPortal){height+=marginBottom;} var openCalendars=document.querySelectorAll('.calendar.popup:not([style*="display: none"])');if(openCalendars.length>0){openCalendars.forEach(function(calendar){var calendarBottom=calendar.getBoundingClientRect().bottom;if(height>calendarBottom){return;} height=calendarBottom;console.log('calendar height is bigger than form height, increasing form height to '+height);});} const isWelcomeMode=document.querySelector('html').getAttribute('data-mode')==='welcomeMode';if(typeof JotForm.importedPDF!=='undefined'&&typeof MutationObserver!=='undefined'&&typeof ResizeObserver!=='undefined'&&JotForm.importedPDF&&isWelcomeMode){const welcomeView=document.querySelector('#pdfimporter-root .pdff-welcomeView');const welcomeViewHeight=welcomeView?Math.max(welcomeView.offsetHeight+160,539):0;height=welcomeViewHeight>0?welcomeViewHeight:height;} height=(document.title==='Please Complete')?300:height;if(window.FORM_MODE==='cardform'){document.body.classList.add('isEmbed') var isSmartEmbed=document.body.classList.contains('isSmartEmbed') height=isSmartEmbed?464:640;try{var formFrame=window.parent.document.querySelector('[id="'+form.id+'"], [id="JotFormIFrame-'+form.id+'"]');if(formFrame&&formFrame.hasAttribute('data-frameHeight')){height=formFrame.getAttribute('data-frameHeight');}}catch(e){}} if(isEmbedForm){var computedStyles=getComputedStyle(document.querySelector(".supernova.isEmbeded"));var backgroundImage=computedStyles.getPropertyValue("background-image");if(backgroundImage&&backgroundImage!='none'){var backgroundStyles=new URLSearchParams();var properties=["background-image","background-size","background-position","background-repeat","background-attachment","background-color"];properties.forEach(function(property){backgroundStyles.set(property,computedStyles.getPropertyValue(property));});window.parent.postMessage('backgroundStyles:'+backgroundStyles.toString()+':'+form.id,'*');} try{if(!window.hcaptcha&&window.grecaptcha&&typeof window.grecaptcha.reset==='function'&&!window.grecaptcha.resetted){window.grecaptcha.resetted=true;window.grecaptcha.reset();console.log('grecaptcha resetted');}}catch(e){console.log("grecaptcha - ",e);}} if("console"in window){if("log"in console&&JotForm.debug){console.log('Debug : setting height to ',height,' from iframe');}} var isFeedbackEmbedButton=window.FORM_MODE==='cardform'&&document.location.search.indexOf('feedbackEmbedButton')>-1;if(!isFeedbackEmbedButton){window.parent.postMessage('setHeight:'+height+':'+form.id,'*');}},fixIESubmitURL:function(){try{if(this.ie()<=8&&navigator.appVersion.indexOf('NT 5.')){$A(this.forms).each(function(form){if(form.action.include("s://submit.")){form.action=form.action.replace(/\/\/submit\..*?\//,"//secure.jotform.com/");}});}}catch(e){}},screenshot:false,passive:false,onprogress:false,compact:false,imageSaved:false,handleScreenshot:function(){var $this=this;setTimeout(function(){document.querySelectorAll('.form-screen-button').forEach(function(button){if(window.parent&&window.parent.JotformFeedbackManager){$this.getContainer(button).style.display='';button.addEventListener('click',function(){$this.passive=false;try{$this.takeScreenShot(button.id.replace('button_',''));}catch(e){console.error(e);}});setTimeout(function(){$this.passive=!window.parent.wishboxInstantLoad;$this.takeScreenShot(button.id.replace('button_',''));},0);}});},300);},getCharset:function(doc){if(!doc){doc=document;} return doc.characterSet||doc.defaultCharset||doc.charset||'UTF-8';},bytesToSize:function(bytes,precision){var sizes=['B','KB','MB','GB','TB'];var posttxt=0;if(bytes==0)return'n/a';if(bytes<1024){return Number(bytes)+" "+sizes[posttxt];} while(bytes>=1024){posttxt++;bytes=bytes/1024;} return bytes.toFixed(precision||2)+" "+sizes[posttxt];},disableHTML5FormValidation:function(){document.querySelectorAll("form").forEach(function(f){f.setAttribute("novalidate",true);});},takeScreenShot:function(id){var p=window.parent;var pleaseWait='
'+''+'
'+'Please Wait'+'
';if(this.onprogress){p.$jot(pleaseWait).appendTo('body');return;} if(p.wishboxCompactLoad){this.compact=true;} if(this.screenshot){if(this.compact){p.$jot('.jt-dimmer').hide();}else{p.$jot('.jt-dimmer, .jotform-feedback-link, .jt-feedback').hide();} p.jotformScreenshotURL=this.screenshot.data;this.injectEditor(this.screenshot.data,this.screenshot.shotURL);return;} this.scuniq=JotForm.uniqid();this.scID=id;var f=JotForm.getForm($('button_'+this.scID));this.sformID=f.formID.value;this.onprogress=true;var $this=this;this.wishboxServer='https://screenshots.jotform.com/wishbox-server.php';var form=document.createElement('form');form.action=this.wishboxServer;form.target='screen_frame';form.id='screen_form';form.method='post';form.acceptCharset='utf-8';form.style.display='none';var doc='';p.$jot('.jt-dimmer, .jotform-feedback-link, .jt-feedback').hide();p.$jot('.hide-on-screenshot, .hide-on-screenshot *').css({'visibility':'hidden'});var parentSource=p.document.getElementsByTagName('html')[0].innerHTML;parentSource=parentSource.replace(/(]*>.*?<\/noscript>)+/gim,'');parentSource=parentSource.replace(/(]*>(\s+.*\s+)+)+<\/noscript>/gim,'');p.$jot('.hide-on-screenshot, .hide-on-screenshot *').css({'visibility':'visible'});parentSource=parentSource.replace(/(\<\/head\>)/gim,"$1");var ie=$this.ie();if(ie!==undefined&&ie<9){parentSource=parentSource.replace(/(\<\/head\>)/gim,"$1");} if(this.passive){p.$jot('.jt-dimmer, .jotform-feedback-link, .jt-feedback').show();}else{p.$jot('.jotform-feedback-link').show();p.$jot(pleaseWait).appendTo('body');} var html=document.createElement('textarea');html.name='html';var nozip=this.getCharset(p.document).toLowerCase()!=='utf-8';if(nozip){form.appendChild(createHiddenInputElement({name:'nozip',value:'1'}));html.value=encodeURIComponent(doc+parentSource+"");}else{form.appendChild(createHiddenInputElement({name:'nozip',value:'0'}));html.value=encodeURIComponent(p.$jot.jSEND((doc+parentSource+"")));} var charset=createHiddenInputElement({name:'charset',value:this.getCharset(p.document)});var height=createHiddenInputElement({name:'height',value:parseFloat(p.$jot(p).height())});var scrollTop=createHiddenInputElement({name:'scrollTop',value:p.$jot(p).scrollTop()});var url=createHiddenInputElement({name:'url',value:p.location.href});var uid=createHiddenInputElement({name:'uniqID',value:this.scuniq});var fid=createHiddenInputElement({name:'formID',value:this.sformID});var action=createHiddenInputElement({name:'action',value:'getScreenshot'});var iframe=document.createElement('iframe');iframe.name='screen_frame';iframe.id='screen_frame_id';iframe.style.display='none';iframe.observe('load',function(){$this.checkScreenShot();});if(p.wishboxInstantLoad&&(ie===undefined||ie>8)){this.injectEditor(false,false);} form.insert(html).insert(height).insert(scrollTop).insert(action).insert(uid).insert(url).insert(fid).insert(charset);$(document.body).insert(form).insert(iframe);form.submit();},checkJSON:function(){if(typeof JSON!=='object'){var script=document.createElement('script');script.type="text/javascript";script.src="/js/vendor/json2.js";document.body.appendChild(script);}},checkScreenShot:function(){var $this=this;var p=window.parent;var count=10;p.$jot.getJSON('https://screenshots.jotform.com/queue/'+this.scuniq+'?callback=?',function(data){if(data.success===true){p.$jot.getJSON(data.dataURL+'?callback=?',function(res){if($this.passive===false){p.jotformScreenshotURL=res.data;$this.injectEditor(res.data,res.shotURL);} $this.screenshot=res;$this.onprogress=false;$('screen_form')&&$('screen_form').remove();$('screen_frame_id')&&$('screen_frame_id').remove();});}else{if((data.status=='waiting'||data.status=='working')&&--count){setTimeout(function(){$this.checkScreenShot();},1000);}else{alert('We are under heavy load right now. Please try again later.');p.$jot('.jt-dimmer, .jotform-feedback-link').show();p.$jot('.jt-feedback').show('slow');}}});},injectEditor:function(data,url){if(this.injected){return;} this.injected=true;var $this=this;var p=window.parent;p.$jot('#js_loading').remove();p.$jot.getJSON(this.server+'?callback=?',{action:'getScreenEditorTemplate',compact:this.compact},function(res){var iff='';var editorFrame;p.iframeWidth=((p.$jot(p).width()-100)-p.$jot('#js-form-content').width());p.iframeHeight=(p.$jot(p).height()-120);if($this.compact){editorFrame=p.$jot(iff).insertBefore('#js-form-content');}else{editorFrame=p.$jot(iff).appendTo('body');} if($this.compact){p.$jot('#js-form-content').css({'float':'right'});} var ie=$this.ie();var closeFrame=function(){if($this.compact){editorFrame.remove();p.$jot('#js-form-content').css('width','100%');}else{editorFrame.hide('slow',function(){editorFrame.remove();});} $this.injected=false;p.$jot('.jt-dimmer, .jotform-feedback-link').show();p.$jot('.jt-feedback').show('slow');};var putImageOnForm=function(image,url){$('screen_'+$this.scID).update('');$('data_'+$this.scID).value=image;$('screen_'+$this.scID).up().show();};if(ie!==undefined&&ie<9){editorFrame.attr('src','https://screenshots.jotform.com/opt/templates/screen_editor.html?shot='+url+'&uniq='+$this.scuniq);var b=p.$jot('').appendTo('body');b.click(function(){p.$jot.getJSON('https://screenshots.jotform.com/wishbox-server.php?callback=?',{action:'getImage',uniqID:$this.scuniq},function(res){if(!res.success){if(confirm('You haven\'t save your edits. Are you sure you want to close the editor?')){closeFrame();b.remove();}}else{closeFrame();b.remove();putImageOnForm(res.data,res.shotURL);}});});}else{var e=editorFrame[0];var frameDocument=(e.contentWindow)?e.contentWindow:(e.contentDocument.document)?e.contentDocument.document:e.contentDocument;frameDocument.document.open();frameDocument.document.write(res.template);setTimeout(function(){frameDocument.document.close();},200);p.jotformScreenshotURL=data;} p.JotformCancelEditor=function(){closeFrame();};p.JotformFinishEditing=function(image){closeFrame();putImageOnForm(image);$this.imageSaved=true;if($this.compact){setTimeout(function(){$(document).fire('image:loaded');},100);}};});},populateGet:function(){try{if('FrameBuilder'in window.parent&&"get"in window.parent.FrameBuilder&&window.parent.FrameBuilder.get!=[]){var outVals={};var getVals=window.parent.FrameBuilder.get;$H(getVals).each(function(pair){if(typeof pair[1]==='object'){for(prop in pair[1]){outVals[pair[0]+"["+prop+"]"]=pair[1][prop];}}else{outVals[pair[0]]=pair[1];}});document.get=Object.extend(document.get,outVals);}}catch(e){}},uniqid:function(prefix,more_entropy){if(typeof prefix=='undefined'){prefix="";} var retId;var formatSeed=function(seed,reqWidth){seed=parseInt(seed,10).toString(16);if(reqWidthseed.length){return Array(1+(reqWidth-seed.length)).join('0')+seed;} return seed;};if(!this.php_js){this.php_js={};} if(!this.php_js.uniqidSeed){this.php_js.uniqidSeed=Math.floor(Math.random()*0x75bcd15);} this.php_js.uniqidSeed++;retId=prefix;retId+=formatSeed(parseInt(new Date().getTime()/1000,10),8);retId+=formatSeed(this.php_js.uniqidSeed,5);if(more_entropy){retId+=(Math.random()*10).toFixed(8).toString();} return retId;},initMultipleUploads:function(){var self=this;var isJotFormNext=JotForm.isJotFormNext||/jotformNext=1/.test(window.location.href);var isIosApp=JotForm.browserIs.ios()&&!JotForm.browserIs.safari();if(JotForm.browserIs.mobile()&&!isJotFormNext&&!isIosApp){var loadingNoSleepScript=true;var baseScriptURL='https://cdn.jotfor.ms';if(JotForm.enterprise||window.location.href.indexOf('jotform.pro')>-1){baseScriptURL=window.location.origin;} var noSleepURL=baseScriptURL+'/js/vendor/NoSleep.min.js';JotForm.loadScript(noSleepURL,function(){loadingNoSleepScript=false;});var toggleNoSleep=function(){if(loadingNoSleepScript||typeof NoSleep==='undefined'){return;} var noSleep=new NoSleep();noSleep.enable();document.removeEventListener('click',toggleNoSleep,true);};document.addEventListener('click',toggleNoSleep,true);} if(isJotFormNext&&JotForm.switchedToOffline&&JotForm.rawMultipleFileInputs){JotForm.resetMultipleUploadsBasicMarkup();} if(window.FORM_MODE!=='cardform'){callIframeHeightCaller();} JotForm.uploader={};$$('.form-upload-multiple').each(function(file){var parent=file.up('div');var f=JotForm.getForm(file);var formID=f.formID.value;if(isJotFormNext){JotForm.captureMultipleUploadsBasicMarkup(file);} var uniq=formID+"_"+JotForm.uniqueID;parent.addClassName('validate[multipleUpload]');var className=file.className;if(className.include("validate[required]")){if(parent.className.indexOf("validate[required]")===-1){parent.addClassName("validate[required]");}} parent.validateInput=function(){var _isVisible=JotForm.isVisible(parent);if(JotForm.doubleValidationFlag()){_isVisible=!(JotForm.isInputAlwaysHidden(parent));} if(!_isVisible){JotForm.corrected(parent);return true;} if(JotForm.isFillingOffline()){return JotForm.corrected(parent);} var fileList=parent.select('.qq-upload-list li:not(.file-deleted)');if(fileList.length<1){if(parent.match('[class*=validate[required]]')){JotForm.corrected(parent);return JotForm.errored(parent,JotForm.texts.required);}else{JotForm.corrected(parent);return true;}}else{var status=true;fileList.each(function(elem){if(elem.getAttribute('class')&&elem.getAttribute('class').indexOf('fail')>=0){status=false;}});if(status){JotForm.corrected(parent);return true;}else{JotForm.errored(parent,JotForm.texts.multipleFileUploads_uploadFailed);return false;}}} if(!JotForm.tempUploadFolderInjected){f.appendChild(createHiddenInputElement({name:'temp_upload_folder',value:uniq}));JotForm.tempUploadFolderInjected=true;} var exts=(file.readAttribute('data-file-accept')||file.readAttribute('file-accept')||"").strip();exts=(exts!=='*')?exts.split(',').map(function(item){return item.trim();}):[];var n,subLabel="";if((n=file.next())&&n.hasClassName('form-sub-label')){subLabel=n.innerHTML;} var m,buttonText,cancelText='Cancel',ofText='of';if(m=file.previous('.qq-uploader-buttonText-value')){buttonText=m.innerHTML;} if(m=file.up('li.form-line').querySelector('.jfUpload-button')){var isV2=m.readAttribute('data-version')==='v2';buttonText=isV2?m.innerHTML:m.innerText;} if(!buttonText){buttonText="Upload a File";} if(subLabel){if(m=parent.querySelector(".cancelText")){cancelText=m.innerText;} if(m=parent.querySelector(".ofText")){ofText=m.innerText;}} else{if(m=parent.siblings().find(function(el){return el.className==='cancelText'})){cancelText=m.innerText;} if(m=parent.siblings().find(function(el){return el.className==='ofText'})){ofText=m.innerText;}} var classNames=file.className.split(' ');var buttonStyle='';$A(classNames).each(function(className){if(className.indexOf('form-submit-button-')===0){buttonStyle=className;}});try{var eventIDElement=document.querySelector('input[name="event_id"]');var uploader=JotForm.isFillingOffline()?false:new qq.FileUploader({debug:JotForm.debug,element:parent,action:JotForm.server,subLabel:subLabel,buttonText:buttonText,buttonStyle:buttonStyle,fileLimit:file.readAttribute('data-file-limit')||file.readAttribute('file-limit'),sizeLimitActive:file.readAttribute('data-limit-file-size')||file.readAttribute('limit-file-size'),sizeLimit:parseInt((file.readAttribute('data-file-maxsize')||file.readAttribute('file-maxsize')),10)*1024,minSizeLimit:parseInt((file.readAttribute('data-file-minsize')||file.readAttribute('file-minsize')),10)*1024,allowedExtensions:exts,cancelText:cancelText,ofText:ofText,messages:{typeError:self.texts.multipleFileUploads_typeError,sizeError:self.texts.multipleFileUploads_sizeError,minSizeError:self.texts.multipleFileUploads_minSizeError,emptyError:self.texts.multipleFileUploads_emptyError,onLeave:self.texts.multipleFileUploads_onLeave,fileLimitError:self.texts.multipleFileUploads_fileLimitError},onComplete:function(id,filename,response){console.log('onComplete',arguments);if(response.success){var qFolder=file.name.replace('[]','');if('message'in response){filename=response.message;} var uploadHiddenID=[this.params.folder,qFolder,filename].join('_');var uploadHiddenInput=document.getElementById(uploadHiddenID);if(!uploadHiddenInput){uploadHiddenInput=createHiddenInputElement({name:'temp_upload['+qFolder+'][]',id:uploadHiddenID});f.appendChild(uploadHiddenInput);} uploadHiddenInput.value=filename;if($('draftID')){var uploadedFiles=[];var uploadedFileID=['uploadNewForSACL',qFolder].join('-');var uploadedFileInput=document.getElementById(uploadedFileID);if(!uploadedFileInput){uploadedFileInput=createHiddenInputElement({name:uploadedFileID,id:uploadedFileID});f.appendChild(uploadedFileInput);}else{uploadedFiles=uploadedFiles.concat(JSON.parse(uploadedFileInput.value));} uploadedFiles.push(filename);uploadedFileInput.value=JSON.stringify(uploadedFiles);} var fileServerInput=document.getElementById('file_server');if(!fileServerInput){fileServerInput=createHiddenInputElement({name:'file_server',id:'file_server'});f.appendChild(fileServerInput);} fileServerInput.value=response.fileServer;parent.value='uploaded';parent.validateInput();}},onDelete:function(folder,field,filename){var id=[folder,field,filename].join('_');if($('draftID')){var uploadedFileID=['uploadNewForSACL',field].join('-');var uploadedFile=$(uploadedFileID);var uplodedFileArray=uploadedFile?JSON.parse(uploadedFile.value):[];if(uplodedFileArray.includes(filename)){const filteredUplodedFileArray=uplodedFileArray.filter(function(item){return item!==filename;});if(filteredUplodedFileArray.length<1){$(uploadedFileID).remove();}else{uploadedFile.value=JSON.stringify(filteredUplodedFileArray);}}else if($(id)){var deletedFiles=[];var deletedFileID=['deletedFileForSACL',field].join('-');var deletedFileInput=document.getElementById(deletedFileID);if(!deletedFileInput){deletedFileInput=createHiddenInputElement({name:deletedFileID,id:deletedFileID});f.appendChild(deletedFileInput);}else{deletedFiles=deletedFiles.concat(JSON.parse(deletedFileInput.value));} deletedFiles.push(filename);deletedFileInput.value=JSON.stringify(deletedFiles);}} if($(id))$(id).remove();parent.validateInput();},showMessage:function(message){console.log('showMessage',arguments);JotForm.corrected(parent);JotForm.errored(parent,message);},params:{action:'multipleUpload',field:file.name?file.name.replace('[]',''):'',origin:window.location.origin||(window.location.protocol+'//'+window.location.hostname),folder:uniq,event_id:eventIDElement&&eventIDElement.value},onSubmit:function(){this.params.folder=document.querySelector("input[name='temp_upload_folder']").value;}});var initWarningTranslations=function(t){setTimeout(function(){if(uploader&&uploader._options){uploader._options.messages={typeError:self.texts.multipleFileUploads_typeError,sizeError:self.texts.multipleFileUploads_sizeError,minSizeError:self.texts.multipleFileUploads_minSizeError,emptyError:self.texts.multipleFileUploads_emptyError,onLeave:self.texts.multipleFileUploads_onLeave,fileLimitError:self.texts.multipleFileUploads_fileLimitError};}},t);};initWarningTranslations(1000);JotForm.uploader[file.id]=uploader;}catch(e){console.log(e);}});Array.from(document.querySelectorAll('.jfUpload-text, .qq-upload-button')).forEach(function(field){var heading=field.querySelector('.jfUpload-heading.forDesktop');heading&&(heading.textContent=JotForm.texts.dragAndDropFilesHere_infoMessage);var headingMobile=field.querySelector('.jfUpload-heading.forMobile');headingMobile&&(headingMobile.textContent=JotForm.texts.chooseAFile_infoMessage);var subHeading=field.querySelector('.maxFileSize');subHeading&&(subHeading.textContent=JotForm.texts.maxFileSize_infoMessage);});},captureMultipleUploadsBasicMarkup:function(fileInput){if(!JotForm.rawMultipleFileInputs)JotForm.rawMultipleFileInputs={};var qID=fileInput.getAttribute('id').match(/input_(.*)/)[1];if(qID){JotForm.rawMultipleFileInputs[qID]=fileInput.outerHTML;}},resetMultipleUploadsBasicMarkup:function(){Object.keys(JotForm.rawMultipleFileInputs).forEach(function(qID){const fileInput=document.querySelector('li#id_'+qID+' input[type="file"]');const inputContainer=fileInput.closest('div.validate\\[multipleUpload\\]');const rawInput=JotForm.rawMultipleFileInputs[qID];if(!inputContainer||!rawInput)return;const fileList=inputContainer.querySelector('ul.qq-upload-list');let fileListMarkup='';if(fileList){fileList.querySelectorAll('.qq-upload-delete').forEach(function(each){each.parentNode.removeChild(each);;});fileListMarkup=fileList.outerHTML;} while(inputContainer.firstChild)inputContainer.removeChild(inputContainer.firstChild);inputContainer.insertAdjacentHTML('afterbegin',rawInput);inputContainer.insertAdjacentHTML('beforeend',fileListMarkup);});},hiddenSubmit:function(frm,options){var checkPagesNumber=document.querySelectorAll('.form-section')||null;var currentPage=JotForm.currentSection.pagesIndex;var selectPageBreak=(JotForm.newDefaultTheme&&checkPagesNumber.length===currentPage)?'.form-pagebreak-back-container':'.form-pagebreak';if(JotForm.currentSection){var formSavingIndicatorEl=document.createElement('div');formSavingIndicatorEl.className='form-saving-indicator';formSavingIndicatorEl.style.float='right';formSavingIndicatorEl.style.padding='21px 12px 10px';formSavingIndicatorEl.innerHTML=' Saving...';JotForm.currentSection.querySelector(selectPageBreak).appendChild(formSavingIndicatorEl);} setTimeout(function(){JotForm.saving=true;JotForm.disableButtons();},10);var isCardForm=window.FORM_MODE=='cardform';if(!$('hidden_submit_form')){var iframe=document.createElement('iframe');iframe.name='hidden_submit';iframe.id='hidden_submit_form';iframe.style.display='none';iframe.observe('load',function(){JotForm.makeUploadChecks();$$('.form-saving-indicator').invoke('remove');JotForm.saving=false;JotForm.enableButtons();});$(document.body).insert(iframe);} $$('.form-radio-other,.form-checkbox-other').each(function(el){if(!el.checked&&JotForm.getOptionOtherInput(el)){JotForm.getOptionOtherInput(el).disable();}});$$('.custom-hint-group').each(function(elem){elem.hideCustomPlaceHolder();});if($('current_page')){$('current_page').value=JotForm.currentSection.pagesIndex;} frm.writeAttribute('target','hidden_submit');frm.insert({top:createHiddenInputElement({name:'hidden_submission',id:'hidden_submission',value:'1'})});if(isCardForm){frm.insert({top:createHiddenInputElement({name:'continueLater',id:'continueLater',value:'1'})});} trackExecution('hidden-submit-async-'+(options&&!!options.async));if(options&&!!options.async){var frmAction=new URL(frm.action);if(frm.action.include('pci.jotform')){var formUrl=new URL(this.url);frmAction.hostname=formUrl.hostname;} var xhr=new XMLHttpRequest();xhr.withCredentials=true;xhr.open('POST',frmAction,true);xhr.addEventListener('load',function(){var response=this;if(isCardForm){JotForm.saving=false;JotForm.enableButtons();} if(200===response.status){if(options.onSuccessCb)options.onSuccessCb(response);}else{if(options.onFailureCb)options.onFailureCb();} if(options.onCompleteCb)options.onCompleteCb();frm.writeAttribute('target','');if(isCardForm){$('continueLater')&&$('continueLater').remove();} $('hidden_submission')&&$('hidden_submission').remove();$$('.custom-hint-group').each(function(elem){elem.showCustomPlaceHolder();});$$('.form-radio-other,.form-checkbox-other').each(function(el){if(!el.checked&&JotForm.getOptionOtherInput(el)){JotForm.getOptionOtherInput(el).enable();}});});if(options&&options.isClone){var allInputs=frm.querySelectorAll('input[type="hidden"]');for(var i=0;i-1&&allInputs[i].value===''){allInputs[i].remove();}}} xhr.send(new FormData(frm));}else{JotForm.ignoreDirectValidation=true;frm.submit();frm.writeAttribute('target','');if(isCardForm){$('continueLater').remove();} $('hidden_submission').remove();$$('.custom-hint-group').each(function(elem){elem.showCustomPlaceHolder();});$$('.form-radio-other,.form-checkbox-other').each(function(el){if(!el.checked&&JotForm.getOptionOtherInput(el)){JotForm.getOptionOtherInput(el).enable();}});}},makeUploadChecks:function(){var formIDField=$$('input[name="formID"]')[0];var parameters={action:'getSavedUploadResults',formID:formIDField.value,sessionID:this.sessionID};if(this.submissionID){parameters.submissionID=this.submissionID;} if(this.submissionToken){parameters.submissionToken=this.submissionToken;} new Ajax.Jsonp(JotForm.server,{parameters:parameters,evalJSON:'force',onComplete:function(t){var res=t.responseJSON;if(res&&res.success){if(res.submissionID&&!$('submission_id')){if(!JotForm.submissionID){JotForm.setSubmissionID(res.submissionID);} formIDField.insert({after:createHiddenInputElement({name:'submission_id',id:'submission_id',value:res.submissionID})});} if(window.FORM_MODE==='cardform'){JotForm.editMode(res,true,null,true);}else{JotForm.editMode(res,true);}}}});},handleSavedForm:function(){var savedSessionID=('session'in document.get)&&(document.get.session.length>0)?document.get.session:false;if(!JotForm.sessionID&&!savedSessionID){return;} JotForm.saveForm=JotForm.sessionID?true:false;var isCardForm=window.FORM_MODE=='cardform';var formIDField=$$('input[name="formID"]')[0];var sessionIDField=document.getElementById('session');if(!sessionIDField){formIDField.insert({after:createHiddenInputElement({name:'session_id',id:'session',value:JotForm.sessionID})});} var tokenField=document.getElementById('submission_token');if(!tokenField&&!isCardForm&&this.submissionToken){formIDField.insert({after:createHiddenInputElement({name:'submission_token',id:'submission_token',value:this.submissionToken})});} if(!isCardForm){formIDField.insert({after:createHiddenInputElement({name:'current_page',id:'current_page',value:0})});} JotForm.loadingPendingSubmission=true;var parameters={action:'getSavedSubmissionResults',formID:formIDField.value,sessionID:savedSessionID,URLparams:window.location.href};if(this.submissionID){parameters.submissionID=this.submissionID;} if(this.submissionToken){parameters.submissionToken=this.submissionToken;} if(window.JFAppsManager&&window.JFAppsManager.isProductListForm){parameters.platform='APP';parameters.platform_id=window.JFAppsManager.appID;parameters.checkoutKey=window.JFAppsManager.checkoutKey;parameters.submissionID=window.JFAppsManager.submissionID;} new Ajax.Jsonp(JotForm.url+'/server.php',{parameters:parameters,evalJSON:'force',onComplete:function(t){var res=t.responseJSON;var isRealSuccess=res.success&&!!res.submissionID;if(isRealSuccess){if(res.submissionID){if(!$('submission_id')){var submissionID=JotForm.submissionID||res.submissionID;formIDField.insert({after:createHiddenInputElement({name:'submission_id',id:'submission_id',value:submissionID})});if(!JotForm.submissionID){JotForm.setSubmissionID(res.submissionID);}} if(!$('submission_token')){var submissionToken=this.submissionToken||res.token;if(submissionToken){formIDField.insert({after:createHiddenInputElement({name:'submission_token',id:'submission_token',value:submissionToken})});if(!this.submissionToken){this.submissionToken=submissionToken;}}} try{if(window.FORM_MODE==='cardform'){JotForm.editMode(res,true,null,true);}else{JotForm.editMode(res,true);}}catch(e){JotForm.loadingPendingSubmission=false;} JotForm.openInitially=res.currentPage-1;} if(res.jfFormUserSCL_emailSentTo&&!$('jfFormUserSCL_emailSentTo')){formIDField.insert({after:createHiddenInputElement({name:'jfFormUserSCL_emailSentTo',id:'jfFormUserSCL_emailSentTo',value:res.jfFormUserSCL_emailSentTo})});}} JotForm.loadingPendingSubmission=false;}});},setSubmissionID:function(submissionID){this.submissionID=submissionID;},setHTMLClass:function(){var ie=this.ie();if(ie){document.querySelector('html').classList.add('ie-'+ie);}},setFocusEvents:function(){document.querySelectorAll('.form-radio, .form-checkbox, .newDefaultTheme-dateIcon').forEach(function(input){input.addEventListener('mousedown',function(){JotForm.lastFocus=input;}) input.addEventListener('focus',function(){JotForm.lastFocus=input;})});document.querySelectorAll('.form-textbox, .form-password, .form-textarea, .form-upload, .form-dropdown').forEach(function(input){input.addEventListener('focus',function(){JotForm.lastFocus=input;});});if((JotForm.newPaymentUI)&&(window.paymentType!=='product'&&window.paymentType!=='subscription')&&window.FORM_MODE!=='cardform'){document.querySelectorAll('[data-component="paymentDonation"]').forEach(function(element){element.closest('.form-line').classList.add('donation_cont');});} if((JotForm.newPaymentUI)&&window.paymentType==='product'&&window.FORM_MODE!=='cardform'){var productItems=document.querySelectorAll('.form-product-item');Array.from(productItems).forEach(function(productItem){productItem.addEventListener('click',function(event){if(isIframeEmbedFormPure()){callIframeHeightCaller();} if(event.target.tagName!=='LABEL'&&!['text','select-one','checkbox','radio'].includes(event.target.type)&&!event.target.hasClassName('image_zoom')){if(productItem.querySelector('.form-checkbox')){var isSelectedProduct=productItem.classList.contains('p_selected')&&productItem.classList.contains('form-product-item');if(JotForm.browserIs.firefox()&&event.target.tagName==='OPTION'&&isSelectedProduct){return;} productItem.querySelector('.form-checkbox').click();}else{if(window.paymentType==='product'&&JotForm.categoryConnectedProducts&&Object.keys(JotForm.categoryConnectedProducts).length>0&&!JotForm.categoryConnectedProducts[productItem.getAttribute('pid')]){document.querySelectorAll('.form-product-input').forEach(function(item){if(item.checked&&item.getValue()!==productItem.getAttribute('pid')){item.checked=false;}});} productItem.querySelector('.form-radio').click();}} if(event.target.type==='checkbox'){var dropDownElement=productItem.querySelector('.form-dropdown');if(dropDownElement){var dropDownElementOptions=dropDownElement.options;var isZeroOptionExistInDropDownElementsOptions=false;for(var i=0;i0&&Array.from(quantityList).every(function(el){return['','0'].includes(el.value);})){productItem.classList.remove('p_selected');}}else{productItem.classList.remove('p_selected');}} if(['select-one','text'].includes(event.target.type)){if(['','0'].includes(event.target.value)){deselectProduct(event.target.type);}else{productItem.classList.add('p_selected');if(event.target.type==='select-one'){JotForm.countTotal();}}}});});document.querySelectorAll('.form-checkbox').forEach(function(element){var productItem=element.closest('.form-product-item');function shouldMakeProductSelected(){if(element.checked&&productItem){var quantityDd=productItem.querySelector('.select_cont select');if((quantityDd&&Number(quantityDd.value)>0)||!quantityDd){return true;}} return false;} if(shouldMakeProductSelected()){productItem.classList.add('p_selected');} element.addEventListener('click',function(){if(shouldMakeProductSelected()){productItem.classList.add('p_selected');}else{if(productItem&&productItem.classList.contains('p_selected')){productItem.classList.remove('p_selected');}}});});} if((JotForm.newPaymentUI)&&window.paymentType==='subscription'){document.querySelectorAll('.form-product-item').forEach(function(element){element.addEventListener('click',function(event){if(event.target.type!=='radio'&&event.target.type!=='text'&&event.target.type!=='select-one'&&!event.target.hasClassName('image_zoom')) {element.querySelector('.form-radio').click();}});});document.querySelectorAll('.form-product-item').forEach(function(element){element.closest('.form-line').classList.add('subscription_cont');});document.querySelectorAll('.form-product-item .form-radio').forEach(function(element){if(element.checked){element.closest('.form-product-item').classList.add('p_selected');} element.addEventListener('change',function(){element.closest('.form-product-item').classList.add('p_selected') document.querySelectorAll('.form-product-item .form-radio').forEach(function(subElement){if(subElement!==element)subElement.closest('.form-product-item').classList.remove('p_selected')});});});}},setBirthDateEvents:function(){function addOptionsToDayDropdown(dayDropdown,selectedMonth,selectedYear){var daysInMonth=new Date(selectedYear,selectedMonth,0).getDate();var daySelectedIndex=dayDropdown.selectedIndex;dayDropdown.innerHTML='';var defaultOption=document.createElement('option');dayDropdown.appendChild(defaultOption);for(var i=1;i<=daysInMonth;i++){var option=document.createElement('option');option.value=i;option.innerHTML=i;dayDropdown.appendChild(option);} if(daySelectedIndex<=dayDropdown.children.length){dayDropdown.selectedIndex=daySelectedIndex;}} var birthdateElements=document.querySelectorAll('[data-type="control_birthdate"]');birthdateElements.forEach(birthdate=>{var birthdateMonth=birthdate.querySelector('[data-component="birthdate-month"]');var birthdateYear=birthdate.querySelector('[data-component="birthdate-year"]');var birthdateDay=birthdate.querySelector('[data-component="birthdate-day"]');let monthIndex=0;let year=2023;birthdateMonth.addEventListener('change',e=>{monthIndex=e.target.value;addOptionsToDayDropdown(birthdateDay,monthIndex,year);});birthdateYear.addEventListener('change',e=>{year=e.target.value;addOptionsToDayDropdown(birthdateDay,monthIndex,year);});});},disableAcceptonChrome:function(){if(JotForm.browserIs.webkit()){document.querySelectorAll('.form-upload').forEach(input=>{if(input.hasAttribute('accept')){var r=input.getAttribute('accept');input.setAttribute('accept','');input.setAttribute('data-file-accept',r);input.setAttribute('file-accept',r);}})}},browserInformations:function(){var is=JotForm.browserIs;function OS(){if(is.android())return"Android";else if(is.windows())return"Windows";else if(is.blackberry())return"Blackberry";else if(is.linux())return"Linux";else if(is.ios())return"iOS";else if(is.mac()&&!is.ios())return"MacOS";return"Unknown OS";} function device(){if(is.mobile()){if(is.windowsPhone()||is.androidPhone()||is.blackberry())return"Mobile";else if(is.ios())return"iPhone";} else if(is.tablet()){if(is.windowsTablet()||is.androidTablet())return"Tablet";else if(is.ios())return"iPad";} else if(is.desktop())return"Desktop";return"Unknown Device";} function browser(){if(is.ie())return"Internet Explorer";else if(is.firefox())return"Firefox";else if(is.chrome())return"Chrome";else if(is.safari())return"Safari";else if(is.operabrowser())return"Opera";return"Unknown Browser";} var offset=new Date().getTimezoneOffset();var sign=(offset<0)?"+":"";var timeZone='GMT '+sign+-(offset/60);var lang=navigator.language||navigator.browserLanguage||navigator.userLanguage;var val=['BROWSER: '+browser(),'OS: '+OS(),'DEVICE: '+device(),'LANGUAGE: '+lang,'RESOLUTION: '+screen.width+"*"+screen.height,'TIMEZONE: '+timeZone,'USER AGENT: '+navigator.userAgent].join('\n');return val;},populateBrowserInfo:function(id){var val=JotForm.browserInformations();setTimeout(function(){if($(id).getValue().length>0){val=[$(id).getValue(),val].join('\n');} $(id).setValue(val);},20);},displayTimeRangeDuration:function(id,justCalculate){var displayDuration=function(){if($('input_'+id+'_hourSelectRange')){var sHour=$('input_'+id+'_hourSelect').value;var sMin=$('input_'+id+'_minuteSelect').value||'00';var sAMPM=$('input_'+id+'_ampm')?$('input_'+id+'_ampm').value:'no';var eHour=$('input_'+id+'_hourSelectRange').value;var eMin=$('input_'+id+'_minuteSelectRange').value||'00';var eAMPM=$('input_'+id+'_ampmRange')?$('input_'+id+'_ampmRange').value:'no';var lab=$('input_'+id+'_ampmRange')&&!(JotForm.newDefaultTheme||JotForm.extendsNewTheme)?'_ampmRange':'_dummy';var durationLabel=$$('label[for=input_'+id+lab+']').first();if(window.FORM_MODE==='cardform'){if(lab=='_ampmRange'){durationLabel=$$('label[for=input_'+id+lab+']').first();}else{durationLabel=$$('#input_'+id+lab).first();}} if(sHour.length>0&&sMin.length>0&&eHour.length>0&&eMin.length>0){if(sAMPM=='PM'&&sHour!=12)sHour=parseInt(sHour)+12;if(sAMPM=='AM'&&sHour==12)sHour=0;if(eAMPM=='PM'&&eHour!=12)eHour=parseInt(eHour)+12;if(eAMPM=='AM'&&eHour==12)eHour=0;var start=new Date(0,0,0,sHour,sMin,0);var end=new Date(0,0,0,eHour,eMin,0);var diff=end.getTime()-start.getTime();if(diff<0){end=new Date(0,0,1,eHour,eMin,0);diff=end.getTime()-start.getTime();} var hours=Math.floor(diff/1000/60/60);diff-=hours*1000*60*60;var min=Math.floor(diff/1000/60);if(min<10)min='0'+min;if(justCalculate){return[hours.toString(),min.toString()];} durationLabel.update('Total '+hours+':'+min+'');durationLabel.setStyle({'color':'black'});$$('input[id=duration_'+id+'_ampmRange][type="hidden"]').first().setValue(hours+':'+min);}else if(!justCalculate){durationLabel.update(' ');} if($('input_'+id+'_timeInput')&&$('input_'+id+'_hourSelect')&&$('input_'+id+'_hourSelect').triggerEvent){$('input_'+id+'_hourSelect').triggerEvent('change');}}};if($('input_'+id+'_timeInput')){$('input_'+id+'_timeInput').observe('blur',displayDuration);$('input_'+id+'_timeInputRange').observe('blur',displayDuration);}else{$('input_'+id+'_hourSelect').observe('change',displayDuration);$('input_'+id+'_minuteSelect').observe('change',displayDuration);$('input_'+id+'_hourSelectRange').observe('change',displayDuration);$('input_'+id+'_minuteSelectRange').observe('change',displayDuration);} if($('input_'+id+'_ampm')&&$('input_'+id+'_ampmRange')){$('input_'+id+'_ampm').observe('change',displayDuration);$('input_'+id+'_ampmRange').observe('change',displayDuration);} var timeDiff;if(JotForm.isEditMode()){var waitDom=function(){if($('input_'+id+'_hourSelectRange')&&$('input_'+id+'_hourSelectRange').value.empty()){window.setTimeout(waitDom,100);}else{timeDiff=displayDuration();}} waitDom();}else{timeDiff=displayDuration();} return timeDiff;},displayLocalTime:function(hh,ii,ampm,v2,fixCurrentAmPm){if(JotForm.isEditMode()&&fixCurrentAmPm)return;const hhElement=document.querySelector(`#${hh}`);if(hhElement&&!hhElement.classList.contains('noDefault')){const date=new Date();let hour=date.getHours();let currentAmpm="";let twentyFour=true;const ampmElement=document.querySelector(`#${ampm}`);if(ampmElement){twentyFour=false;currentAmpm=(hour>11)?'PM':'AM';hour=(hour>12)?hour-12:hour;hour=(hour==0)?12:hour;} let min=date.getMinutes();const iiElement=document.querySelector(`#${ii}`);if(!v2){const step=Number(iiElement.options[2].value)-Number(iiElement.options[1].value);min=Math.round(min/step)*step;} min=this.addZeros(min,2);if(min>=60){min="00";hour++;if(twentyFour){if(hour==24)hour=0;}else{if(currentAmpm=='AM'&&hour==12)currentAmpm='PM';else if(currentAmpm=='PM'&&hour==12)currentAmpm='AM';else if(hour==13)hour=1;}} if(hour<10&&(!!v2||hhElement.options[1].value.length>1)){hour='0'+hour;} if(ampmElement){const ampmRangeEl=document.querySelector(`#${ampm}Range`);if(currentAmpm=='PM'){if(ampmElement.querySelectorAll('option[value="PM"]').length>0)ampmElement.value='PM';if(ampmRangeEl&&mRangeEl.querySelectorAll('option[value="PM"]').length>0)ampmRangeEl.value='PM';}else{if(ampmElement.querySelectorAll('option[value="AM"]').length>0)ampmElement.value='AM';if(ampmRangeEl&&mRangeEl.querySelectorAll('option[value="AM"]').length>0)ampmRangeEl.value='AM';}} if(fixCurrentAmPm)return;hhElement.value=hour;iiElement.value=min;if(document.querySelector(`#${hh}Range`)){document.querySelector(`#${hh}Range`).value=hour;document.querySelector(`#${ii}Range`).value=min;} if(document.querySelector(`#${v2}Range`)){document.querySelector(`#${v2}Range`).value=hour+':'+min;} if(v2){document.querySelector(`#${v2}`).value=hour+':'+min;}}},setDateTimeFieldItem:function(fieldItem,qid){const isHourOrMin=fieldItem.key==='hour'||fieldItem.key==='min';const value=fieldItem.value;let element;if(isHourOrMin){const _key=fieldItem.key==='hour'?'hour':'minute';let hourOrMinEl=document.querySelector('#input_'+qid+'_'+_key+'Select');if(hourOrMinEl){hourOrMinEl.value=value.length<2&&value<10?'0'+value:value;}} const timeInputElement=document.querySelector("#input_"+qid+"_"+fieldItem.key) if(document.querySelector(`#${fieldItem.key}_${qid}`)){element=document.querySelector(`#${fieldItem.key}_${qid}`);element.value=value;}else if(timeInputElement&&(JotForm.newDefaultTheme||JotForm.extendsNewTheme||timeInputElement.dataset.version==="v2")){element=timeInputElement;element.value=value;} const elementIsSelect=element&&element.nodeName==='SELECT';if(elementIsSelect&&isHourOrMin&&element.options.selectedIndex===-1){element.value='0'+value;}},displayDynamicDate:function(id,dynamic){var offset=parseInt(dynamic.split('today')[1])||0;var dynamicDate=new Date();dynamicDate.setDate(dynamicDate.getDate()+offset);JotForm.formatDate({date:dynamicDate,dateField:document.querySelector(`#id_${id}`)});},dateLimits:{},getCalendar:function(id){var calendar=document.querySelector('#calendar_'+id);return calendar;},setCalendar:function(id,startOnMonday,limits,parent){try{var triggerElement="input_"+id+"_pick";JotForm.dateLimits[id]=limits;var field=$('id_'+id);var calendar=Calendar.setup({triggerElement:triggerElement,dateField:"year_"+id,parentElement:parent,closeHandler:function(){JotForm.calendarClose.apply(this,arguments);if($('lite_mode_'+id)){if(JotForm.newDefaultTheme&&($('lite_mode_'+id).hasClassName('calendar-opened'))){$('lite_mode_'+id).removeClassName('calendar-opened');} if(id.indexOf('-')>-1){$('lite_mode_'+id).triggerEvent('change');} $('lite_mode_'+id).triggerEvent('blur');}},selectHandler:function(){JotForm.formatDate.apply(this,arguments);},startOnMonday:startOnMonday,limits:limits,id:id});var calendarButton=document.querySelector('#'+triggerElement);calendarButton.observe("click",function(){var calendar=$("calendar_"+id);if(calendar.style&&calendar.style.display!=="none"){JotForm.handleIFrameHeight();}});field.observe('keyup',function(){field.fire('date:changed');});var clearDate=function(){$("month_"+id).value=$("day_"+id).value=$("year_"+id).value="";} var invalidDate=function(invalidDate){invalidDate.addClassName("invalidDate");clearDate();} if($('lite_mode_'+id)){$('lite_mode_'+id).dateChanged=function(e,calendar,doNotTriggerErrors){var lite_mode=e.currentTarget;var seperator=lite_mode.readAttribute('seperator')||lite_mode.readAttribute('data-seperator');var format=(lite_mode.readAttribute('format')||lite_mode.readAttribute('data-format')).toLowerCase();lite_mode.removeClassName("invalidDate");lite_mode.removeClassName("invalidLimits");field.removeClassName('form-line-error');field.removeClassName('form-datetime-validation-error');if(lite_mode.value===""){field.fire('date:changed');return clearDate();} var inputLength=calendar.isNewTheme?lite_mode.value.replace(new RegExp('[^\\d'+seperator+']'),'').length:lite_mode.value.length;if(inputLength==((seperator.length*2)+format.length)){var _yIn=format.indexOf("yy");var _mIn=format.indexOf("mm");var _dIn=format.indexOf("dd");var _sorter=new Array(_yIn,_mIn,_dIn);_sorter=_sorter.sort();var _sortIndex={year:_sorter.indexOf(_yIn),month:_sorter.indexOf(_mIn),day:_sorter.indexOf(_dIn)} var year=parseInt(lite_mode.value.split(seperator)[_sortIndex.year]);var month=parseInt(lite_mode.value.split(seperator)[_sortIndex.month])-1;var day=parseInt(lite_mode.value.split(seperator)[_sortIndex.day]);var _tempDate=new Date(year,month,day);if(!_tempDate||!_tempDate.getDate()){if(!doNotTriggerErrors)invalidDate(lite_mode,calendar);}else{calendar.setDate(_tempDate);calendar.selectHandler(calendar);}}else{if(!doNotTriggerErrors)invalidDate(lite_mode,calendar);} if(lite_mode.hasClassName("invalidDate")){JotForm.errored(lite_mode,'Enter a valid date');field.addClassName('form-line-error');field.addClassName('form-datetime-validation-error');}} $('lite_mode_'+id).observe('blur',function(e){e.stopPropagation();e.currentTarget.dateChanged(e,calendar);e.currentTarget.setAttribute("date-val",calendar.date.getTime());return false;});if(!JotForm.newDefaultTheme&&!JotForm.extendsNewTheme&&!calendar.isNewTheme){$('lite_mode_'+id).observe('keydown',function(e){var input=e.target.value;if(e.key==='Backspace'&&input[input.length-1]===e.target.dataset.seperator){input=input.substr(0,input.length-1);} e.target.value=input.substr(0,10);});$('lite_mode_'+id).observe('input',function(e){var input=e.target.value;var values=input.split(e.target.dataset.seperator).map(function(v){return v.replace(/\D/g,'')});var output=[];if(e.target.dataset.format!=='yyyymmdd'){output=values.map(function(v,i){return v.length==2&&i<2?v+e.target.dataset.seperator:v;});}else{output=values.map(function(v,i){return(v.length==4&&i==0)||(v.length==2&&i==1)?v+e.target.dataset.seperator:v;});} e.target.value=output.join('').substr(0,10);e.currentTarget.dateChanged(e,calendar,true);});}} if(!parent){var openCalendar=function(){var ele=this;setTimeout(function(){if(JotForm.newDefaultTheme){handlePopupUI(calendar,{width:ele.parentNode.parentNode.offsetWidth});} calendar.showAtElement(ele);},50);};if($('input_'+id+'_pick').hasClassName('showAutoCalendar')||JotForm.isSourceTeam){var _selectors=[('#day_'+id),('#month_'+id),('#year_'+id),('#lite_mode_'+id)];$$(_selectors.join(',')).each(function(elem){if(!elem.onclick){elem.observe('focus',openCalendar);elem.observe('click',openCalendar);}});} $("year_"+id).observe("blur",function(){calendar.hide();});if($("lite_mode_"+id)){$("lite_mode_"+id).observe("blur",function(){calendar.hide();});}}}catch(e){JotForm.error(e);}},currentDateReadonly:function(){},calendarClose:function(calendar){var calendar_id=!calendar.isNewTheme?calendar.id:calendar.dateField.id[calendar.dateField.id.length-1];var found=calendar.dateField.id.match(/_[a-z0-9]+/);var selector=Array.isArray(found)?found[0]:'';var calendarFields=selector?$$('input[id*="'+selector+'"]'):[];var validations=calendar.dateField.className.replace(/.*validate\[(.*)\].*/,'$1').split(/\s*,\s*/);var incomplete=calendarFields.any(function(c){return c.value.empty()});if((validations.include("required")||validations.include("disallowPast"))&&incomplete){calendar.dateField.validateInput();} if(validations.include("required")&&!incomplete){JotForm.corrected($('id_'+calendar_id));} calendar.hide();},getDefaults:function(){document.querySelectorAll('.form-textbox, .form-dropdown, .form-textarea, .form-hidden-time').forEach(function(input){if(input.hinted||input.value===""){return;} JotForm.defaultValues[input.id]=input.value;});document.querySelectorAll('.form-radio, .form-checkbox').forEach(function(input){if(!input.checked){return;} JotForm.defaultValues[input.id]=input.value;});},handleOtherOptions:function(){document.querySelectorAll('.form-radio-other-input, .form-checkbox-other-input').forEach(function(inp){inp.placeholder=inp.getAttribute('data-otherhint')||'Other';});document.querySelectorAll('.form-radio, .form-checkbox').forEach(function(input){var id=input.id.replace(/input_(\d+)_\d+/gim,'$1');if(id.match('other_')){id=input.id.replace(/other_(\d+)/,'$1');} var other=document.getElementById('other_'+id);if(other){var other_input=document.getElementById('input_'+id);other_input.addEventListener('keyup',function(){other.value=other_input.value;var willInputBeChecked=other_input.value!=='';var isInputChecked=other.checked;if(!isInputChecked&&willInputBeChecked){other_input.click();} setTimeout(function(){other.checked=willInputBeChecked;});});other_input.addEventListener('click',function(){other_input.value=other_input.value===other_input.getAttribute('data-otherhint')?'':other_input.value;if(!other.checked){other.checked=true;}});other.addEventListener('click',function(){if(other.className.match(/\[.*required.*\]/)){other_input.value=other_input.value===other_input.getAttribute('data-otherhint')?'':other_input.value;}else{other_input.value=other_input.value!==''?other_input.value:other_input.getAttribute('data-otherhint');} if(other.checked){other_input.select();}else{if(other_input.hintClear){other_input.hintClear();}}});input.addEventListener('click',function(){if(input!==other&&input.checked&&!other.checked){other_input.value='';}});}});},shuffleOptions:function(id){var type=JotForm.calculationType(id);if(type==="radio"||type==="checkbox"){try{var options=$("id_"+id).select('.form-'+type+'-item');var length=$("id_"+id).down('.form-'+type+'-other-input')?options.length-1:options.length;for(var i=0;i12){erroredElement=monthElement;}else if((isNaN(day)||day<1)){erroredElement=dayElement;}else{switch(month){case 2:if((year%4==0)?day>29:day>28){erroredElement=dayElement;} break;case 4:case 6:case 9:case 11:if(day>30){erroredElement=dayElement;} break;default:if(day>31){erroredElement=dayElement;} break;}}} let isTargetActive=e&&e.target&&e.target===document.activeElement;if(window.FORM_MODE==='cardform'&&typeof document.activeElement!=='undefined'&&document.activeElement&&typeof document.activeElement.up==='function'&&monthElement){isTargetActive=monthElement.closest('.jfCard-question')===document.activeElement.closest('.jfCard-question');} if(!erroredElement&&hourElement&&minElement&&(hourElement.value!=""||minElement.value!="")&&!isTargetActive) {const hour=(hourElement.value.strip()=='')?-1:+hourElement.value;const min=(minElement.value.strip()=='')?-1:+minElement.value;if(isNaN(hour)||(ampmElement?(hour<0||hour>12):(hour<0||hour>23))){erroredElement=hourElement;}else if(isNaN(min)||min<0||min>59){erroredElement=minElement;}} const active=document.activeElement;let hasErrorInLiteModeEl=false;let limitError=false;if(!erroredElement){var dateInput=dateElement.querySelector('input[class*="validateLiteDate"]')||dateElement.querySelector('input[class*="validate"][class*="limitDate"]');if(dateInput&&dateInput.classList.contains('invalidDate')){erroredElement=dateInput;hasErrorInLiteModeEl=true;} if(dateInput&&dateInput.classList.contains('invalidLimits')){erroredElement=dateInput;limitError=true;}} if(erroredElement&&active!=yearElement&&active!=monthElement&&active!=dayElement){if(erroredElement===hourElement||erroredElement===minElement){erroredElement.errored=false;JotForm.errored(erroredElement,JotForm.texts.invalidTime);}else if(hasErrorInLiteModeEl){erroredElement.errored=false;const errorTxt=JotForm.texts.dateInvalid.replace("{format}",erroredElement.readAttribute("placeholder"));JotForm.errored(erroredElement,errorTxt);}else if(limitError){erroredElement.errored=false;JotForm.errored(erroredElement,JotForm.texts.dateLimited);}else{erroredElement.errored=false;const errorTxt=JotForm.texts.dateInvalidSeparate.replace('{element}',erroredElement.id.replace("_"+questionId,"")) JotForm.errored(erroredElement,errorTxt);} dateElement.classList.add('form-line-error');dateElement.classList.add('form-datetime-validation-error');return false;}else{JotForm.corrected(monthElement);JotForm.corrected(dayElement);JotForm.corrected(yearElement);if(hourElement&&minElement){JotForm.corrected(hourElement);JotForm.corrected(minElement);} dateElement.classList.remove('form-line-error');dateElement.classList.remove('form-datetime-validation-error');} return true;};if(hourElement&&minElement){hourElement.addEventListener('change',function(e){monthElement.dateTimeCheck(e)});minElement.addEventListener('change',function(e){monthElement.dateTimeCheck(e)});}});}catch(e){console.error(e);}},handleTimeChecks:function(){try{document.querySelectorAll('.form-line[data-type=control_time]').forEach(function(timeField){var questionId=timeField.id.split('_')[1];var hourElement=timeField.querySelector(`#input_${questionId}_hourSelect`);var minElement=timeField.querySelector(`#input_${questionId}_minuteSelect`);var ampmElement=timeField.querySelector(`#input_${questionId}_ampm`);var hourRangeElement=timeField.querySelector(`#input_${questionId}_hourSelectRange`);var minRangeElement=timeField.querySelector(`#input_${questionId}_minuteSelectRange`);var ampmRangeElement=timeField.querySelector(`#input_${questionId}_ampmRange`);hourElement.timeCheck=function(){var erroredElement=null;if(!erroredElement&&hourElement&&minElement&&(hourElement.value!=""||minElement.value!="")){var hour=(hourElement.value.strip()=='')?-1:+hourElement.value;var min=(minElement.value.strip()=='')?-1:+minElement.value;if(isNaN(hour)||(ampmElement?(hour<0||hour>12):(hour<0||hour>23))){erroredElement=hourElement;}else if(isNaN(min)||min<0||min>59){erroredElement=minElement;}} if(!erroredElement&&hourRangeElement&&minRangeElement&&(hourRangeElement.value!=""||minRangeElement.value!="")){var hour=(hourRangeElement.value.strip()=='')?-1:+hourRangeElement.value;var min=(minRangeElement.value.strip()=='')?-1:+minRangeElement.value;if(isNaN(hour)||(ampmRangeElement?(hour<0||hour>12):(hour<0||hour>23))){erroredElement=hourRangeElement;}else if(isNaN(min)||min<0||min>59){erroredElement=minRangeElement;}} if(erroredElement){JotForm.errored(erroredElement,JotForm.texts.invalidTime);timeField.classList.add('form-line-error');return false;}else{if(hourElement&&minElement){JotForm.corrected(hourElement);JotForm.corrected(minElement);} if(hourRangeElement&&minRangeElement){JotForm.corrected(hourRangeElement);JotForm.corrected(minRangeElement);}} return true;} if(hourElement&&minElement){hourElement.addEventListener('change',function(){hourElement.timeCheck()});minElement.addEventListener('change',function(){hourElement.timeCheck()});} if(hourRangeElement&&minRangeElement){hourRangeElement.addEventListener('change',function(){hourElement.timeCheck()});minRangeElement.addEventListener('change',function(){hourElement.timeCheck()});}});}catch(e){console.error(e);}},handleTextareaLimits:function(firstRun){if(typeof firstRun==='undefined'){firstRun=true;} $$('.form-textarea-limit-indicator span').each(function(el){var inpID=el.id.split('-')[0];if(!$(inpID)){return;} var minimum=el.readAttribute('data-minimum');var limit=el.readAttribute('data-limit');var input=$(inpID);var count;var countText=function(firstRun){if(input.value===""||input.hasClassName('form-custom-hint')){$(el.parentNode).removeClassName('form-textarea-limit-indicator-error');el.update("0/"+(minimum>-1?minimum:limit));return JotForm.corrected(el);} var contents;if(input.hasClassName("form-textarea")&&input.up('div').down('.nicEdit-main')){contents=input.value.stripTags(' ').replace(/ /g,' ');}else{contents=input.value;} if(input.up('div').down('.nicEdit-main')){var isStyled=input.up('div').down('.nicEdit-main').querySelector('style');if(isStyled)isStyled.remove();} var cleaned_contents=contents.replace(/(\<\w*)((\s\/\>)|(.*\<\/\w*\>))/gm,' ').replace(/ | /gi,' ');$(el.parentNode).removeClassName('form-textarea-limit-indicator-error');JotForm.corrected(el.up('.form-line').down('textarea'));var limitByType=function(type){var limitType=type=="min"?el.readAttribute('data-typeminimum'):el.readAttribute('type');if(limitType=='Words'){count=$A(cleaned_contents.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,'').split(/\s+/)).without("").length;}else if(limitType=='Letters'){count=cleaned_contents.length;} var limiting=false;if(((type=="min"&&countlimit))&&!(firstRun===true)){$(el.parentNode).addClassName('form-textarea-limit-indicator-error');var minMax=type=="min"?"Min":"";var lim=type=="min"?minimum:limit;var lettersWords=limitType==="Words"?"word":"character";var msg=JotForm.getValidMessage(JotForm.texts[lettersWords+minMax+"LimitError"],lim);JotForm.errored(el.up('.form-line').down('textarea'),msg);limiting=true;} el.update(count+"/"+((minimum&&count0){runMax=!limitByType("min")} if(limit&&limit>0&&runMax){limitByType("max");}};countText(firstRun);input.observe('change',countText);input.observe('focus',countText);input.observe('keyup',countText);if(input.hasClassName("form-textarea")&&input.up('div').down('.nicEdit-main')){var cEditable=input.up('div').down('.nicEdit-main');var runCount=function(){input.value=cEditable.innerHTML;countText();};cEditable.observe('keyup',runCount);cEditable.observe('blur',function(){setTimeout(runCount,0);});}});},handleAutoCompletes:function(){var editModeFirst=[];$H(JotForm.autoCompletes).each(function(pair){var el=$(pair.key);el.writeAttribute('autocomplete','off');var pairs=pair.value.split(/\r\n|\r|\n|\|/g);var values=$A(pairs);var lastValue;var selectCount=0;var liHeight=0;var list=document.createElement('div');list.className='form-autocomplete-list';Object.assign(list.style,{listStyle:'none',listStylePosition:'outside',position:'absolute',zIndex:'10000',display:'none'});var render=function(){var isCardForm=window.FORM_MODE==='cardform';if(isCardForm){var ebcr=el.getBoundingClientRect();var top=((ebcr.top+ebcr.height))-5+'px';var left=(ebcr.left)+'px';var width=(ebcr.width<1?100:ebcr.width)+'px';list.setStyle({top:top,left:left,width:width});list.show();}else{var dims=el.getDimensions();var offs=el.cumulativeOffset();list.setStyle({backgroundColor:'#f0f8ff',top:((dims.height+offs[1]))+'px',left:offs[0]+'px',width:((dims.width<1?100:dims.width)-2)+'px'});list.show();}};$(document.body).insert(list);list.close=function(){list.update();list.hide();selectCount=0;};el.observe('blur',function(){list.close();});el.observe('keyup',function(e){var word=el.value;if(lastValue==word){return;} lastValue=word;list.update();if(!word){list.close();return;} var fuzzy=el.readAttribute('data-fuzzySearch')=='Yes';var matches;var string=word.toLowerCase();matches=values.collect(function(v){if((fuzzy&&v.toLowerCase().include(string))||v.toLowerCase().indexOf(string)==0){return v;}}).compact();var maxMatches=el.readAttribute('data-maxMatches');if(maxMatches>0)matches=matches.slice(0,maxMatches);if(matches.length>0){matches.each(function(match){var li=document.createElement('li');li.className='form-autocomplete-list-item';var val=match;li.val=val;try{val=match.replace(new RegExp('('+word+')','gim'),'$1');} catch(e){JotForm.error(e);} li.insert(val);li.onmousedown=function(){el.value=JotForm.decodeHtmlEntities(match);el.triggerEvent('change');list.close();};list.insert(li);});render();liHeight=liHeight||$(list.firstChild).getHeight()+(parseInt($(list.firstChild).getStyle('padding'),10)||0)+(parseInt($(list.firstChild).getStyle('margin'),10)||0);list.setStyle({height:(liHeight*((matches.length>9)?10:matches.length)+4)+'px',overflow:'auto'});if(JotForm.isEditMode()&&editModeFirst.indexOf(el.id)===-1){list.hide();editModeFirst.push(el.id);} if(!e.isTrusted){list.close();}}else{list.close();}});el.observe('keydown',function(e){var selected;if(!list.visible()||!list.firstChild){return;} selected=list.select('.form-autocomplete-list-item-selected')[0];if(selected){selected.removeClassName('form-autocomplete-list-item-selected');} switch(e.keyCode){case Event.KEY_UP:if(selected&&selected.previousSibling){$(selected.previousSibling).addClassName('form-autocomplete-list-item-selected');}else{$(list.lastChild).addClassName('form-autocomplete-list-item-selected');} if(selectCount<=1){if(selected&&selected.previousSibling){$(selected.previousSibling).scrollIntoView(true);selectCount=0;}else{$(list.lastChild).scrollIntoView(false);selectCount=10;}}else{selectCount--;} break;case Event.KEY_DOWN:if(selected&&selected.nextSibling){$(selected.nextSibling).addClassName('form-autocomplete-list-item-selected');}else{$(list.firstChild).addClassName('form-autocomplete-list-item-selected');} if(selectCount>=9){if(selected&&selected.nextSibling){$(selected.nextSibling).scrollIntoView(false);selectCount=10;}else{$(list.firstChild).scrollIntoView(true);selectCount=0;}}else{selectCount++;} break;case Event.KEY_ESC:list.close();break;case Event.KEY_TAB:case Event.KEY_RETURN:if(selected){el.value=JotForm.decodeHtmlEntities(selected.val);lastValue=el.value;} list.close();if(e.keyCode==Event.KEY_RETURN){e.stop();} break;default:return;}});list.close();});},decodeHtmlEntities:function(str){var textarea=document.createElement('textarea');textarea.innerHTML=str;return textarea.value;},getFileExtension:function(filename){return(/[.]/.exec(filename))?(/[^.]+$/.exec(filename))[0]:undefined;},setAPIUrl:function(){if(JotForm.enterprise!=='undefined'&&JotForm.enterprise){this.APIUrl='https://'+JotForm.enterprise+'/API';return;} const isEUDomain=/(?:eu\.jotform)|(jotformeu\.com)/.test(window.location.host);const isHipaaDomain=/(?:hipaa\.jotform)/.test(window.location.host);switch(true){case isEUDomain:this.APIUrl='https://eu-api.jotform.com';break;case isHipaaDomain:this.APIUrl='https://hipaa-api.jotform.com';break;case /form.jotform/.test(window.location.host):case /fb.jotform/.test(window.location.host):case /form.myjotform/.test(window.location.host):this.APIUrl='https://api.jotform.com';break;case Boolean(window.JotFormAPIEndpoint):this.APIUrl=window.JotFormAPIEndpoint;break;case window.parent!==window:const form=document.querySelector('.jotform-form');const formAction=form.readAttribute('action');switch(true){case Boolean(JotForm.hipaa):this.APIUrl='https://hipaa-api.jotform.com';break;case /jotformeu\./.test(formAction):this.APIUrl='https://eu-api.jotform.com';break default:this.APIUrl='https://api.jotform.com';break;} break;case JotForm.isFullSource===true:switch(true){case /eu-submit.jotform/.test(this.url):this.APIUrl='https://eu-api.jotform.com';break;case /:\/\/submit.jotform/.test(this.url):this.APIUrl='https://api.jotform.com';break;default:this.APIUrl=this.url.replace(/\/$/,'')+'/API' break;} break;default:this.APIUrl='/API';}},setJotFormUserInfo:function(){const formID=document.querySelector('input[name="formID"]').value;JotForm.createXHRRequest(JotForm.APIUrl+'/formuser/'+formID+'/combinedinfo?master=1','GET',null,function(responseData){const user=responseData.content.credentials;if(!user){return;} if(user.accountType==='GUEST'||user.account_type==='GUEST'){return;} if(user.account_type&&user.account_type.name&&user.account_type.name==='GUEST'){return;} window.JFUser={name:user.name,email:user.email} if(window.parent.isBuilder){return;} JotForm.setNameAndEmailFieldsFromUserCredentials();},function(){},true);},setAsanaTaskID:function(){appendHiddenInput('asanaTaskID',getQuerystring('asanaTaskID'));},fillFieldElementIfEmpty:function(element,value){if(element&&!element.value){element.value=value;if(window.FORM_MODE==='cardform'){element.parentNode.classList.add('isFilled');}}},setNameAndEmailFieldsFromUserCredentials:function(){if(!window.JFUser||getQuerystring('preview')){return;} var firstName=document.querySelector("input[data-component='first']");var lastName=document.querySelector("input[data-component='last']");var middleName=document.querySelector("input[data-component='middle']");var email=document.querySelector("input[data-component='email']");var user=window.JFUser;setTimeout(function(){JotForm.runAllConditions();},1200);if(user.email){JotForm.fillFieldElementIfEmpty(email,user.email);} if(!user.name){return;} var names=user.name.split(' ');if(names.length>1){JotForm.fillFieldElementIfEmpty(lastName,names[names.length-1]);if(names.length>2){if(middleName){JotForm.fillFieldElementIfEmpty(middleName,user.name.substring(user.name.indexOf(" "),user.name.lastIndexOf(" ")));}else{JotForm.fillFieldElementIfEmpty(firstName,user.name.substring(0,user.name.lastIndexOf(" ")));}}} JotForm.fillFieldElementIfEmpty(firstName,names[0]);},getIsHTML:function(content){try{var divElem=document.createElement('div');divElem.innerHTML=content;return divElem.children.length>0;}catch(e){return false;}},prePopulations:function(fields,isPrefill){var _data=fields||document.get;var replaceUnicodeSpaces=function(str){return str.replace(/[\u00A0\u180E\u2000-\u200B\u202F\u205F\u3000\uFEFF]/,' ');} $H(_data).each(function(pair){if(typeof pair.value==='undefined'){return;} if(pair.key.match(/[\s\S]+;/))pair.key=pair.key.replace(/[\s\S]+;/,'');var stricterMatch=pair.key.length<3?true:false;var strict_n='[name$="_'+pair.key+'"]';var n=stricterMatch?strict_n:'[name*="_'+pair.key+'"]';var checkbox_n='[name*="_'+pair.key+'"]';var radio_n='[name$="_'+pair.key+'"]';var input;if(window.FORM_MODE!=='cardform'){input=$$('.form-star-rating'+strict_n)[0];if(input){input.setRating(parseInt(pair.value));return;}} if(typeof pair.value==='object'){pair.value=pair.value[0]||"";} input=$$('.form-slider'+n)[0];if(input){input.setSliderValue(parseInt(pair.value));return;} if(pair.key=="coupon-input"&&$('coupon-input')){$('coupon-input').setValue(pair.value);$('coupon-button').triggerEvent('click');$(window).scrollTo(0,0);return;} input=$$('.form-textbox%s, .form-dropdown%s, .form-textarea%s, .form-hidden%s'.replace(/\%s/gim,strict_n))[0];if(!input){input=$$('.form-textbox%s, .form-dropdown%s, .form-textarea%s, .form-hidden%s'.replace(/\%s/gim,n)).filter(function(x){return x.value==='';})[0];if(input){var formIDField=$$('input[name="formID"]')[0];var questionType=input.closest('li')&&input.closest('li').getAttribute('data-type');if(questionType&&!['control_rating','control_phone','control_time'].includes(questionType)){JotForm.errorCatcherLog({message:{inputName:input.name,matchedParam:pair.key,questionType,formID:formIDField.value}},'PREPOPULATE_SINGLE_INPUT_NON_STRICT_MATCH');}}} if(!input&&pair.key.indexOf("[")>0){var name=pair.key.substr(0,pair.key.lastIndexOf('['));var strictName=name.includes(']')?name:pair.key.replace(/(\w+)\[\d+\]/g,'_$1\\[');var strictRadioName=pair.key.replace(/(\w+)\[\d+\]/g,'_$1');if(name.length>0&&$$("select[name*="+name+"], input[name*="+name+"]").length>0){var index=pair.key.substr(pair.key.lastIndexOf('[')+1).replace("]","");if(index&&Number(index)>-1&&$$("select[name*="+name+"], input[name*="+name+"]").length>index){var type=$$("select[name*="+name+"]").length>0?"select":$$("input[name*="+name+"]")[index].type;switch(type){case"select":if($$("select[name*="+name+"]")[index]){$$("select[name*="+name+"]")[index].value=pair.value.replace(/\+/g,' ');} break;case"text":case"tel":case"number":input=$$("input[name*="+strictName+"]")[index];if(!input){input=$$("input[name*="+name+"]")[index];if(!input){break;} var formIDField=$$('input[name="formID"]')[0];var questionType=input.closest('li')&&input.closest('li').getAttribute('data-type');JotForm.errorCatcherLog({message:{inputName:input.name,matchedParam:name,index,questionType,formID:formIDField.value}},'PREPOPULATE_MULTI_INPUT_NON_STRICT_MATCH');} input.value=pair.value.replace(/\+/g,' ');input.triggerEvent('keyup');break;case"radio":case"checkbox":try{if((pair.value=="true"||pair.value==1)&&$$("input[name*="+name+"]")[index]&&!($$("input[name*="+name+"]").first().up('.form-line').readAttribute('data-type')==='control_matrix'&&name.indexOf('[')<0)){let checkboxRadioInput=$$("input[name$="+strictRadioName+"]")[index]||$$("input[name*="+strictName+"]")[index];if(!checkboxRadioInput){checkboxRadioInput=$$("input[name*="+name+"]")[index];if(!checkboxRadioInput){break;} var formIDField=$$('input[name="formID"]')[0];var questionType=checkboxRadioInput.closest('li').getAttribute('data-type');JotForm.errorCatcherLog({message:{inputName:checkboxRadioInput.name,matchedParam:name,index,questionType,formID:formIDField.value}},'PREPOPULATE_MULTI_INPUT_NON_STRICT_MATCH');} checkboxRadioInput.click();}}catch(e){console.log(e);} break;}}}} if(input&&input.readAttribute('data-type')=='input-grading'){var grades=pair.value.split(',');var stub=input.id.substr(0,input.id.lastIndexOf('_')+1);for(var i=0;i-1){input.value=pair.value.replace(/\+/g,' ');JotForm.defaultValues[input.id]=input.value;}else{try{var valuesArray=input.up('.form-line').readAttribute('data-type')==="control_checkbox"?pair.value.split(','):[pair.value];for(var i=0;i0){return Object.values(FormTranslation.dictionary).map(function(language){return language[inp.value];}).filter(function(translation){return translation;}).any(function(translatedValue){return valuesArray[i]===translatedValue;});} return valuesArray[i]===inp.value;});if(!normalInputWithValue&&RegExp(pair.key+'\\[other\\]$').test(input.name)){input.value=valuesArray[i];if(input.value===''){continue;} valuesArray[i]="other";var other=$('other_'+inputId);other.value=input.value;}} pair.value=valuesArray.join(",");}catch(e){console.error(e);}}});}else if(input&&input.hasClassName("form-textarea")&&input.up('div').down('.nicEdit-main')){var isHtmlValue=JotForm.getIsHTML(pair.value);var val=pair.value.replace(/\+/g,' ');if(isHtmlValue){if(window.DomPurify){val=window.DomPurify.sanitize(val);} input.up('div').down('.nicEdit-main').update(val);}else{input.up('div').down('.nicEdit-main').update(val.replace(//g,'>'));}}else if(input&&input.hasClassName("form-textarea")&&input.up('div').down('.jfTextarea-editor')){var isHtmlValue=JotForm.getIsHTML(pair.value);if(isHtmlValue&&window.DomPurify){pair.value=window.DomPurify.sanitize(pair.value);} input.up('div').down('.jfTextarea-editor').update(pair.value);}else if(input&&input.hasClassName("form-dropdown")){var isMultiple=input.readAttribute('multiple')||input.multiple;var val=pair.value.replace(/\{\+\}/g,'{plusSign}').replace(/\+/g,' ').replace(/\{plusSign\}/g,'+');var arr=isMultiple?val.split(","):[val];var options=input.select('option');input.value=arr;$A(options).each(function(option){option.writeAttribute("selected",arr.include(option.value)?"selected":false);});if(window.FORM_MODE==='cardform'&&window.CardForm){window.CardForm.setDropdownInitialValues();}}else if(input){input.value=pair.value.replace(/\{\+\}/g,'{plusSign}').replace(/\+/g,' ').replace(/\{plusSign\}/g,'+');var formLine=input.up('.form-line');var dontStripPlusIn=["control_textarea"];if(isPrefill||document.referrer.match(/jotform/)||input.getAttribute('type')==='email'||(formLine&&(dontStripPlusIn.indexOf(formLine.readAttribute('data-type'))>-1))){input.value=pair.value;} JotForm.defaultValues[input.id]=input.value;try{if(formLine&&(formLine.readAttribute('data-type')==="control_datetime"||formLine.readAttribute('data-type')==="control_inline")){var dateField=formLine.readAttribute('data-type')==='control_datetime'?formLine:input.up('[data-type=datebox]');if(dateField){var year=dateField.down('input[id*="year_"]').value;var month=dateField.down('input[id*="month_"]').value;var day=dateField.down('input[id*="day_"]').value;if(year!==""&&month!==""&&day!==""){JotForm.formatDate({date:new Date(year,month-1,day),dateField:dateField});var dateInput=dateField.down('input[id*="input_"]');var liteModeInput=dateField.down('input[id*="lite_mode_"]');if(dateInput&&dateInput.getAttribute('id').indexOf("timeInput")===-1){var ISODate=year+'-'+month+'-'+day;JotForm.defaultValues[dateInput.id]=ISODate;dateInput.value=ISODate;} if(liteModeInput){JotForm.defaultValues[liteModeInput.id]=liteModeInput.value;}}}}}catch(e){console.log(e)}} $$('.form-textbox%s, .form-textarea%s, .form-hidden%s'.replace(/\%s/gim,n)).each(function(input){input.triggerEvent('keyup');});$$('.form-dropdown%s'.replace(/\%s/gim,n)).each(function(input){input.triggerEvent('change');});JotForm.onTranslationsFetch(function(){var checkboxNaming='(_'+pair.key+'([(.*?)])?)$';var checkboxNamingRegex=new RegExp(checkboxNaming.replace(/\[/g,'\\[').replace(/\]/g,'\\]'));var checkboxParam='.form-radio%s'.replace(/\%s/gim,radio_n)+', '+'.form-checkbox%s'.replace(/\%s/gim,checkbox_n) $$(checkboxParam).each(function(input){input=$(input.id);if(isPrefill&&input.type==='checkbox'&&!checkboxNamingRegex.test(input.name))return;var disabled=input.disabled?!!(input.enable()):false;var value=pair.value.replace(/\{\+\}/g,'{plusSign}').replace(/\+/g,' ').replace(/\{plusSign\}/g,'+');var allTranslations=[];if(typeof FormTranslation!=='undefined'){Object.values(FormTranslation.dictionary).forEach(function processTranslations(e){if(e[input.value]){allTranslations.push(e[input.value].replace(/\{\+\}/g,'{plusSign}').replace(/\+/g,' ').replace(/\{plusSign\}/g,'+'));}});} if(allTranslations.length===0){allTranslations.push(input.value.replace(/\{\+\}/g,'{plusSign}').replace(/\+/g,' ').replace(/\{plusSign\}/g,'+'));} var valueSplittedByComma=value.replace(/([^\\]),/g,'$1\u000B').split('\u000B');allTranslations.each(function(inputValue){if(inputValue.indexOf(',')&&!(value.includes('
'))){inputValue=inputValue.replace(/,/g,"\\,");} if(value==inputValue||$A(valueSplittedByComma).include(inputValue)||$A(value.split('
')).include(inputValue)||valueSplittedByComma.includes(replaceUnicodeSpaces(inputValue))){if(!input.checked){if(input.disabled){input.enable();input.click();input.disable();}else{input.click();} JotForm.defaultValues[input.id]=inputValue;}}else if($A(pair.value.split(',')).include('other')){if((input.name.indexOf('[other]')>-1)||(input.id&&input.id.indexOf('other_')>-1)){input.click();}} if(disabled)setTimeout(function(){input.disable();});});});});if(input&&input.hasClassName('form-textarea')&&input.hasClassName('form-custom-hint')){let hasContentForTextArea=input.hasContent;const richTextEditorContent=input.up('div').down('.nicEdit-main')&&input.up('div').down('.nicEdit-main').innerHTML;if(richTextEditorContent){hasContentForTextArea=true;} if(hasContentForTextArea){input.removeClassName('form-custom-hint');}}});setTimeout(function(){if(!(document.getElementById('draftID'))){JotForm.runAllConditions();}},1500);if(window.FORM_MODE==='cardform'){var cards=window.CardForm.cards;window.CardForm.checkCardsIfFilled(cards);} var hasQueryParams=window.location.search!=='';var canonical=$$('link[rel="canonical"]')[0];if(hasQueryParams&&canonical&&window.location.href!==canonical.href){canonical.href=window.location.href;}},resetForm:function(frm){var hiddens=frm.querySelectorAll('input[type="hidden"], #input_language');hiddens.forEach(function(h){h.__defaultValue=h.value;});frm.reset();hiddens.forEach(function(h){h.value=h.__defaultValue;});return frm;},editMode:function(data,noreset,skipField,skipCardIndex,cb,errorCb){if(cb===undefined){cb=function(){};} if(errorCb===undefined){errorCb=function(){};} if(this.isNewSaveAndContinueLaterActive&&this.isEditMode()){document.querySelectorAll('.js-new-sacl-button').forEach(function(saveBtn){saveBtn.style.display='none';});} let preLink="";if(!JotForm.debug){preLink="https://cdn.jotfor.ms/";} if(document.get.offline_forms=='true'&&document.get.jotformNext==1){preLink=window.location.pathname.replace('/index.html','');} const self=this;if(!window.editModeFunction){this.loadScript(preLink+'/js/form.edit.mode.js?v_'+(new Date()).getTime(),function(){self.editMode=editModeFunction;if(JotForm.sessionID&&data){data.fromSession=true;} self.editMode(data,noreset,skipField,skipCardIndex,errorCb);cb()});this.loadScript(preLink+'/js/stock.edit.js?v_'+(new Date()).getTime())}else{self.editMode(data,noreset,skipField,skipCardIndex,cb);}},isEditMode:function(){if(window.FORM_MODE==='cardform'&&window.CardForm&&window.CardForm.layoutParams){return CardForm.layoutParams.isEditMode;} return window.location.pathname.match(/^\/edit\//)||window.location.pathname.match(/^\/\/edit/)||window.location.href.match(/mode=inlineEdit/)||window.location.href.match(/mode=submissionToPDF/)||window.JotForm.offlineEditMode===true;},setConditions:function(conditions){conditions.reverse();JotForm.conditions=conditions;conditions.forEach(function(condition){condition.action=[].concat(condition.action);});},setCalculations:function(calculations){if(JotForm.calculations.length===0){JotForm.calculations=calculations;}else{Object.values(calculations).forEach(function(calculation){JotForm.calculations.push(calculation);});}},prepareCalculationsOnTheFly:function(questions){JotForm.errorCatcherLog({},'JOT3_IS_USED_PREPARE_CALCULATIONS_ON_THE_FLY_FUNC');var questions_by_name=[];var questions_by_type=[];function transpose(a){return a[0].map(function(val,c){return a.map(function(r){return r[c];});});} if(questions.length>0){if(JotForm.calculations.length<=0){JotForm.calculations=[];} questions.each(function(question){if(question){questions_by_name[question.name]=question.qid;questions_by_type[question.name]=question.type;}});questions.each(function(question){if(question){var values=[];switch(question.type){case'control_textbox':question.text!==''?values.push(question.text):void(0);question.subLabel!==''?values.push(question.subLabel):void(0);question.description!==''?values.push(question.description):void(0);break;case'control_image':question.labelText!==''?values.push(question.labelText):void(0);break;case'control_inline':question.template!==''?values.push(question.template):void(0);break;default:question.text!==''?values.push(question.text):void(0);question.description!==''?values.push(question.description):void(0);} for(var value;value=values.shift();){var regex=/\{([^\}]*)\}/gim;for(var questions=[];result=regex.exec(value);questions.push(result));if(questions.length>0){questions=transpose(questions);questions[1].forEach(function(question_name){var qname,qtype;var seperator=question_name.indexOf(':')>-1?':':'[';qname=questions_by_name[question_name.split(seperator)[0]];qtype=questions_by_type[question_name.split(seperator)[0]];var multilineFieldRegex=/\[(.*?)\]/gi;var multilineFieldResult=multilineFieldRegex.exec(question_name);var multilineFieldEquation=multilineFieldResult?qname+'|'+multilineFieldResult[1]:'';if(qtype==='control_inline'){var inlineFieldRegex=/(\:)(.*)/gi;var inlineFieldResult=inlineFieldRegex.exec(question_name);if(inlineFieldResult){var subfield=inlineFieldResult[2];var subfieldSplit=subfield.split('-');var fieldId=Number(subfieldSplit[0])?subfieldSplit[0]:subfieldSplit[1];multilineFieldEquation=qname+'|'+fieldId;}} JotForm.calculations.push({decimalPlaces:"2",defaultValue:"",equation:"{"+(multilineFieldEquation||qname)+"}",ignoreHiddenFields:"",insertAsText:"1",isLabel:["control_text","control_inline"].indexOf(question.type)>-1?"":"1",newCalculationType:"1",operands:(multilineFieldEquation||qname),readOnly:"",replaceText:question_name,resultField:question.qid,showBeforeInput:"",tagReplacement:"1",useCommasForDecimals:"",allZeroCopy:""});});}}}});}},runConditionForId:function(id){Object.values(JotForm.fieldConditions).forEach(function(value){const conds=value.conditions;conds.forEach(function(cond){cond.terms.forEach(function(term){var inputTermField="input_"+term.field;if(term.field===id||id===inputTermField){JotForm.checkCondition(cond);}});});});},otherConditionTrue:function(field,visibility){visibility=visibility.replace(/multiple/,"");var otherConditionTrue=false;Object.values(JotForm.fieldConditions).forEach(function(value){var conds=value.conditions;conds.forEach(function(cond){cond.action.forEach(function(action){if(action.fields){action.fields.forEach(function(multiField){if(multiField===field&&action.visibility&&action.visibility.toLowerCase().replace(/multiple/,"")===visibility&&action.hasOwnProperty('currentlyTrue')&&action.currentlyTrue){otherConditionTrue=true;return;}});} if(action.field===field&&action.visibility&&action.visibility.toLowerCase()===visibility&&action.hasOwnProperty('currentlyTrue')&&action.currentlyTrue){otherConditionTrue=true;}});});});return otherConditionTrue;},showField:function(field,isConditionActive){if(JotForm.otherConditionTrue(field,'hide'))return;isConditionActive=typeof isConditionActive=='undefined'?true:isConditionActive var element=null;var idField=$('id_'+field);var cidField=$('cid_'+field);var sectionField=$('section_'+field);if(sectionField&&cidField){element=sectionField;}else if(cidField&&!idField){element=cidField;}else{element=idField;} if(!element){var productField=$$('input[name*="q'+field+'"][type="hidden"]');if(productField.length>0){productField[0].setAttribute('selected',true);} return element;} if(element.getAttribute('data-type')==='control_button'&&element.getElementsBySelector('button').length>1){element.getElementsBySelector('button').each(function(item){if(JotForm.useJotformSign==='Yes'&&item.hasClassName('useJotformSign-button')){item.show();}else if((!JotForm.useJotformSign||JotForm.useJotformSign!=='Yes')&&item.hasClassName('submit-button')){item.show();} if(item.hasClassName('form-submit-reset')||item.hasClassName('form-submit-print')){item.show();} if(item.hasClassName('form-pagebreak-back')){item.show();} if(element.querySelector('.form-submit-clear-wrapper')){element.querySelector('.form-submit-clear-wrapper').show();}});}else{element.show();} var wasHidden=element.hasClassName('form-field-hidden')||element.hasClassName('always-hidden');element.removeClassName('form-field-hidden');if(isConditionActive||window.FORM_MODE==='cardform'){if(window.FORM_MODE=='cardform'&&element.hasClassName('always-hidden')){element.setAttribute('always-hidden-removed-by-cardform',true)} element.removeClassName('always-hidden');} if(!(element.hasClassName("form-section")||element.hasClassName("form-section-closed"))&&element.down(".always-hidden")){element.down(".always-hidden").removeClassName('always-hidden');} if(JotForm.paymentFields.indexOf(element.getAttribute('data-type'))>-1&&$('hiddenPaymentField')){$('hiddenPaymentField').remove();} if(sectionField){if(element.hasClassName('form-section-closed')){if(element.select('.form-collapse-table')[0].hasClassName('form-collapse-hidden')){element.removeClassName('form-section-closed');element.addClassName('form-section');element.setStyle({height:"auto",overflow:"visible"});}else{element.setStyle({overflow:"hidden"});}}else{element.setStyle({height:"auto",overflow:"visible"});}} if(JotForm.getInputType(field)==='html'){if($('text_'+field).innerHTML.match(/google.*maps/gi)){$('text_'+field).innerHTML=$('text_'+field).innerHTML;} JotForm.runAllCalculationByID(field);} var elemShown=element.show();if(JotForm.getInputType(field)==='widget'){JotForm.showWidget(field);} if(JotForm.getInputType(field)==='signature'&&wasHidden){JotForm.showAndResizeESignature(field);} if(JotForm.getInputType(field)==='collapse'){if(sectionField&&!element.hasClassName('form-section-closed')){element.select('li.form-line').each(function(node){var id=node.id.split('_')[1];if(JotForm.getInputType(id)==='widget'){JotForm.showWidget(id);}else if(JotForm.getInputType(id)==='signature'){JotForm.showAndResizeESignature(id);}});}} if(window.FORM_MODE=='cardform'&&wasHidden&&($('id_'+field)&&$('id_'+field).readAttribute('data-type')=='control_matrix')){JotForm.setMatrixLayout(field,false);} if(JotForm.donationField&&element.down('[data-component="paymentDonation"][data-custom-amount-field]')){JotForm.updateDonationAmount();} if(element.getAttribute('data-type')==="control_paypalSPB"&&$$('[data-paypal-button="Yes"]')[0]){var paypalButton=$$('.paypal-buttons.paypal-buttons-context-iframe')[0];if(paypalButton){var paypalButtonContainer=JotForm.getContainer(paypalButton);if(paypalButtonContainer){paypalButtonContainer.setAttribute('paypal-button-status','show');}}} return elemShown;},collectStylesheet:function(){const styles=document.querySelectorAll('style, link');const styleTags=[];styles.forEach(function(style){if(style.type==='text/css'||style.rel==='stylesheet'){styleTags.push(style.outerHTML);}});return styleTags;},handleWidgetStyles:function(){const team=getQuerystring('team') if(JotForm.newDefaultTheme){window.newDefaultTheme='v2';} if(team==='marvel'||team==='muse'){const styleTags=JotForm.collectStylesheet();document.querySelectorAll('[data-type=control_widget] iframe').forEach(function(frame){frame.addEventListener("load",function(){frame.contentWindow.postMessage({cmd:'injectStyle',styleTags:styleTags},'*');});});}},showWidget:function(id,postTranslate){var referrer=document.getElementById("customFieldFrame_"+id)?document.getElementById("customFieldFrame_"+id).src:false;if(referrer){var frame=(navigator.userAgent.indexOf("Firefox")!=-1&&typeof getIframeWindow!=='undefined')?getIframeWindow(window.frames["customFieldFrame_"+id]):window.frames["customFieldFrame_"+id];var isFrameXDready=(!$("customFieldFrame_"+id).hasClassName('frame-xd-ready')&&!$("customFieldFrame_"+id).retrieve('frame-xd-ready'))?false:true;if(frame&&isFrameXDready){XD.postMessage(JSON.stringify({type:"show",qid:id}),referrer,frame);if(typeof window.JCFServerCommon!=='undefined'){if(JotForm.isVisible(JotForm.getSection($("id_"+id)))&&JotForm.isVisible($("id_"+id))){if(window.JCFServerCommon.frames.hasOwnProperty(id)){window.JCFServerCommon.frames[id].sendReadyMessage(id);}}} if(postTranslate&&JotForm.getWidgetType(id)==='configurableList'&&typeof FormTranslation!=='undefined'){var message={type:"translate",id:id,dictionary:FormTranslation.dictionary,to:FormTranslation.to,success:true};XD.postMessage(JSON.stringify(message),referrer,frame);}}}},reloadWidget:function(id){var referrer=document.getElementById("customFieldFrame_"+id)?document.getElementById("customFieldFrame_"+id).src:false;if(referrer){var frame=(navigator.userAgent.indexOf("Firefox")!=-1&&typeof getIframeWindow!=='undefined')?getIframeWindow(window.frames["customFieldFrame_"+id]):window.frames["customFieldFrame_"+id];var isFrameXDready=(!$("customFieldFrame_"+id).hasClassName('frame-xd-ready')&&!$("customFieldFrame_"+id).retrieve('frame-xd-ready'))?false:true;if(frame&&isFrameXDready){XD.postMessage(JSON.stringify({type:"reload",qid:id}),referrer,frame);}}},disableWidget:function(id){var referrer=document.getElementById("customFieldFrame_"+id)?document.getElementById("customFieldFrame_"+id).src:false;if(referrer){var frame=(navigator.userAgent.indexOf("Firefox")!=-1&&typeof getIframeWindow!=='undefined')?getIframeWindow(window.frames["customFieldFrame_"+id]):window.frames["customFieldFrame_"+id];var isFrameXDready=(!$("customFieldFrame_"+id).hasClassName('frame-xd-ready')&&!$("customFieldFrame_"+id).retrieve('frame-xd-ready'))?false:true;if(frame&&isFrameXDready){XD.postMessage(JSON.stringify({type:"disable",qid:id}),referrer,frame);}}},shouldWidgetSkipSubmit:function(){if(JotForm.isEncrypted||JotForm.disableSubmitButton){return true;} var selfSubmittingPayments=["stripe","braintree","square","eway","bluepay","moneris","paypalcomplete","mollie"];if(JotForm.payment==='sensepass'&&JotForm.isDirectFlow==='Yes'){selfSubmittingPayments.push('sensepass');} if(window.paymentType=='subscription'&&JotForm.payment==='paypalcomplete'){selfSubmittingPayments.splice(selfSubmittingPayments.indexOf('paypalcomplete'),1);} if(!JotForm.isEditMode()&&JotForm.isPaymentSelected()&&selfSubmittingPayments.indexOf(JotForm.payment)>-1){return JotForm.paymentTotal>0||(JotForm.payment=='stripe'&&window.paymentType=='subscription');} return false;},showAndResizeESignature:function(id){var element=document.querySelector('#id_'+id);if(element&&JotForm.isVisible(element)&&element.querySelectorAll('.pad').length>0){const sigresizeEvent=document.createEvent('HTMLEvents');sigresizeEvent.initEvent("dataavailable",true,true);sigresizeEvent.eventName="on:sigresize";sigresizeEvent.memo=sigresizeEvent.memo||{};document.querySelector('.pad').dispatchEvent(sigresizeEvent);}},hideField:function(field,multiple,dontClear){if(JotForm.otherConditionTrue(field,'show'))return;var idPrefix='id_';if($('cid_'+field)&&!$('id_'+field)){idPrefix='cid_';} if($('cid_'+field)&&$('section_'+field)){idPrefix='section_';} var element=$(idPrefix+field);if(element){element.addClassName('form-field-hidden');var isProductListInEditMode=JotForm.isEditMode()&&JotForm.clearFieldOnHide==='dontClear'&&element.getAttribute('data-type')==='control_payment';if(JotForm.paymentFields.indexOf(element.getAttribute('data-type'))>-1&&!$('hiddenPaymentField')&&!isProductListInEditMode){appendHiddenInput('hiddenPaymentField',1,{id:'hiddenPaymentField'});} if(element.getAttribute('data-type')==="control_paypalSPB"&&$$('[data-paypal-button="Yes"]')[0]){var paypalButton=$$('.paypal-buttons.paypal-buttons-context-iframe')[0];if(paypalButton){var paypalButtonContainer=JotForm.getContainer(paypalButton);if(paypalButtonContainer){paypalButtonContainer.setAttribute('paypal-button-status','hide');}}} if(JotForm.clearFieldOnHide=="enable"&&!dontClear&&!JotForm.ignoreInsertionCondition){try{JotForm.clearField(field);}catch(e){console.log(e);}} if(element.style.setProperty){element.style.setProperty('display','none','important');}else{element.hide();} if(element.getAttribute('data-type')&&element.getAttribute('data-type')=='control_button'&&element.getElementsBySelector('button').length>1){var submitButtonsElements=element.getElementsBySelector('button');var saclButton=submitButtonsElements.find(function(bt){return bt.hasClassName('form-sacl-button')});var previewPDFButton=submitButtonsElements.find(function(bt){return bt.hasClassName('form-submit-preview')});if(saclButton||previewPDFButton){element.show();submitButtonsElements.each(function(item){if(item!=saclButton&&item!=previewPDFButton){item.addClassName('form-field-hidden');if(item.style.setProperty){item.style.setProperty('display','none','important');}else{item.hide();} if(element.querySelector('.form-submit-clear-wrapper')){element.querySelector('.form-submit-clear-wrapper').hide();}}});}} if(JotForm.donationField&&element.down('[data-component="paymentDonation"][data-custom-amount-field]')){JotForm.updateDonationAmount(0);} JotForm.corrected(element);if(JotForm.clearFieldOnHide=='enable'&&JotForm.getInputType(field)==="signature"){JotForm.handleSignatureState(field);} return element;} var productField=$$('input[name*="q'+field+'"][type="hidden"]');if(productField.length>0){productField[0].setAttribute('selected',false);}},handleSignatureState:function(field){var signatureLine=jQuery('#signature_pad_'+field+" .signature-line");var signatureInput=jQuery('#signature_pad_'+field+" #input_"+field);var pad=jQuery('#signature_pad_'+field+" .pad");if(pad&&signatureInput&&signatureInput.val()!==""){pad.jSignature("clear");signatureLine.addClass('signature-placeholder');signatureInput.val("");JotForm.triggerWidgetCondition(field);}},clearField:function(field,subfield,dontTrigger){var type=JotForm.calculationType(field);if(!type)return;var defaultValue="input_"+field in JotForm.defaultValues?JotForm.defaultValues["input_"+field]:"";if(field.indexOf('|')>-1){var fieldSplit=field.split('|');field=fieldSplit[0];if(!subfield){subfield=fieldSplit[1];}} if(type=="file"){$("id_"+field).select('ul').each(function(element){if(element.getElementsByTagName('li').length>0){element.querySelectorAll('span.qq-upload-delete').forEach(function(item){item.click();});}});} if(type=="collapse"){$("section_"+field).select(".form-line").each(function(el){var id=el.id.replace("id_","");JotForm.clearField(id);});return;} if(type==="matrix"&&subfield&&$(subfield)){$(subfield).value="";if(!dontTrigger&&$(subfield).triggerEvent){$(subfield).triggerEvent('keyup');}}else if(type==="matrix"){$('id_'+field).select('input[type="text"], input[type="tel"], input[type="number"]').each(function(el){el.value=(el.id in JotForm.defaultValues)?JotForm.defaultValues[el.id]:"";});$("id_"+field).select('input[type="radio"], input[type="checkbox"]').each(function(input){if(!JotForm.defaultValues[input.id]){input.checked=false;}});$('id_'+field).select('select').each(function(el){if(el.id in JotForm.defaultValues){el.value=JotForm.defaultValues[el.id];}else{el.selectedIndex=0;}});if($('id_'+field).select('input, select').length===0)return;var firstField=$('id_'+field).select('input, select').first();if(firstField&&firstField.triggerEvent){if(firstField.nodeName.toLowerCase()==='input'){if(firstField.type==="checkbox"||firstField.type==="radio"){$('id_'+field).triggerEvent('change');}else{firstField.triggerEvent('keyup');}}else{firstField.triggerEvent('change');}}}else if(["address","combined","datetime","time"].include(type)){if($('id_'+field).readAttribute('data-type')==='control_mixed'){$('id_'+field).select('.jfField').each(function(el){if(el.readAttribute('data-type')==='mixed-dropdown'){var dropdownID=el.querySelector('select').id;if(el.querySelector('input')){el.querySelector('input').value=(dropdownID in JotForm.defaultValues)?JotForm.defaultValues[dropdownID]:"";}}})}else{$('id_'+field).select('input').each(function(el){el.value=(el.id in JotForm.defaultValues)?JotForm.defaultValues[el.id]:"";});} $('id_'+field).select('select').each(function(el){if(el.id in JotForm.defaultValues){el.value=JotForm.defaultValues[el.id];}else{el.selectedIndex=0;}});var triggerMe=$('input_'+field)?$('input_'+field):$('id_'+field).select('input').first();if(triggerMe&&triggerMe.triggerEvent){triggerMe.triggerEvent('keyup');} if($('input_'+field+'_full')&&$('input_'+field+'_full').readAttribute("data-masked")=="true"){JotForm.setQuestionMasking("#input_"+field+"_full","textMasking",$('input_'+field+'_full').readAttribute("maskValue"));}}else if(["braintree","stripe","paypalpro","authnet"].include(type)){$('id_'+field).select('input[type="text"], .form-address-country').each(function(el){el.value=(el.id in JotForm.defaultValues)?JotForm.defaultValues[el.id]:"";});}else if(type==="html"){try{$('id_'+field).select(".replaceTag").each(function(span){var def=span.readAttribute("default");span.update(def);});}catch(e){console.log(e);}}else if(type==="inline"){var selector='input, select';if(subfield){var TIMESTAMP_OF_2019=1546300000000;var isNewIDType=Number(subfield)-1){if(el.id in JotForm.defaultValues){el.checked=true;}else{el.checked=false;}}else{if(el.parentNode.dataset.type==='signaturebox'){var signatureImage=el.parentNode.querySelector('.FITB-sign-image');if(signatureImage)signatureImage.setAttribute('src','');} var newValue=(el.id in JotForm.defaultValues)?JotForm.defaultValues[el.id]:"";if(el.value!==newValue){el.value=newValue;el.triggerEvent("change");}}});}else if(type=="textarea"){$('input_'+field).value=defaultValue;if($('input_'+field).triggerEvent&&!dontTrigger)$('input_'+field).triggerEvent("keyup");if($('input_'+field).showCustomPlaceHolder){$('input_'+field).showCustomPlaceHolder();} var richArea=$("id_"+field).down('.nicEdit-main');if(richArea){richArea.innerHTML=defaultValue;if($('input_'+field).hasClassName('custom-hint-group')&&!$('input_'+field).hasContent){richArea.setStyle({'color':'#babbc0'});}}}else{if(type=="checkbox"||type=="radio"){var dataChanged=false;$("id_"+field).select('input[type="radio"], input[type="checkbox"]').each(function(input){var currentValue=input.checked;if(input.id in JotForm.defaultValues){input.checked=true;}else{input.checked=false;} if(!dataChanged&¤tValue!==input.checked)dataChanged=true;});if($('id_'+field).triggerEvent&&!dontTrigger&&dataChanged)$('id_'+field).triggerEvent('change');}else if(type=="select"){if($('input_'+field)){$('input_'+field).value=defaultValue;if($('input_'+field).triggerEvent&&!dontTrigger)$('input_'+field).triggerEvent('change');}else{$("id_"+field).select('select').each(function(element){if(element.readAttribute('data-component')!=='mixed-dropdown'){element.value='';if(element.triggerEvent&&!dontTrigger)element.triggerEvent('change');}});}}else if($('input_'+field)){$('input_'+field).value=defaultValue;if($('input_'+field).triggerEvent&&!dontTrigger){if(type=="widget"){var widgetEl=$('input_'+field);widgetEl.fire('widget:clear',{qid:parseInt(widgetEl.id.split('_')[1])});widgetEl.triggerEvent('change');}else{$('input_'+field).triggerEvent('keyup');}} if(defaultValue===""&&$('input_'+field).hintClear){$('input_'+field).hintClear();} if($('input_'+field).readAttribute("data-masked")=="true"){JotForm.setQuestionMasking("#input_"+field,"textMasking",$('input_'+field).readAttribute("maskValue"));} if($('input_'+field).hasClassName("form-star-rating")&&$('input_'+field).setRating){$('input_'+field).setRating(0);} if(type=="email"){var parent=$('input_'+field).parentElement;if(window.FORM_MODE=='cardform'&&parent&&parent.hasClassName('isFilled')){parent.removeClassName('isFilled');}}}}},checkValueByOperator:function(operator,condValueOrg,fieldValueOrg,termField){try{if(typeof condValueOrg=="string"&&condValueOrg.indexOf("{")>-1&&condValueOrg.indexOf("}")>-1){condValueOrg=condValueOrg.replace(/\{.*?\}/gi,function(match){var stripped=match.replace(/[\{\}]/g,"");var elements=$$('input[name$="_'+stripped+'"], input[name$="_'+stripped+'[date]"], input[name$="_'+stripped+'[0]"]');elements=Array.from(elements);if(elements.length>0){var element=elements.first();var nonRadioElement=elements.find(function(el){return el.type!=='radio'});if(element&&!nonRadioElement){var checkedElement=elements.find(function(el){return el.checked});if(checkedElement){return checkedElement.value;} return;} if(element&&element.value){return element.value;}} return match;});}}catch(e){console.log(e);} var fieldType=JotForm.getInputType(termField);var fieldValue=Object.isBoolean(fieldValueOrg)?fieldValueOrg:fieldValueOrg.toString().strip().toLowerCase();var condValue=Object.isBoolean(condValueOrg)?condValueOrg:condValueOrg.toString().strip().toLowerCase();if(fieldType==='appointment'){fieldValue=fieldValue?new Date(fieldValue.replace(/-/g,'/')).getTime():0;condValue=condValue?new Date(condValue.replace(/-/g,'/')).getTime():0;} switch(operator){case"equals":return fieldType=='number'?parseFloat(fieldValue)==parseFloat(condValue):fieldValue==condValue;case"quantityEquals":case"equalDate":return fieldValue==condValue;case"equalDay":return JotForm.getDayOfWeek(fieldValue)==condValueOrg.toLowerCase();case"notEquals":case"notEqualDate":case"quantityNotEquals":return fieldValue!=condValue;case"notEqualDay":return JotForm.getDayOfWeek(fieldValue)!=condValue;case"endsWith":return fieldValue.endsWith(condValue);case"notEndsWith":return!fieldValue.endsWith(condValue);case"startsWith":return fieldValue.startsWith(condValue);case"notStartsWith":return!fieldValue.startsWith(condValue);case"contains":condValues=condValue!=","?condValue.split(","):condValue.split(" ");return $A(condValues).any(function(cv){return fieldValue.include(cv.replace(/^\s+|\s+$/g,''));});case"notContains":condValues=condValue.split(",");return!$A(condValues).any(function(cv){return fieldValue.include(cv.replace(/^\s+|\s+$/g,''));});case"greaterThan":case"quantityGreater":return(parseFloat(fieldValue,10)||0)>(parseFloat(condValue,10)||0);case"lessThan":case"quantityLess":if(fieldValue.length){return(parseFloat(fieldValue,10)||0)<(parseFloat(condValue,10)||0);}else{return false;} case"isEmpty":if(Object.isBoolean(fieldValue)||!fieldValue.empty){return!fieldValue;} return fieldValue.empty();case"isFilled":if(Object.isBoolean(fieldValue)||!fieldValue.empty){return fieldValue;} return!fieldValue.empty();case"before":return fieldValueOrgcondValueOrg;default:JotForm.error("Could not find this operator",operator);} return false;},getDayOfWeek:function(date){date=new Date(date);var days=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"];return days[date.getDay()];},typeCache:{},getInputType:function(id){if(JotForm.typeCache[id]){return JotForm.typeCache[id];} if(typeof id==='string'&&id.indexOf('|')>-1){var tempField=id.split('|');if($('id_'+tempField[0])&&$('id_'+tempField[0]).readAttribute('data-type')=="control_inline"){id=tempField[0];}else{id=tempField[0]+'_field_'+tempField[1];}} var type="other";if($('id_'+id)&&$('id_'+id).readAttribute('data-type')=="control_text"){type='html';}else if($('id_'+id)&&$('id_'+id).readAttribute('data-type')=="control_inline"){type='inline';}else if($('input_'+id+'_pick')||($('id_'+id)&&$('id_'+id).readAttribute('data-type')=="control_datetime")){type='datetime';}else if($('input_'+id+'_duration')){type='appointment';}else if($('input_'+id)){type=$('input_'+id).nodeName.toLowerCase()=='input'?$('input_'+id).readAttribute('type').toLowerCase():$('input_'+id).nodeName.toLowerCase();if($('input_'+id).hasClassName("form-radio-other-input")){type="radio";} if($('input_'+id).hasClassName("js-forMixed")){type="mixed";} if($('input_'+id).hasClassName("form-checkbox-other-input")){type="checkbox";} if($('input_'+id).hasClassName('form-autocomplete')){type="autocomplete";} if($$('#id_'+id+' .pad').length>0){type='signature';} if($('input_'+id).hasClassName('form-slider')){type='slider';} if($('input_'+id).hasClassName('form-widget')){type='widget';} if($('input_'+id).hasClassName('form-star-rating')){type="rating";}}else if($('input_'+id+'_month')){type='birthdate';}else if($('input_'+id+'_hourSelect')){type='time';}else if($("cid_"+id)&&$("cid_"+id).getAttribute("data-type")=="control_collapse"){return'collapse';}else if($$('#id_'+id+' .form-product-item').length>0){type=$$('#id_'+id+' .form-product-item')[0].select('input')[0].readAttribute('type').toLowerCase();}else if($$('#id_'+id+' .product--subscription').length>0){type=$$('#id_'+id+' .product--subscription')[0].select('input')[0].readAttribute('type').toLowerCase();}else if($$('#id_'+id+' .form-address-table').length>0){type='address';}else if($$('input[id^=input_'+id+'_]')[0]&&$$('input[id^=input_'+id+'_]')[0].hasClassName('form-grading-input')){type='grading';}else if($('id_'+id)&&$('id_'+id).getAttribute('data-type')=='control_mixed'){type='mixed';}else{if($$('#id_'+id+' input')[0]){type=$$('#id_'+id+' input')[0].readAttribute('type').toLowerCase();if(type=="text"||type=='tel'||type==='number'){type="combined";} var matrixInputs=$$('#id_'+id+' input,'+'#id_'+id+' select');if(!matrixInputs.every(function(input){return input.type===matrixInputs[0].type})){type="combined";}}else if($$('#id_'+id+' select')[0]){type="select";}} JotForm.typeCache[id]=type;return type;},strToDate:function(str){var invalid=new Date(undefined);var match=/(\d{4})\-(\d{2})-(\d{2})T?(\d{2})?\:?(\d{2})?/gim;if(str.empty()){return invalid;} if(!match.test(str)){return invalid;} var d=new Date();str.replace(match,function(all,year,month,day,hour,minutes){if(hour){d=new Date(parseInt(year,10),parseInt(month,10)-1,parseInt(day,10),parseInt(hour,10),parseInt(minutes,10));}else{d=new Date(parseInt(year,10),parseInt(month,10)-1,parseInt(day,10));} return all;});return d;},getBirthDate:function(id){var day=document.querySelector('#input_'+id+'_day').value||"%empty%";var month=document.querySelector('#input_'+id+'_month').selectedIndex||"%empty%";month=String(month);var year=document.querySelector('#input_'+id+'_year').value||"%empty%";var date=year+"-"+(month.length==1?'0'+month:month)+"-"+(day.length==1?'0'+day:day);if(date.includes("%empty%"))return"";return date;},get24HourTime:function(id){var hour=$('input_'+id+'_hourSelect').getValue();if(hour=="")return"";var minute=$('input_'+id+'_minuteSelect').getValue();if(minute.length==0)minute="00";var ampm=($('input_'+id+'_ampm'))?$('input_'+id+'_ampm').getValue():'';hour=Number(hour);if(ampm=='PM'&&hour!=12){hour+=12;}else if(ampm=='AM'&&hour==12){hour=0;} hour=(hour<10)?"0"+hour:String(hour);return hour+minute;},getDateValue:function(id){let date="";const yearElement=document.querySelector(`#year_${id}`) if(yearElement){date+=(yearElement.value||"%empty%");} const monthElement=document.querySelector(`#month_${id}`) if(monthElement){const mm=monthElement.value?(monthElement.value.length>1?monthElement.value:"0"+monthElement.value):"%empty%";date+="-"+mm;} const dayElement=document.querySelector(`#day_${id}`) if(dayElement){const dd=dayElement.value?(dayElement.value.length>1?dayElement.value:"0"+dayElement.value):"%empty%";date+="-"+dd;} if(date.includes("%empty%")){JotForm.info("Wrong date: "+date);return"";} let h="";const hourElement=document.querySelector(`#hour_${id}`) const ampmElement=document.querySelector(`#ampm_${id}`) if(ampmElement){if(hourElement){h=hourElement.value;if(ampmElement.value=='pm'){h=parseInt(h,10)+12;} if(h=="24"){h=0;} date+="T"+((h.length==1?"0"+h:h)||"00");}}else{if(hourElement){h=hourElement.value;date+="T"+((h.length==1?"0"+h:h)||"00");}} const minElement=document.querySelector(`#min_${id}`);if(minElement){date+=":"+(minElement.value||"00");} if(h===""){date+="T00:00";} return date;},hidePages:{},getAdditionalRequiredValidationArray:function(action,qIdForMultiple){if(!action.additionalRequireTypes)return;var values=[];if(qIdForMultiple){Object.keys(action.additionalRequireTypes).forEach(function(qKey){var qidFromQKey=typeof qKey==='string'&&qKey.split('-').length>=2&&qKey.split('-')[1] if(qIdForMultiple===qidFromQKey){Object.keys(action.additionalRequireTypes[qKey]).forEach(function(val){values.push(action.additionalRequireTypes[qKey][val]);});}});}else{Object.keys(action.additionalRequireTypes).forEach(function(qKey){Object.keys(action.additionalRequireTypes[qKey]).forEach(function(val){values.push(action.additionalRequireTypes[qKey][val]);});});} return values;},getFieldFromID:function(questionID){return document.querySelector('.form-line#id_'+questionID);},getMatrixValues:function(questionID,operator){const matrix=document.getElementById("matrix_"+questionID);const desktopVersion=matrix.querySelector('.forDesktop');const mobileVersion=matrix.querySelector('.forMobile');const dataType=matrix.getAttribute('data-type');let currentVersion='desktop';if(desktopVersion&&mobileVersion&&document.defaultView.getComputedStyle(desktopVersion,null).display==='none'){currentVersion='mobile';} const checkedValues=function(value){const yesNoID=value.id;const yesNoValue=Array.from(document.querySelectorAll('label[for="'+yesNoID+'"]'));const yesNoValueText=yesNoValue.length>0?yesNoValue[0].innerText:value.checked;return value.checked?yesNoValueText:value.checked;} switch(true){case dataType==='Yes No'&&(operator=='contains'||operator=='notContains'):let selector="";if(desktopVersion&¤tVersion==='desktop'){selector='#id_'+questionID+' input:not([disabled]):not([class*="jsMatrix-mobileNo"]:not([class*="jsMatrix-mobileYes"])';} if(mobileVersion&¤tVersion==='mobile'){selector='#id_'+questionID+' input:not([disabled])[class*="jsMatrix-mobileNo"],[class*="jsMatrix-mobileYes"]';} return Array.from(document.querySelectorAll(selector)).map(function(value){return checkedValues(value);});}},checkCondition:function(condition,sourceField,sourceEvent){if(condition.__disabledByDebugger){return;} var any=false,all=true;var filled;if(condition.link===undefined){condition.link='Any';} $A(condition.terms).each(function(term){var value;var anotherField=JotForm.getFieldIdFromFieldRef(term.value);term.field=String(term.field);try{var fieldType=JotForm.getInputType(term.field);switch(fieldType){case"combined":if(['isEmpty','isFilled'].include(term.operator)){filled=$$('#id_'+term.field+' input,'+'#id_'+term.field+' select').collect(function(e){return e.getAttribute('type')==='checkbox'||e.getAttribute('type')==='radio'?(e.checked?e.value:''):e.value;}).any();if(JotForm.checkValueByOperator(term.operator,term.value,filled)){any=true;}else{all=false;} return;}else{value=$$('#id_'+term.field+' input,'+'#id_'+term.field+' select').collect(function(e){return e.getAttribute('type')==='checkbox'?(e.checked?e.value:''):e.value;});if(JotForm.checkValueByOperator(term.operator,term.value,value)){any=true;}else{all=false;}} break;case"address":if(['isEmpty','isFilled'].include(term.operator)){filled=$$('#id_'+term.field+' input:not(.jfDropdown-search)','#id_'+term.field+' select').collect(function(e){return e.value;}).any();if(JotForm.checkValueByOperator(term.operator,term.value,filled)){any=true;}else{all=false;}}else if(term.operator=="equalCountry"||term.operator=='notEqualCountry'){var option;var termValue=term.value;if(anotherField){termValue=$('input_'+anotherField+'_country').value;} $('input_'+term.field+'_country').select("option").each(function(opt){if(termValue===opt.value){option=opt;throw $break;}});if(option){if(term.operator=='equalCountry'){if(option.selected){any=true;}else{all=false;}}else if(term.operator=='notEqualCountry'){if(!option.selected){any=true;}else{all=false;}}}}else{var inputValue;var termValue=term.value;if(anotherField){termValue=$('input_'+anotherField+'_state').value;} inputValue=$('input_'+term.field+'_state').value if(inputValue){if(term.operator=='equalState'){if(inputValue==termValue){any=true;}else{all=false;}}else if(term.operator=='notEqualState'){if(!(inputValue==termValue)){any=true;}else{all=false;}}}} break;case"birthdate":case"datetime":value=(fieldType=="datetime")?JotForm.getDateValue(term.field):JotForm.getBirthDate(term.field);if(value===undefined){return;} if(['isEmpty','isFilled'].include(term.operator)){if(JotForm.checkValueByOperator(term.operator,term.value,value)){any=true;}else{all=false;}}else{var termValue=term.value;termValue=term.value.toLowerCase().replace(/\s/g,"");if(termValue.indexOf('today')>-1){var offset=parseInt(termValue.split('today')[1])||0;var comparativeDate=new Date();comparativeDate.setDate(comparativeDate.getDate()+offset);var year=comparativeDate.getFullYear();var month=comparativeDate.getMonth()+1;month=(month<10)?'0'+month:month;var day=comparativeDate.getDate();day=(day<10)?'0'+day:day;termValue=year+"-"+month+"-"+day;}else if(anotherField){var year=$("year_"+anotherField).value;var month=$("month_"+anotherField).value;var day=$("day_"+anotherField).value;if(term.operator==="equalDay"||term.operator==="notEqualDay"){termValue=JotForm.getDayOfWeek(JotForm.strToDate(year+"-"+month+"-"+day));}else{termValue=year+"-"+month+"-"+day;}} if(['equalDate','notEqualDate','after'].include(term.operator)){if(JotForm.checkValueByOperator(term.operator,JotForm.strToDate(termValue),JotForm.strToDate(value.split('T')[0]))){any=true;}else{all=false;}}else if(['equalDay','notEqualDay'].include(term.operator)){if(JotForm.checkValueByOperator(term.operator,termValue,JotForm.strToDate(value))){any=true;}else{all=false;}}else{if(JotForm.checkValueByOperator(term.operator,JotForm.strToDate(termValue),JotForm.strToDate(value))){any=true;}else{all=false;}}} break;case"time":value=JotForm.get24HourTime(term.field);var termValue=(!term.value)?"":term.value.replace(/:/,"");if(anotherField){termValue=JotForm.get24HourTime(anotherField);} if(termValue.length==3)termValue="0"+termValue;if(term.operator=='before'&&value.empty()){all=false;}else{if(JotForm.checkValueByOperator(term.operator,termValue,value)) any=true;else all=false;} break;case"checkbox":case"radio":if(['isEmpty','isFilled'].include(term.operator)){filled=$$('#id_'+term.field+' input').collect(function(e){return e.checked;}).any();if(JotForm.checkValueByOperator(term.operator,term.value,filled)){any=true;}else{all=false;} return;} if(term.value)term.value=term.value.replace(/&/g,'&').replace(/>/g,'>').replace(/</g,'<');if(['lessThan','greaterThan'].include(term.operator)){var localResult=false;$$('#id_'+term.field+' input').each(function(input){value=input.checked?input.value:'';if(JotForm.checkValueByOperator(term.operator,term.value,value)){any=true;localResult=true;}});if(!localResult)all=false;return;} var otherValue=$('id_'+term.field).down(".form-"+fieldType+"-other-input")?$('id_'+term.field).down(".form-"+fieldType+"-other-input").getAttribute('data-otherhint').replace(/&/g,'&').replace(/>/g,'>').replace(/</g,'<'):"";$$('#id_'+term.field+' input').each(function(input){if(input.hasClassName('form-'+fieldType+'-other')&&input.checked){value='-- '+otherValue+' --';}else{value=input.checked?input.value:'';value=value.replace(/_expanded/,'');} var termValue=term.value.strip();var checkResult=JotForm.checkValueByOperator(term.operator,termValue,value);if(term.operator=='notEquals'){checkResult=$$('#id_'+term.field+' input').filter(function(value){return value.checked;}).map(function(checkedValue){return JotForm.checkValueByOperator(term.operator,termValue,checkedValue.value);}).every(function(value){return value;});} if(document.getElementById("matrix_"+term.field)){var checkedValue=JotForm.getMatrixValues(term.field,term.operator);if(checkedValue){checkResult=JotForm.checkValueByOperator(term.operator,termValue,checkedValue);}} if(checkResult){any=true;}else{if(term.operator=='notEquals'&&termValue==value){all=false;if(condition.link.toLowerCase()=='all'){throw $break;}}else if(input.value==termValue||(input.hasClassName('form-'+fieldType+'-other')&&termValue=='-- '+otherValue+' --')||input.value.replace(/_expanded/,'')==termValue){all=false;}}});break;case"select":if(term.value){term.value=term.value.replace(/&/g,'&');} var tempInput='';if(term.field.indexOf('|')>-1){var tempSplit=term.field.split('|');tempInput='input_'+tempSplit[0]+'_field_'+tempSplit[1];}else{tempInput='input_'+term.field;} if($(tempInput)&&$(tempInput).multiple){if(term.operator=='equals'){var option=$(tempInput).querySelector('option[value="'+(term.value||'').replace(/["\\]/g,'\\$&')+'"]');if(option&&option.selected){any=true;}else{all=false;}}else if(term.operator=='notEquals'){var option=$(tempInput).querySelector('option[value="'+(term.value||'').replace(/["\\]/g,'\\$&')+'"]');if(option&&!option.selected){any=true;}else{all=false;}}else if(['isEmpty','isFilled'].include(term.operator)){var selected=false;var arr=$(tempInput).options;for(var i=0;i0){value=$('id_'+term.field).select('.qq-upload-file').length>0;}else{if($('input_'+term.field).uploadMarked){value=$('input_'+term.field).uploadMarked;}else{value=$('input_'+term.field).value;}} if(value===undefined){return;} if(JotForm.checkValueByOperator(term.operator,term.value,value,term.field)){any=true;}else{all=false;} break;case"textarea":value=$('input_'+term.field).value;if($('input_'+term.field).hinted||$('input_'+term.field).hasClassName('form-custom-hint')){value="";} if(value===undefined){return;} var rich=$('id_'+term.field).down('.nicEdit-main');if(rich){value=value.stripTags().replace(/\s/g,' ').replace(/ /g,' ');} if(JotForm.checkValueByOperator(term.operator,term.value,value,term.field)){any=true;}else{all=false;} break;case"widget":value=$('input_'+term.field).value;var termField=term.field;var widgetType=JotForm.getWidgetType(term.field);if(value===undefined){return;} if(widgetType&&widgetType==='checklist'){var checked=JotForm.getChecklistWidgetValues(term.field).checked;termField=checked.indexOf(term.value)!==-1;value=checked.find(function(value){return value===term.value;})||'';if(term.operator==='isFilled'||term.operator==='isEmpty'){value=checked.join(',');}} if(widgetType&&(widgetType=='inventory'||widgetType=='inventoryV2')&&value){var valArr=value.split('\n');if(Array.isArray(valArr)){value=valArr[0];if(isNaN(valArr[0])){value=valArr[0].match(/ \[(\d+)\]$/)[1];}}} if(value.indexOf("widget_metadata")>-1){try{value=JSON.parse(value).widget_metadata.value;var matchingItem=false;for(var i=0;i-1){var tempSplit=term.field.split('|');var questionId=tempSplit[0];var fieldId=tempSplit[1];var TIMESTAMP_OF_2019=1546300000000;var isNewIDType=Number(fieldId)>TIMESTAMP_OF_2019;var selector=isNewIDType?'[id*='+fieldId+'-]':'[id$=-'+fieldId+']';selector='#id_'+questionId+' input'+selector+', #id_'+questionId+' select'+selector;}else{return;} var inputs=$$(selector);if(inputs.length===0){return;} value=inputs.collect(function(e){return['checkbox','radio'].indexOf(e.getAttribute('type'))>-1?(e.checked?e.value:''):e.value;}).filter(function(val){return val;}).join(' ');if(JotForm.checkValueByOperator(term.operator,term.value,value,term.field)){any=true;}else{all=false;} break;case"appointment":value=JotForm.appointments[term.field].getComparableValue();if(JotForm.checkValueByOperator(term.operator,term.value,value,term.field)){any=true;}else{all=false;} break;default:var tempInput='';if(term.field.indexOf('|')>-1){var tempSplit=term.field.split('|');tempInput='input_'+tempSplit[0]+'_field_'+tempSplit[1];}else{tempInput='input_'+term.field;} if(!$(tempInput)){return;} if($(tempInput)&&$(tempInput).multiple){if(term.operator=='equals'){var option=$(tempInput).select('option[value='+term.value+']');if(option.length>0&&option[0].selected){any=true;}else{all=false;}}else if(term.operator=='notEquals'){var option=$(tempInput).select('option[value='+term.value+']');if(option.length>0&&!option[0].selected){any=true;}else{all=false;}}else if(['isEmpty','isFilled'].include(term.operator)){var selected=false;var arr=$(tempInput).options;for(var i=0;i100?100:conditionBasedMaxLoop;var maxLoopSize=JotForm.clearFieldOnHide=="enable"?3:limitedMaxLoop;window.lastConditionTimeStamp=window.lastConditionTimeStamp||new Date().getTime();var betweenLookUp=(timestamp-window.lastConditionTimeStamp)/1000;if(betweenLookUp>10){window.__antiConditionLoopCache={};window.lastConditionTimeStamp=null;} if(!("__antiConditionLoopCache"in window)){window.__antiConditionLoopCache={};} if(antiLoopKey in window.__antiConditionLoopCache){window.__antiConditionLoopCache[antiLoopKey]++;if(window.__antiConditionLoopCache[antiLoopKey]>maxLoopSize){return true;}}else{window.__antiConditionLoopCache[antiLoopKey]=1;} return false;} const ignoreFields=['time','datetime','text','mixed'];const operands=(condition.action&&condition.action[0]&&condition.action[0].operands&&condition.action[0].operands.split(','))||[];const baseFieldsForLoop=(condition.action&&condition.action[0]&&condition.action[0].baseField&&condition.action[0].baseField.split(','))||[];const ignoreFieldConditionLoopCheck=Boolean(([...baseFieldsForLoop,...operands]).find(conditionFieldForLoop=>ignoreFields.includes(JotForm.getInputType(conditionFieldForLoop))));const checkConditionInfiniteLoop=condition.type==='calculation'?(this.loopMapExist||ignoreFieldConditionLoopCheck):true;if(checkConditionInfiniteLoop&&conditionInfiniteLoop()){if(JotForm.isConditionDebugMode){var index=JotForm.conditions.findIndex(val=>val===condition);if(typeof __conditionDebugger_logStatus==='function'){__conditionDebugger_logStatus([{title:'Loop Detected In',value:`Condition-${index}`}]);} console.log({condition:condition,sourceField:sourceField,index},'IN CHECK CONDITION');} return;} if(condition.type=='field'){var isConditionValid=(condition.link.toLowerCase()=='any'&&any)||(condition.link.toLowerCase()=='all'&&all);if(condition.disabled==true)return;condition.action.each(function(action){var matchingTermAction=condition.terms.any(function(term){return term.field==action.field;});if(isConditionValid){action.currentlyTrue=true;if(action.visibility.toLowerCase()=='show'){JotForm.showField(action.field);}else if(action.visibility.toLowerCase()=='hide'){JotForm.hideField(action.field,false,matchingTermAction);}else if(action.visibility.toLowerCase()=='showmultiple'&&action.fields){if(JotForm.showOrHideMultipleFields){JotForm.showOrHideMultipleFields(true,action.fields,true);}else{action.fields.each(function(field){JotForm.showField(field,true);});}}else if(action.visibility.toLowerCase()=='hidemultiple'&&action.fields){if(JotForm.showOrHideMultipleFields){JotForm.showOrHideMultipleFields(false,action.fields,true,matchingTermAction);}else{action.fields.each(function(field){JotForm.hideField(field,true,matchingTermAction);});}}}else{action.currentlyTrue=false;if(action.visibility.toLowerCase()=='show'){JotForm.hideField(action.field,false,matchingTermAction);}else if(action.visibility.toLowerCase()=='hide'){JotForm.showField(action.field,false);}else if(action.visibility.toLowerCase()=='showmultiple'&&action.fields){if(JotForm.showOrHideMultipleFields){JotForm.showOrHideMultipleFields(false,action.fields,true,matchingTermAction);}else{action.fields.each(function(field){JotForm.hideField(field,true,matchingTermAction);});}}else if(action.visibility.toLowerCase()=='hidemultiple'&&action.fields){if(JotForm.showOrHideMultipleFields){JotForm.showOrHideMultipleFields(true,action.fields,true);}else{action.fields.each(function(field){JotForm.showField(field,true);});}}} if(window.FORM_MODE!=='cardform')JotForm.iframeHeightCaller();if($('section_'+action.field)||'fields'in action){if(JotForm.clearFieldOnHide==='enable'){JotForm.runAllCalculations(true);}} if($('input_'+action.field)&&$('input_'+action.field).triggerEvent){if(!matchingTermAction&&$('input_'+action.field).className.indexOf("-other-")<0){$('input_'+action.field).triggerEvent('keyup');}}});}else if(condition.type=='require'){var isConditionValid=(condition.link.toLowerCase()=='any'&&any)||(condition.link.toLowerCase()=='all'&&all);condition.action.each(function(action){action.currentlyTrue=isConditionValid;if(action.visibility.toLowerCase()=='require'){var additionalRequireType=JotForm.getAdditionalRequiredValidationArray(action,false);JotForm.requireField(action.field,isConditionValid,additionalRequireType);}else if(action.visibility.toLowerCase()=='unrequire'){JotForm.requireField(action.field,!isConditionValid);}else if(action.visibility.toLowerCase()=='requiremultiple'&&action.fields){action.fields.each(function(field){var additionalRequireType=JotForm.getAdditionalRequiredValidationArray(action,field);JotForm.requireField(field,isConditionValid,additionalRequireType);});}else if(action.visibility.toLowerCase()=='unrequiremultiple'&&action.fields){action.fields.each(function(field){JotForm.requireField(field,!isConditionValid);});}else if(action.visibility.toLowerCase()=='enable'){JotForm.enableDisableField(action.field,isConditionValid);}else if(action.visibility.toLowerCase()=='disable'){JotForm.enableDisableField(action.field,!isConditionValid);}else if(action.visibility.toLowerCase()=='disablesubmit'){JotForm.disableSubmitForCard(action,isConditionValid);}});}else if(condition.type=='mask'){try{condition.action.each(function(action){if((condition.link.toLowerCase()=='any'&&any)||(condition.link.toLowerCase()=='all'&&all)){condition.conditionTrue=true;JotForm.setQuestionMasking("#input_"+action.field,"textMasking",action.mask);if($("input_"+action.field)) {$("input_"+action.field).writeAttribute('data-masked',"true");$("input_"+action.field).className.indexOf('validate[Fill Mask]')===-1&&$("input_"+action.field).addClassName('validate[Fill Mask]');$("input_"+action.field).writeAttribute('masked',"true");JotForm.setFieldValidation($("input_"+action.field));}}else{condition.conditionTrue=false;var removeMask=true;$A(JotForm.conditions).each(function(cond){if(cond.disabled==true)return;if(cond.type!=='mask')return;if(!cond.conditionTrue)return;$A(cond.action).each(function(act){if(act.field==action.field){removeMask=false;}});});if(removeMask){JotForm.setQuestionMasking("#input_"+action.field,"","",true);if($("input_"+action.field)) {$("input_"+action.field).writeAttribute('masked',"false");}}}});}catch(error){console.log(error);}}else if(condition.type=='calculation'){var tempResultField=condition.action[0].resultField;var tempInput=$("id_"+tempResultField);if(tempResultField.indexOf('|')>-1){var slicedQid=tempResultField.split('|');var qid=slicedQid[0];var fieldId=slicedQid[1];if($("id_"+qid)&&$("id_"+qid).getAttribute('data-type')==='control_inline'){tempInput=$$("#id_"+qid+' input[id*='+fieldId+']');}else{tempResultField='input_'+qid+'_field_'+fieldId;tempInput=$(tempResultField);}} if(!tempInput){return;} var calcs=JotForm.calculations;for(var i=0;i0&&condition.action.first().skipHide==='hidePage'){var action=condition.action.first();if(window.FORM_MODE=='cardform'){if((condition.link.toLowerCase()=='any'&&any)||(condition.link.toLowerCase()=='all'&&all)){JotForm.hideField(action.skipTo);}else{JotForm.showField(action.skipTo);}}else{var pageId=parseInt(action.skipTo.replace('page-',''),10);if((condition.link.toLowerCase()=='any'&&any)||(condition.link.toLowerCase()=='all'&&all)){JotForm.hidePages[pageId]=true;Array.from(document.querySelectorAll('.form-all .page-section')[pageId-1].children||[]).forEach(function(element){JotForm.corrected(element);});}else{JotForm.hidePages[pageId]=false;}} return;} var action=condition.action[0];var sections;if(window.FORM_MODE=='cardform'){sections=$$('.form-all > .form-line');var currentQuestionIndex;var nextQuestionIndex;try{var allQuestions=window.CardLayout.layoutParams.allQuestions;var currentSection=sections.find(function(section){return section.firstChild&§ion.firstChild.classList.contains('isVisible');});allQuestions.some(function(q,index){if(q.id===currentSection.id.substring(currentSection.id.indexOf('_')+1)){currentQuestionIndex=index;return true;}});if(action.skipTo=='end'){nextQuestionIndex=allQuestions.length-1;}else{allQuestions.some(function(q,index){if(q.id===action.skipTo||q.id===action.skipTo.replace('page-','')){nextQuestionIndex=index;return true;};});}}catch(error){console.log(error);}}else{sections=$$('.form-all > .page-section');} if(window.FORM_MODE=='cardform'&&!isConditionValid){for(var i=nextQuestionIndex;i=nextQuestionIndex;i--){var card=JotForm.getFieldFromID(allQuestions[i].id);if(card&&!card.hasClassName('always-hidden')){JotForm.showField(allQuestions[i].id);}}}}}catch(error){console.log(error);}}}else{if(action.skipTo=='end'){JotForm.nextPage=sections[sections.length-1];}else{JotForm.nextPage=sections[parseInt(action.skipTo.replace('page-',''),10)-1];}} if($$('[data-type="control_paypalSPB"]')[0]&&$$('[data-paypal-button="Yes"]')[0]){var paypalSection=JotForm.getSection($$('[data-type="control_paypalSPB"]')[0]).pagesIndex;var currentSection=JotForm.currentSection.pagesIndex;var nextSection=JotForm.nextPage.pagesIndex;if((paypalSection>currentSection&&paypalSectionnextSection)){var paypalButton=$$('.paypal-buttons.paypal-buttons-context-iframe')[0];var paypalButtonContainer=JotForm.getContainer(paypalButton);if(paypalButton&&paypalButtonContainer){paypalButtonContainer.setAttribute('paypal-button-status','hide');}}}}else{JotForm.info('Fail: Skip To: page-'+JotForm.currentPage+1);JotForm.nextPage=false;}} if(JotForm.nextPage&&JotForm.isEditMode()){if(window.FORM_MODE!=='cardform'){var currentPageIndex=$$('.page-section').indexOf(JotForm.currentSection);var skipCondition=function(){if(condition.link.toLowerCase()=='any'){return condition.terms.every(function(term){return $$('.page-section').indexOf($('id_'+term.field).up('.page-section'))>currentPageIndex;});} return condition.terms.some(function(term){return $$('.page-section').indexOf($('id_'+term.field).up('.page-section'))>currentPageIndex;});} JotForm.nextPage=skipCondition()?false:JotForm.nextPage;}} JotForm.enableDisableButtonsInMultiForms();},currentPage:false,nextPage:false,previousPage:false,fieldConditions:{},setFieldConditions:function(field,event,condition){var tempField='';if(field.indexOf('|')>-1){var fieldSplit=field.split('|');tempField=fieldSplit[0]+'_field_'+fieldSplit[1];}else{tempField=field;} if(!JotForm.fieldConditions[tempField]){JotForm.fieldConditions[tempField]={event:event,conditions:[]};} JotForm.fieldConditions[tempField].conditions.push(condition);this.setSubproductQuantityConditions(tempField,condition);},setSubproductQuantityConditions:function(tempField,condition){if(tempField.match(/input_[0-9]+_quantity_[0-9]+_[0-9]+/)){var qid=tempField.split('_')[1],pid=tempField.split('_')[3];var pItem=document.querySelector('.form-product-item[pid="'+pid+'"], .form-product-item[data-pid="'+pid+'"]');if(!pItem){return;} var subQuantities=pItem.querySelectorAll('#input_'+qid+'_'+pid+'_subproducts.form-product-child-table .form-subproduct-quantity');if(subQuantities.length===0){return;} Array.from(subQuantities).forEach(function(quantityInput){var _condition=JSON.parse(JSON.stringify(condition));_condition.terms[0].field=quantityInput.id.replace('input_','');var c={conditions:[],event:'change'};c.conditions.push(_condition);JotForm.fieldConditions[quantityInput.id]=c;});}},widgetsAsCalculationOperands:[],requireField:function(qid,req,additionalRequireType){var subfieldID=null;if(qid.indexOf('|')>-1){var subfieldID=qid.split('|')[1];qid=qid.split('|')[0];} if(!$('id_'+qid))return;if(JotForm.otherConditionTrue(qid,req?'unrequire':'require'))return;var elements=[];if(subfieldID){elements=$$('#id_'+qid+' input[id$=-'+subfieldID+'], #id_'+qid+' textarea[id$=-'+subfieldID+'], #id_'+qid+' select[id$=-'+subfieldID+']');}else{elements=$$('#id_'+qid+' input, #id_'+qid+' textarea, #id_'+qid+' select');} elements.each(function(el){if(el.id==='coupon-input'||(el.type==='hidden'&&!el.up('.form-star-rating')&&!el.hasClassName('form-widget')&&!el.up('.FITB-inptCont[data-type="signaturebox"]')&&(!("input_"+qid+"_date"===el.id&&JotForm.getInputType(qid)==="appointment"&&$("input_"+qid+"_date"))))||el.hasClassName('form-checkbox-other-input')||el.hasClassName('form-radio-other-input')||el.hasClassName('jfModal-input')||$A(['prefix','middle','suffix','addr_line2']).any(function(name){return el.name.indexOf("["+name+"]")>-1;})||el.hasClassName('jfDropdown-search')||el.hasClassName('jfRating-shortcut-input')||el.hasClassName('__PrivateStripeElement-input')||el.up('.product-container-wrapper .filter-container #payment-category-dropdown')||(el.up('.product-container-wrapper .filter-container')&&el.id==='productSearch-input')){return;} var validations=[];if(el.className.indexOf('validate[')>-1){validations=el.className.substr(el.className.indexOf('validate[')+9);validations=validations.substr(0,validations.indexOf(']')).split(/\s*,\s*/);}else{validations=[];} if(JotForm.getInputType(qid)=="file"&&el.getAttribute("multiple")=="multiple"&&el.up('[class*=validate[multipleUpload]]')){var uploadWrapper=el.up('[class*=validate[multipleUpload]]');uploadWrapper.className=uploadWrapper.className.replace(/validate\[required\]/gi,'');if(req){uploadWrapper.addClassName("validate[required]");}else{uploadWrapper.removeClassName("form-validation-error");}} if("input_"+qid+"_date"===el.id&&JotForm.getInputType(qid)=="appointment"&&$("input_"+qid+"_date")){if(req){$("input_"+qid+"_date").addClassName("validate");}else{$("input_"+qid+"_date").removeClassName("validate");}} el.className=el.className.replace(/validate\[.*\]/,'');for(var i=validations.length-1;i>=0;i--){if(validations[i]==='required'||additionalRequireType&&additionalRequireType.some(function(t){return t===validations[i];})){validations.splice(i,1);}} if(req){validations.push('required');additionalRequireType&&additionalRequireType.forEach(function(t){validations.push(t)});if(el.hasClassName('form-widget')){el.addClassName('widget-required');}}else{el.removeClassName('form-validation-error');el.removeClassName('widget-required');} if(validations.length>0){el.addClassName('validate['+validations.join(',')+']');} JotForm.setFieldValidation(el);});var sigPad=$$('div.pad#sig_pad_'+qid)[0];if(sigPad){sigPad.setAttribute('data-required',req);sigPad.className=sigPad.className.replace('validate[required]','').trim() if(req){sigPad.className=sigPad.className+' validate[required]';}} if(req){if($('label_'+qid)&&!$('label_'+qid).down('.form-required')){$('label_'+qid).insert('*');} elements.each(function(e){if(e.up('.FITB-inptCont')&&!e.up('.FITB-inptCont').down('.form-required')){e.up('.FITB-inptCont').insert('*');}});}else{if($('label_'+qid)&&$('label_'+qid).down('.form-required')){$('label_'+qid).down('.form-required').remove();} elements.each(function(e){if(e.up('.FITB-inptCont')&&e.up('.FITB-inptCont').down('.form-required')){e.up('.FITB-inptCont').down('.form-required').remove();}});if($("id_"+qid).down('.form-error-message')){$("id_"+qid).down('.form-error-message').remove();} $("id_"+qid).removeClassName('form-line-error');if($$('.form-line-error').length==0){JotForm.hideButtonMessage();}}},enableDisableField:function(qid,enable){var subfieldID=null;if(qid.indexOf('|')>-1){var subfieldID=qid.split('|')[1];qid=qid.split('|')[0];} if(!$('id_'+qid))return;try{var isSignatureField=$('id_'+qid).getAttribute('data-type')==="control_signature";var isAppointmentField=$('id_'+qid).getAttribute('data-type')==="control_appointment";var appointmentElements=isAppointmentField?Array.from($('id_'+qid).querySelectorAll(".calendarDay:not(.isUnavailable):not(.empty), .calendarDay.conditionallyDisabled, .appointmentSlot:not(.disabled), .appointmentSlot.conditionallyDisabled")):[];var isWidget=$('id_'+qid).readAttribute('data-type')==='control_widget'&&JotForm.getWidgetType(qid);var canEnabledDisabledWidget=isWidget?$('id_'+qid).down("iframe"):false;var elements=[];if(subfieldID){elements=$('id_'+qid).select("input[id*="+subfieldID+"], select[id*="+subfieldID+"]");}else{elements=$('id_'+qid).select("input, textarea, select, button").concat(appointmentElements);} elements.each(function(input){var isAppointmentSlot=isAppointmentField&&input.hasClassName("appointmentSlot");var isAppointmentCalendarDay=isAppointmentField&&input.hasClassName("calendarDay");var isActiveSlot=isAppointmentSlot&&input.hasClassName('active');var isDataRichText=input.hasAttribute('data-richtext')&&input.getAttribute('data-richtext')=="Yes";var signaturePad=isSignatureField?jQuery('#sig_pad_'+qid+'.pad'):null;var isMatrixButtonForMobileView=input.hasClassName("js-mobileMatrixPrevButton")||input.hasClassName("js-mobileMatrixNextButton");if(isMatrixButtonForMobileView){return;} if(enable){input.removeClassName("conditionallyDisabled");if(signaturePad&&signaturePad.jSignature){signaturePad.jSignature('enable');} if(canEnabledDisabledWidget){canEnabledDisabledWidget.setStyle({'pointer-events':''});} if(!JotForm.isEditMode()){input.enable();if(input.classList.contains('form-star-rating-star')){input.parentNode.enable();} if(isActiveSlot){input.setStyle({'pointer-events':'all'});}else if(isDataRichText){var richTextArea=input.parentElement.querySelector(".nicEdit-main");if(richTextArea){richTextArea.setAttribute("contenteditable","true")};}else{input.removeClassName(isAppointmentSlot?"disabled":(isAppointmentCalendarDay?"isUnavailable":""));} return;} switch(input.tagName){case'SELECT':$$('#'+input.id+' > option').each(function(opt){opt.enable();});break;case'TEXTAREA':if(isDataRichText){var richTextArea=input.parentElement.querySelector(".nicEdit-main");if(richTextArea){richTextArea.setAttribute("contenteditable","true")};} default:input.removeAttribute('readonly');input.enable();break;} return;} if(!(input.hasClassName('form-radio-other-input')||input.hasClassName('form-checkbox-other-input'))){input.addClassName("conditionallyDisabled");} if(signaturePad&&signaturePad.jSignature){signaturePad.jSignature('disable');} if(canEnabledDisabledWidget){canEnabledDisabledWidget.setStyle({'pointer-events':'none'});} if(!JotForm.isEditMode()){input.disable();if(input.classList.contains('form-star-rating-star')){input.parentNode.disable();} if(isActiveSlot){input.setStyle({'pointer-events':'none'});}else if(isDataRichText){var richTextArea=input.parentElement.querySelector(".nicEdit-main");if(richTextArea){richTextArea.setAttribute("contenteditable","false")};}else{input.addClassName(isAppointmentSlot?"disabled":(isAppointmentCalendarDay?"isUnavailable":""));} return;} switch(input.tagName){case'SELECT':$$('#'+input.id+' > option').each(function(opt){opt.disabled=!opt.selected;});break;case'INPUT':if(['checkbox','radio'].include(input.type)||input.type==='file'||(['year_'+qid,'month_'+qid,'day_'+qid,'lite_mode_'+qid]).include(input.id)||(input.getAttribute('data-type')==='input-spinner')) {input.disable();} case'TEXTAREA':if(isDataRichText){var richTextArea=input.parentElement.querySelector(".nicEdit-main");if(richTextArea){richTextArea.setAttribute("contenteditable","false")};} default:input.setAttribute('readonly','');break;}});}catch(e){console.log(e);}},triggerWidgetCalculation:function(id){if(JotForm.widgetsAsCalculationOperands.include(id)){if(document.createEvent){var evt=document.createEvent('HTMLEvents');evt.initEvent('change',true,true);$('input_'+id).dispatchEvent(evt);}else if($('input_'+id).fireEvent){return $('input_'+id).fireEvent('onchange');}}},setCalculationResultReadOnly:function(){JotForm.calculations.forEach(function(calc){if((calc.readOnly&&calc.readOnly!="0")&&$('input_'+calc.resultField)!=null){$('input_'+calc.resultField).setAttribute('readOnly','true');}});},setCalculationEvents:function(){var setCalculationListener=function(el,ev,calc){var element=typeof el==="string"?document.getElementById(el):el;element.addEventListener(ev,function(){if(ev==="paste"){setTimeout(function(){element.classList.add('calculatedOperand');JotForm.checkCalculation(calc,el,ev);},10);}else{element.classList.add('calculatedOperand');JotForm.checkCalculation(calc,el,ev);}});};JotForm.calculations.forEach(function(calc,index){if(!calc.operands||typeof calc.operands==='function')return;var ops=calc.operands.split(',');for(var i=0;i-1){var splitResult=opField.split('|');var qid=splitResult[0];var fieldId=splitResult[1];if($('id_'+qid)&&$('id_'+qid).getAttribute('data-type')==='control_inline'){mixedOpField='id_'+qid;}else{mixedOpField='input_'+qid+'_field_'+fieldId;}} if(!opField||opField.empty()||(!$('id_'+opField)&&!$(mixedOpField)))continue;var type=JotForm.calculationType(opField);switch(type){case"mixed":if($(mixedOpField)){setCalculationListener($(mixedOpField),'change',calc,index);setCalculationListener($(mixedOpField),'blur',calc,index);setCalculationListener($(mixedOpField),'keyup',calc,index);setCalculationListener($(mixedOpField),'paste',calc,index);} break;case'inline':var el=$(mixedOpField)?$(mixedOpField):$('id_'+opField);setCalculationListener(el,'change',calc,index);break;case"widget":setCalculationListener($('id_'+opField),'change',calc);JotForm.widgetsAsCalculationOperands.push(opField);break;case'radio':case'checkbox':setCalculationListener($('id_'+opField),'change',calc);if($('input_'+opField)){setCalculationListener($('id_'+opField),'keyup',calc);} break;case'select':case'file':if(Protoplus&&Protoplus.getIEVersion&&Protoplus.getIEVersion()==8){setCalculationListener($('id_'+opField),'click',calc);}else{setCalculationListener($('id_'+opField),'change',calc);} break;case'datetime':setCalculationListener($('id_'+opField),'date:changed',calc);setCalculationListener($('id_'+opField),'paste',calc);setCalculationListener($('id_'+opField),'keyup',calc);$$('#id_'+opField+' input').each(function(el){setCalculationListener($(el),'blur',calc);});$$("#id_"+opField+' select').each(function(el){setCalculationListener($(el),'change',calc);});break;case'time':$$("#id_"+opField+' select').each(function(el){setCalculationListener($(el),'change',calc,index);});if(JotForm.newDefaultTheme||JotForm.extendsNewTheme){$$("#id_"+opField+" input[class*='form-textbox']").each(function(el){setCalculationListener($(el),'keyup',calc,index);setCalculationListener($(el),'blur',calc,index);});} break;case'birthdate':$$("#id_"+opField+' select').each(function(el){setCalculationListener($(el),'change',calc,index);});break;case'address':setCalculationListener($('id_'+opField),'change',calc,index);setCalculationListener($('id_'+opField),'blur',calc,index);setCalculationListener($('id_'+opField),'keyup',calc,index);$$("#id_"+opField+' select').each(function(el){setCalculationListener($(el),'change',calc,index);});break;case'number':setCalculationListener($('id_'+opField),'keyup',calc,index);setCalculationListener($('id_'+opField),'paste',calc,index);setCalculationListener($('id_'+opField),'click',calc,index);break;default:setCalculationListener($('id_'+opField),'change',calc,index);setCalculationListener($('id_'+opField),'blur',calc,index);setCalculationListener($('id_'+opField),'keyup',calc,index);setCalculationListener($('id_'+opField),'paste',calc,index);if(window.FORM_MODE==='cardform'&&$('id_'+opField).querySelector(".jfQuestion-fullscreen")&&!$('id_'+opField).querySelector(".jfQuestion-fullscreen").hasClassName("isHidden")){setCalculationListener($('id_'+opField),'click',calc,index);} break;}}});},runAllCalculations:function(ignoreEditable,htmlOnly){JotForm.calculations.forEach(function(calc){if(htmlOnly&&JotForm.getInputType(calc.resultField)!=="html")return;if(!(ignoreEditable&&(!calc.readOnly||calc.readOnly=="0"))&&!!calc.equation){JotForm.checkCalculation(calc);}});},calculationType:function(id){const paymentTypes=['control_stripe','control_stripeCheckout','control_stripeACH','control_stripeACHManual','control_payment','control_paymentwall','control_paypal','control_paypalexpress','control_paypalpro','control_paypalcomplete','control_clickbank','control_2co','control_googleco','control_worldpay','control_onebip','control_authnet','control_dwolla','control_braintree','control_square','control_boxpayment','control_eway','control_bluepay','control_firstdata','control_paypalInvoicing','control_payjunction','control_chargify','control_cardconnect','control_echeck','control_bluesnap','control_payu','control_pagseguro','control_moneris','control_mollie','control_sofort','control_skrill','control_sensepass','control_paysafe','control_iyzico','control_gocardless','control_paypalSPB','control_cybersource','control_payfast'];const field=document.querySelector(`[id="id_${id}"]`) if(field&&field.readAttribute('data-type')&&paymentTypes.includes(field.readAttribute('data-type'))){return field.readAttribute('data-type').replace("control_","");}else if(field&&field.readAttribute('data-type')=='control_matrix'){return'matrix';}else{return JotForm.getInputType(id);}},isTimeObject:function(id){var ndtTimeIDs=['time','hour','min','ampm'];for(var i=0;i=0){return true;}} return false;},runAllCalculationByID:function(field){JotForm.calculations.forEach(calc=>{if(calc&&calc.resultField==field){JotForm.checkCalculation(calc);}});},runRelatedCalculations:function(field){JotForm.calculations.forEach(calc=>{const{operands,baseField}=calc;const fields=operands?operands.split(','):[baseField].filter(Boolean);if(fields.indexOf(field)!==-1){JotForm.checkCalculation(calc);}});},checkCalculation:function(calc,sourceField,sourceEvent){if(!calc.resultField||(calc.hasOwnProperty('conditionTrue')&&!calc.conditionTrue)){return'';} if(JotForm.ignoreInsertionCondition&&!JotForm.replaceTagTest){return;} var result=calc.resultField;var mixedResult=false;if(result.indexOf('|')>-1){var splitResult=result.split('|');var qid=splitResult[0];var fieldId=splitResult[1];if($('id_'+qid)&&$('id_'+qid).getAttribute('data-type')==='control_inline'){mixedResult='id_'+qid;}else{mixedResult='input_'+qid+'_field_'+fieldId;}} var showBeforeInput=(calc.showBeforeInput&&calc.showBeforeInput!="0")?calc.showBeforeInput:false;var ignoreHidden=(calc.ignoreHiddenFields&&calc.ignoreHiddenFields!="0")?calc.ignoreHiddenFields:false;var useCommasForDecimals=(calc.useCommasForDecimals&&calc.useCommasForDecimals!="0")?calc.useCommasForDecimals:false;if(!$('id_'+result)&&!$(mixedResult))return;try{if(!['text','email','textarea','calculation','combined','address','datetime','time','html','authnet','paypalpro','number','radio','checkbox','select','matrix','widget','signature','braintree','stripe','square','eway','bluepay','firstdata','chargify','echeck','payu','pagseguro','moneris','paypal','dwolla','bluesnap','paymentwall','payment','paypalexpress','payjunction','2co','cardconnect','clickbank','onebip','worldpay','rating','hidden','file','other','mixed','sofort','sensepass','paysafe','iyzico','gocardless','stripeACH','paypalSPB','cybersource',"paypalcomplete",'inline','appointment','stripeCheckout','payfast','stripeACHManual','sensepass','birthdate'].include(JotForm.calculationType(result)))return;}catch(e){console.log(e);} var combinedObject={};var getValue=function(data,numeric){var subField="";if(data.indexOf("_")>-1){subField=data.substring(data.indexOf("_"));data=data.substring(0,data.indexOf("_"));} var hasMixedTypeChar=false;if(data.indexOf("|")>-1){hasMixedTypeChar=true;} if(hasMixedTypeChar==false){if($('id_'+data)){if(!$('id_'+data).hasClassName('calculatedOperand')&&showBeforeInput)return'';if(ignoreHidden&&($('id_'+data).hasClassName("form-field-hidden")||($('id_'+data).up(".form-section")&&$('id_'+data).up(".form-section").hasClassName("form-field-hidden")))){return numeric?0:'';}}else if(!$('input_'+data)){return'';}} var type=JotForm.calculationType(data);var val='';switch(type){case'matrix':if($("input_"+data+subField)){var subFieldType=$("input_"+data+subField).type;if(["checkbox","radio"].indexOf(subFieldType)>-1){if($("input_"+data+subField).checked){var chk=$("input_"+data+subField);if(chk.readAttribute('data-calcvalue')){val=chk.readAttribute('data-calcvalue');}else{val=chk.value;}}}else{val=$("input_"+data+subField).value;}}else if($("id_"+data).down('.form-radio')){$$('input[id^="input_'+data+subField+'_"]').each(function(radio){if(radio.checked){val=radio.readAttribute('data-calcvalue')?radio.readAttribute('data-calcvalue'):radio.value;}});} break;case'mixed':var slicedQid;var fieldId;if(data.indexOf('|')>-1){slicedQid=data.split('|');questionId=slicedQid[0];fieldId=slicedQid[1];} var tempInput=$('input_'+questionId+'_field_'+fieldId);if(tempInput&&typeof tempInput.value!=='undefined'){val=tempInput.value;} break;case'2co':case'authnet':case'bluepay':case'bluesnap':case'boxpayment':case'braintree':case'cardconnect':case'chargify':case'clickbank':case'cybersource':case'dwolla':case'echeck':case'eway':case'firstdata':case'gocardless':case'googleco':case'mollie':case'moneris':case'onebip':case'pagseguro':case'payjunction':case'payment':case'paysafe':case'iyzico':case'sensepass':case'paypal':case'paypalexpress':case'paypalSPB':case'paypalpro':case'paypalcomplete':case'paypalInvoicing':case'payu':case'square':case'sofort':case'stripe':case'stripeCheckout':case'stripeACH':case'stripeACHManual':case'worldpay':case'payfast':if($("id_"+data).down('#payment_total')){val=$("id_"+data).down('#payment_total').innerText;}else if($('input_'+data+'_donation')){val=$('input_'+data+'_donation').value;}else if($("id_"+data).down('#payment_recurringpayments')){val=$("id_"+data).down('#payment_recurringpayments').innerText;} if(JotForm.currencyFormat&&JotForm.currencyFormat.dSeparator===","){val=val.replace(/\./g,"").replace(/\,/g,".");} break;case'radio':$$("#id_"+data+' input[type="radio"]').each(function(rad){if(rad.checked){if(rad.readAttribute('data-calcvalue')){val=rad.readAttribute('data-calcvalue');}else{var otherOption=JotForm.getOptionOtherInput(rad);if(typeof FormTranslation!=='undefined'&&otherOption&&otherOption.innerText){val=JotForm.getOptionOtherInput(rad).innerText;}else{val=rad.value;if(typeof FormTranslation!=='undefined'){val=FormTranslation.translate(val);}}}}});break;case'checkbox':var valArr=[];$$("#id_"+data+' input[type="checkbox"]').each(function(chk){if(chk.checked){if(chk.readAttribute('data-calcvalue')){valArr.push(chk.readAttribute('data-calcvalue'));}else{if(typeof FormTranslation!=='undefined'){valArr.push(FormTranslation.translate(chk.value));}else{valArr.push(chk.value);}}}});if(numeric){val=valArr.inject(0,function(accum,thisVal){return accum+(parseFloat(thisVal.replace(/-?([^0-9])/g,"$1").replace(/[^0-9\.-]/g,""))||0);});}else{val=valArr.join(', ');} break;case'select':var optionValue=function(option){if(JotForm.newDefaultTheme&&option.value==='')return'';if(option.textContent)return option.textContent.replace(/^\s+|\s+$/g,'');return option.innerText.replace(/^\s+|\s+$/g,'');};if(numeric)val=0;var tempInput;if(data.indexOf('|')>-1){slicedQid=data.split('|');var questionId=slicedQid[0];var fieldId=slicedQid[1];tempInput=$('input_'+questionId+'_field_'+fieldId);}else{tempInput=$('input_'+data);} tempInput.select('option').each(function(option,ind){var option=tempInput.options[ind];if(option&&option.selected){var current=option.readAttribute('data-calcvalue')?option.readAttribute('data-calcvalue'):optionValue(option);if(numeric){if(/\d/.test(current)){val+=(current==="")?0:parseFloat(current.replace(/[^\-0-9.]/g,""));}else{val+=0;}}else{val+=current;}}});break;case'number':if($$("#id_"+data+' input[type="number"]').length>1){var valArr=[];$$("#id_"+data+' input[type="number"]').each(function(el){valArr.push(el.value);});val=valArr.join(' ');}else{if(!$('input_'+data).value.empty()&&!isNaN($('input_'+data).value)){val=parseFloat($('input_'+data).value);}} break;case'inline':var qid='';var fieldID='';if(data.indexOf('|')>-1){qid=data.split('|')[0];fieldID=data.split('|')[1];var valArr=[];combinedObject={};var TIMESTAMP_OF_2019=1546300000000;var isDate=false;var isTime=false;var selector=Number(fieldID)>TIMESTAMP_OF_2019?'#id_'+qid+' input[id*='+fieldID+'-]'+', select[id*='+fieldID+'-]':'#id_'+qid+' input[id$=-'+fieldID+']'+', select[id$=-'+fieldID+']' $$(selector).each(function(el){if(!el.value.empty()&&(!(['checkbox','radio'].indexOf(el.getAttribute('type'))>-1)||el.checked)){valArr.push(el.value);} var id=el.id.replace(Number(fieldID)>TIMESTAMP_OF_2019?/^[^-]*-/:/-[^-]*$/,'');combinedObject[id]=el.value;if(el&&el.parentNode&&el.parentNode.getAttribute("data-type")==='datebox')isDate=true;if(el&&el.parentNode.parentNode&&el.parentNode.parentNode.getAttribute("data-type")==='timebox')isTime=true;});val=valArr.join(' ');if(isDate){var date=new Date(combinedObject['year_'+qid+'-date'],combinedObject['month_'+qid+'-date']-1,combinedObject['day_'+qid+'-date']);val=date/60/60/24/1000;} if(isTime){var millis=Date.UTC('1970','0','1',combinedObject['hourSelect_'+qid+'_time'],combinedObject['minuteSelect_'+qid+'_time']);val=millis/60/60/1000;}}else{qid=data;var valArr=[];combinedObject={};$$("#id_"+qid+' input[type="text"]').each(function(el){if(!el.value.empty()&&JotForm.isVisible(el)){valArr.push(el.value);} var id=el.id;combinedObject[id]=el.value;});$$("#id_"+qid+' input[type="tel"]').each(function(el){if(!el.value.empty()&&JotForm.isVisible(el)){valArr.push(el.value);} var id=el.id;combinedObject[id]=el.value;});$$("#id_"+qid+' input[type="checkbox"]').each(function(chk){if(chk.checked){if(typeof FormTranslation!=='undefined'){valArr.push(FormTranslation.translate(chk.value));}else{valArr.push(chk.value);}} var id=chk.id;combinedObject[id]=chk.checked?chk.value:'';});val=valArr.join(' ');} break;case'combined':case'grading':var valArr=[];combinedObject={};$$("#id_"+data+' input[type="text"]').each(function(el){if(!el.value.empty()){valArr.push(el.value);} var id=el.id.replace(/_.*/,"");combinedObject[id]=el.value;});$$("#id_"+data+' input[type="tel"]').each(function(el){if(!el.value.empty()){valArr.push(el.value);} var id=el.id.replace(/input_[0-9].*_+/,"");combinedObject[id]=el.value;});val=valArr.join(' ');break;case'datetime':var valArr=[];if(numeric){valArr.push($("month_"+data).value);valArr.push($("day_"+data).value);valArr.push($("year_"+data).value);if(!(JotForm.newDefaultTheme||JotForm.extendsNewTheme)||window.FORM_MODE=='cardform'){$$("#id_"+data+' select').each(function(el){valArr.push(el.value);});}else{$$("#id_"+data+' input,'+"#id_"+data+' select').each(function(el){var splittedID=el.id.split("_");var id=JotForm.isTimeObject(el.id)?splittedID[splittedID.length-1]:el.id.replace(/_.*/,"");if(['hourSelect','minuteSelect','ampm'].indexOf(id)>-1){valArr.push(el.value);}});}}else{$$("#id_"+data+' input[type="tel"]').each(function(el){valArr.push(el.value);var id=el.id.replace(/_.*/,"");combinedObject[id]=el.value;});if(!(JotForm.newDefaultTheme||JotForm.extendsNewTheme)||window.FORM_MODE=='cardform'){$$("#id_"+data+' select').each(function(el){var id=el.id.replace(/_.*/,"");combinedObject[id]=el.value;valArr.push(el.value);});}else{$$("#id_"+data+' input,'+"#id_"+data+' select').each(function(el){if(el.id.indexOf('lite')===-1){var splittedID=el.id.split("_");var id=JotForm.isTimeObject(el.id)?splittedID[splittedID.length-1]:el.id.replace(/_.*/,"");combinedObject[id]=el.value;if(['hourSelect','minuteSelect','ampm'].indexOf(id)>-1){valArr.push(el.value);}}});}} if(numeric){if(!valArr[0].empty()&&!valArr[1].empty()&&!valArr[2].empty()){var hours='';var mins='';var ampm='';if(valArr.length>4&&!valArr[3].empty()&&!valArr[4].empty()){hours=parseInt(valArr[3]);if(valArr.length==6&&!valArr[5].empty()){ampm=valArr[5];if(ampm=='PM'&&hours!=12){hours+=12;}else if(ampm=='AM'&&hours==12){hours=0;}} mins=valArr[4];} var millis=new Date(valArr[2],valArr[0]-1,valArr[1],hours,mins).getTime();val=millis/60/60/24/1000;if(!hours&&!mins){val=Math.ceil(val);}}else{val=0;}}else{if(valArr.length>2&&!valArr[0].empty()&&!valArr[1].empty()&&!valArr[0].empty()){var separator="-";var separatorEl=$$("#id_"+data+" span[class=date-separate]").first();if(separatorEl){separator=separatorEl.innerHTML.replace(/[^\/\-\.]/g,'');} val=valArr[0]+separator+valArr[1]+separator+valArr[2];} if(valArr.length>4&&!valArr[3].empty()&&!valArr[4].empty()){val+=' '+valArr[3]+':'+valArr[4];if(valArr.length==6&&!valArr[5].empty())val+=' '+valArr[5];}} break;case'time':if($('until_'+data)){if($("duration_"+data+"_ampmRange")&&!$("duration_"+data+"_ampmRange").value.empty()){if(numeric){var duration=$("duration_"+data+"_ampmRange").value;if(duration.indexOf(":")>-1){var time=duration.split(":");var hours=time[0]||0;var mins=time[1]||0;var millis=Date.UTC('1970','0','1',hours,mins);val=millis/60/60/1000;}}else{val=$("duration_"+data+"_ampmRange").value;}}else{var res=JotForm.displayTimeRangeDuration(data,true);if(res){var hours=res[0]||0;var mins=res[1]||0;var millis=Date.UTC('1970','0','1',hours,mins);val=numeric?millis/60/60/1000:(hour+":"+mins);if(numeric){break;}}} if($("duration_"+data+"_ampmRange")&&!$("duration_"+data+"_ampmRange").value.empty()){break;}} var valArr=[];combinedObject={};var timeElements=JotForm.newDefaultTheme||JotForm.extendsNewTheme?"#id_"+data+" select,"+"#id_"+data+" input,"+", #id_"+data+" input:not(.form-textbox)":"#id_"+data+" select";if(numeric){$$(timeElements).each(function(el){var isNDTtimeInput=(JotForm.newDefaultTheme||JotForm.extendsNewTheme)&&el.getAttribute('id').indexOf('timeInput')>=0;if(!isNDTtimeInput){valArr.push(el.value);}});var hour='';var mins='';var ampm='';hours=parseInt(valArr[0])||0;if(valArr.length==3&&!valArr[2].empty()){ampm=valArr[2];if(ampm=='PM'&&hours!=12){hours+=12;}else if(ampm=='AM'&&hours==12){hours=0;}} mins=valArr[1];var millis=Date.UTC('1970','0','1',hours,mins);val=millis/60/60/1000;}else{if($("input_"+data+"_hourSelect")&&!$("input_"+data+"_hourSelect").value.empty()&&$("input_"+data+"_minuteSelect")&&!$("input_"+data+"_minuteSelect").value.empty()){val=$("input_"+data+"_hourSelect").value+":"+$("input_"+data+"_minuteSelect").value;if($("input_"+data+"_ampm")){val+=" "+$("input_"+data+"_ampm").value;}} if($("input_"+data+"_hourSelectRange")&&!$("input_"+data+"_hourSelectRange").value.empty()&&$("input_"+data+"_minuteSelectRange")&&!$("input_"+data+"_minuteSelectRange").value.empty()){val+=" - "+$("input_"+data+"_hourSelectRange").value+":"+$("input_"+data+"_minuteSelectRange").value;if($("input_"+data+"_ampmRange")){val+=" "+$("input_"+data+"_ampmRange").value;} if($("duration_"+data+"_ampmRange")&&!$("duration_"+data+"_ampmRange").value.empty()){val+=" ("+$("duration_"+data+"_ampmRange").value+")";}} $$(timeElements).each(function(el){var splittedID=el.id.split("_");var id=splittedID[splittedID.length-1];if(splittedID[0]==='duration'){id='duration-'+id;} combinedObject[id]=el.value;});} break;case'birthdate':var valArr=[];if(numeric){try{var months=$("input_"+data+"_month").value;var days=$("input_"+data+"_day").value;var years=$("input_"+data+"_year").value;var millis=new Date(years,months?months-1:'',days).getTime();val=Math.ceil(millis/60/60/24/1000);}catch(e){console.log("birthdate error");console.log(e);}}else{$$("#id_"+data+' select').each(function(el){valArr.push(el.value);});if(!valArr[0].empty()&&!valArr[1].empty()&&!valArr[2].empty()){val=valArr[0]+' '+valArr[1]+' '+valArr[2];}} break;case'address':var valArr=[];combinedObject={};var inputSelector="#id_"+data+(window.FORM_MODE=='cardform'?' .jfField:not(.isHidden)':'')+' input[type="text"]:not(.jfDropdown-search)';var dropdownSelector="#id_"+data+(window.FORM_MODE=='cardform'?' .jfField:not(.isHidden)':'')+' select';$$(inputSelector).each(function(el){var isDuplicate=false;if(!el.value.empty()&&valArr[0]&&valArr[0].indexOf(el.value)>-1){isDuplicate=true;} if(!el.value.empty()&&!isDuplicate){valArr.push(el.value);} var id=el.id.replace(/input_[0-9].*?_+/,"");combinedObject[id]=el.value;});$$(dropdownSelector).each(function(el){var isDuplicate=false;if(!el.value.empty()&&valArr[0]&&valArr[0].includes(el.value)){isDuplicate=true;} if(!el.value.empty()&&!isDuplicate){valArr.push(el.value);} var id=el.id.replace(/input_[0-9].*_+/,"");combinedObject[id]=el.value;});val=valArr.join(', ');break;case'file':if($$('#id_'+data+' input')[0].readAttribute('multiple')==='multiple'||$$('#id_'+data+' input')[0].readAttribute('multiple')===''){var fileList=$('id_'+data).select('.qq-upload-list li');if(fileList.length>0){val=fileList.reduce(function(acc,elem){return(acc?acc+', ':'')+elem.getAttribute('actual-filename');},'');}}else{val=$('input_'+data).value;val=val.substring(val.lastIndexOf("\\")+1);} break;case'textarea':if($('input_'+data)&&typeof $('input_'+data).value!=='undefined'){val=$('input_'+data).value;var rich=$('id_'+data).down('.nicEdit-main');if(rich){val=val.stripTags().replace(/\s/g,' ').replace(/ /g,' ');}} break;case'widget':var widgetType=JotForm.getWidgetType(data);switch(widgetType){case"timer":case"fancyTimer":if(numeric){val=$('input_'+data).value;}else{var seconds=$('input_'+data).value;var minutes=Math.floor(seconds/60);seconds=seconds-(minutes*60);seconds=JotForm.addZeros(seconds,2);val=minutes+":"+seconds;} break;case"configurableList":case"dynMatrix":var br=JotForm.calculationType(result)==="html"?"
":"\n";var json=$('input_'+data).value;if(numeric){val=0;} try{json=JSON.parse(json);for(var i=0;i0){val+=valArr.join(",")+br;}}}catch(e){console.log($('input_'+data).value);console.log(calc);} break;case"giftRegistry":val=$('input_'+data).value;if(JotForm.calculationType(result)==="html"){val=val.replace(/\n/g,"
");} break;case"inventory":case"inventoryV2":val=$('input_'+data).value;if(val){var valArr=val.split('\n');val=valArr[0];if(numeric&&isNaN(valArr[0])){val=valArr[0].match(/ \[(\d+)\]$/)[1];}} break;case"imagelinks":case"links":var br=JotForm.calculationType(result)==="html"?"
":"\n";var json=JSON.parse($('input_'+data).value).widget_metadata.value;for(var i=0;i';}else{val+=''+(showName?json[i].name:json[i].url)+'';}}else{val+=showName?json[i].name+": ":"";val+=json[i].url+br;}} break;case"htmltext":var b64=JSON.parse($('input_'+data).value).widget_metadata.value;val=window.atob?window.atob(b64):"";if(JotForm.calculationType(result)!=="html"){val=val.strip().replace(/
/g,"\n").stripTags().replace(/ /g,' ');} break;case"drivingDistance":val=$('input_'+data).value;if(val.indexOf("Distance")>-1){var matches=val.match(/Distance(.*)/);if(matches.length>1){val=matches[1];}} break;case"pickers":var val=$('input_'+data).value;if(numeric&&$('customFieldFrame_'+data).src.indexOf('datepicker.html')!==-1){var valArr=val.split("/");var millis=Date.UTC(valArr[2],valArr[0]-1,valArr[1],0,0);val=millis/60/60/24/1000;} break;case"ios7Date":var val=$('input_'+data).value;if(numeric&&val){var valArr=val.split("/");var millis=Date.UTC(valArr[2],valArr[0]-1,valArr[1],0,0);val=millis/60/60/24/1000;} break;case"datesDifference":widgetSettings=$('widget_settings_'+data).value;if(widgetSettings){var settingsData=JSON.parse(decodeURIComponent(widgetSettings));for(var j=0;j2){var millis=Date.UTC(args[0],args[1]-1,args[2]);out+=millis/60/60/24/1000;}}else if(specOp==='nth'){var n=args[0];args=args.splice(1);args=args.sort(function(a,b){if(parseFloat(a)>parseFloat(b))return 1;if(parseFloat(b)>parseFloat(a))return-1;return 0;});args=args.reverse();out+=args[parseFloat(n)-1];}else if(specOp==='avg'||specOp==='avgNoZero'){var len=sum=0;for(var j=0;j0){len++;sum+=parseFloat(args[j]);}} out+=specOp==='avg'?sum/args.length:sum/len;}else if(specOp==='count'){var field=originalArgs[0];field=field.replace(/[\{\}]/g,'');var type=JotForm.getInputType(field);var len=$$("#id_"+field+' input[type="'+type+'"]:checked').length;out+=len;}else if(specOp==='commaSeparate'){if(typeof args[0]=="number"){args[0]=args[0].toFixed(calc.decimalPlaces);var parts=args[0].toString().split(".");parts[0]=parts[0].replace(/\B(?=(\d{3})+(?!\d))/g,",");out+=parts.join(".");}else{out+=args[0];}}else if(specOp==='addDays'||specOp==='subtractDays'){function isValidDate(d){return d instanceof Date&&!isNaN(d);} var date=isValidDate(new Date(args[0]*24*60*60*1000))?new Date(args[0]*24*60*60*1000):new Date(args[0]);date.setHours(0,0,0);date.setMinutes(0,0,0);if(specOp==='addDays'){date.setDate(date.getDate()+args[1]);} if(specOp==='subtractDays'){date.setDate(date.getDate()-args[1]);} if(!isValidDate(date)){return;} if(JotForm.getInputType(calc.resultField)!=="datetime"){out+=getStringDate(date);}else{out+=date.getTime();} return out;}else{var tempValue=acceptableFunctions[specOp].apply(undefined,args);if(specOp==='pow'){if(typeof BigInt==='function'&&tempValue>Number.MAX_SAFE_INTEGER){tempValue=BigInt(tempValue).toString();}else if(tempValue<1&©Zero){tempValue=tempValue.toFixed(calc.decimalPlaces);}else{}} out+=tempValue;}}else if(specOp==='random'){out+=Math.random();}else{out+=acceptableFunctions[specOp];}}catch(e){console.log(e);}}else if(character==='{'){var end=equation.indexOf('}',i);var qid=equation.substring(i+1,end);try{var val=getValue(qid,numeric);if(numeric&&typeof val!=='number'&&(val.indexOf('(')==-1&&val.indexOf(')')==-1)){val=Number(val)||0;}}catch(e){console.log("error catching value");console.log(e);} if(val===''&&numeric)return false;out+=val;i+=end-i;}else{out+=character;}} return out;};var output=calculate(calc.equation);if(!(typeof output=="string"&&output.length>1)&&((typeof calc.allowZeroCopy==='string'?calc.allowZeroCopy!=='1':!calc.allowZeroCopy)&&parseFloat(output)===0)&&$('input_'+result)&&($('input_'+result).readAttribute('defaultValue')!=null||$('input_'+result).readAttribute('data-defaultvalue')!=null)){output=$('input_'+result).readAttribute('defaultValue')||$('input_'+result).readAttribute('data-defaultvalue');} var resultFieldType=calc.isLabel?"html":JotForm.calculationType(result);if(JotForm.ignoreInsertionCondition&&JotForm.replaceTagTest&&(resultFieldType!=='html'&&resultFieldType!=='inline')){return;} switch(resultFieldType){case"inline":if(result.indexOf('|')>-1){var idPatcher={addr_line1:'streetaddress',addr_line2:'addressline2',postal:'zip'};var selectFieldId=["country"];var splitResult=result.split('|');var qid=splitResult[0];var fieldId=splitResult[1];var TIMESTAMP_OF_2019=1546300000000;var isNewIDType=Number(fieldId)>TIMESTAMP_OF_2019;var selector=isNewIDType?'#id_'+qid+' input[id*='+fieldId+'-]':'#id_'+qid+' input[id$=-'+fieldId+']';var resultFields=$$(selector);var hasCombinedField=false;Object.keys(combinedObject).forEach(function(id){var patchedId=idPatcher[id]?idPatcher[id]:id;var selectInput=selectFieldId.indexOf(patchedId)>-1?'select':'input';var selector=isNewIDType?'#id_'+qid+' input[id*='+fieldId+'-'+id+']':'#id_'+qid+' '+selectInput+'[id*='+patchedId+'][id$=-'+fieldId+']';var visibleFields=$$(selector).filter(function(field){return JotForm.isVisible(field)||field.id.indexOf('lite_mode'>-1);});if(visibleFields[0]&&(isNaN(output)&&output.indexOf(combinedObject[id])>-1)){hasCombinedField=true;visibleFields[0].value=combinedObject[id];visibleFields[0].triggerEvent('blur');}});if(!hasCombinedField&&resultFields[0]){if(resultFields[0].parentNode.getAttribute("data-type")==="datebox"){var date=new Date(output*60*60*24*1000);JotForm.formatDate({date:date,dateField:$("lite_mode_"+qid+"-date-"+fieldId)});} else if(resultFields[0].value!==output){resultFields[0].value=output;resultFields[0].triggerEvent('change');}} break;} case"html":JotForm.runReplaceTag(calc,combinedObject,output,result,resultFieldType);break;case"address":case"authnet":case"paypalpro":case"combined":case"braintree":case"stripe":for(var inputId in combinedObject){if(inputId!==""){if($('id_'+result).select('input[id*='+inputId+'], select[id*='+inputId+']').length>0){var fieldInputElement=$('id_'+result).select('input[id*='+inputId+'], select[id*='+inputId+']').first() if(calc.baseField&&$('id_'+calc.baseField).readAttribute('data-type')==="control_fullname"){$('id_'+result).select('input[id*='+inputId+'], select[id*='+inputId+']').each(function(value){if(value.readAttribute('data-component')=='cc_firstName'){fieldInputElement=value;} if(value.readAttribute('data-component')=='cc_lastName'){fieldInputElement=value;}});} fieldInputElement.value=combinedObject[inputId];if(resultFieldType=='address'&&window.FORM_MODE=='cardform'){var parentElement=fieldInputElement.parentElement;if(parentElement.querySelector('input')){parentElement.querySelector('input').value=combinedObject[inputId];}else if(parentElement.querySelector('select')){parentElement.querySelector('select').value=combinedObject[inputId];parentElement.querySelector(".jfDropdown-chip.isSingle").innerText=combinedObject[inputId];}} if(combinedObject[inputId]){fieldInputElement.parentNode.addClassName('isFilled');}}}} if($('input_'+result+'_full')&&$('input_'+result+'_full').readAttribute("masked")=="true"){JotForm.setQuestionMasking('#input_'+result+'_full',"textMasking",$('input_'+result+'_full').readAttribute("maskValue"));} break;case"time":case"datetime":var setTimeValues=function(date){var hour=date.getHours();var minute=JotForm.addZeros(date.getMinutes(),2);if(!isNaN(hour)&&!isNaN(minute)){var ampmField=$('input_'+result+'_ampm')||$('ampm_'+result);if(ampmField){ampmField.value=hour>=12?'PM':'AM';hour=hour%12||12;ampmField.triggerEvent('change');} var hourSelect=$("input_"+result+"_hourSelect")||$("hour_"+result);if(hourSelect){if(!ampmField) hour=JotForm.addZeros(hour,2);hourSelect.value=hour;hourSelect.triggerEvent('change');} var minuteSelect=$("input_"+result+"_minuteSelect")||$("min_"+result);if(minuteSelect){if(minuteSelect.options){var roundedMinute='00';for(var i=0;i=minute){break;}} minute=roundedMinute;} minuteSelect.value=minute;minuteSelect.triggerEvent('change');} var timeInput=$('input_'+result+'_timeInput');if(timeInput){var calculatedHour=hour.toString().length===1?'0'+hour:hour;calculatedHour=calculatedHour==0?'12':calculatedHour;timeInput.value=calculatedHour+":"+minute;timeInput.triggerEvent('change');}}};if(combinedObject&&"year"in combinedObject||resultFieldType==='time'){if(output.length===13){output=parseFloat(output,10);var date=new Date(output);setTimeValues(date);}else{var dateObject=new Date(output);if(dateObject.getTime()&&resultFieldType==='time'){setTimeValues(dateObject);}else{for(var inputId in combinedObject){if(JotForm.isTimeObject(inputId)){var ndtTimeQuery=$('id_'+result).select('input[id*=input_'+result+'_'+inputId+'], select[id*=input_'+result+'_'+inputId+']');var targetTimeObject=JotForm.newDefaultTheme&&ndtTimeQuery.length>0?ndtTimeQuery.first():'';var ldtTimeQuery=$('id_'+result).select('input[id*='+inputId+'], select[id*='+inputId+']');targetTimeObject=!JotForm.newDefaultTheme&&ldtTimeQuery.length>0?ldtTimeQuery.first():targetTimeObject;var cardFormTimeQuery=$('id_'+result).select('input[id*='+inputId+'_'+result+'], select[id*='+inputId+'_'+result+']');targetTimeObject=window.FORM_MODE=='cardform'&&cardFormTimeQuery.length>0?cardFormTimeQuery.first():targetTimeObject;targetTimeObject.value=combinedObject[inputId];if(inputId==='duration-ampmRange'){var durationSplittedIds=inputId.split("-");var durationAmpmRangeQuery=$('id_'+result).select('input[id*='+durationSplittedIds[0]+'_'+result+'_'+durationSplittedIds[1]+'], select[id*='+durationSplittedIds[0]+'_'+result+'_'+durationSplittedIds[1]+']');targetTimeObject=JotForm.newDefaultTheme&&durationAmpmRangeQuery.length>0?durationAmpmRangeQuery.first():targetTimeObject;targetTimeObject.value=combinedObject[inputId];JotForm.displayTimeRangeDuration(result,false);} if(window.FORM_MODE=='cardform'){var tempInputID=inputId.indexOf('Range')>=0?inputId.replace('Range','')+'-range':inputId;tempInputID=tempInputID.indexOf('Select')>=0?tempInputID.replace('Select',''):tempInputID;var dataType=resultFieldType==='time'?'data-type*="'+'time-'+tempInputID+'"':'data-type*="'+inputId+'"';var dateQuery=$('id_'+result).select('div[class*=jfField]['+dataType+']');for(var i=0;i0?dateQuery.first():'';targetDateEl.value=combinedObject[inputId];}}}}}else{try{if((typeof output=="number"&&output>0)||(typeof output=="string"&&output.replace(/\s/g,"").length>0&&output!=="0")){if(!isNaN(output)){if(output.length===13){output=parseFloat(output,10);}else{output=Math.round(output*60*60*24*1000);}} var date=new Date(typeof output==='string'?output.replace(/(\-|\.)/g,'/'):output);var year=date.getFullYear();var month=JotForm.addZeros(date.getMonth()+1,2);var day=JotForm.addZeros(date.getDate(),2);if($('input_'+result)){$('input_'+result).value=year+'-'+month+'-'+day;if(!isNaN(year))$$('#cid_'+result+' .jfField[data-type="year"] input')[0].value=year;if(!isNaN(month))$$('#cid_'+result+' .jfField[data-type="month"] input')[0].value=month;if(!isNaN(day))$$('#cid_'+result+' .jfField[data-type="day"] input')[0].value=day;}else{if(!isNaN(year))$("year_"+result).value=year;if(!isNaN(month))$("month_"+result).value=month;if(!isNaN(day))$("day_"+result).value=day;} setTimeValues(date);}}catch(e){console.log(e);}} if($('lite_mode_'+result)){var date=new Date($("year_"+result).value,($("month_"+result).value-1),$("day_"+result).value);if(date.getTime()){JotForm.formatDate({date:date,dateField:$('id_'+result)});}} break;case"number":var lastCommaIndex=output.lastIndexOf(',');if(lastCommaIndex>-1&&lastCommaIndex===output.length-calc.decimalPlaces-1){output=output.substring(0,lastCommaIndex)+"."+output.substring(lastCommaIndex+1);} output=output.replace(/[^\-0-9\.]/g,"");$('input_'+result).value=output;var parent=$('input_'+result).parentElement;if(window.FORM_MODE=='cardform'&&parent&&!parent.hasClassName('isFilled')){parent.addClassName('isFilled');} break;case"radio":var sources=$$('#id_'+calc.operands+' input[type="radio"]:checked');var outputs=sources.length?sources.collect(function(out){if(out.value){return out.value;}}):output.strip();var radios=$$("#id_"+result+' input[type="radio"]');$A(radios).each(function(rad){rad.checked=false;if(typeof outputs==='string'){if(rad.value==output.strip()){rad.checked=true;}}else{if(rad.value==output.strip()||outputs.include(rad.value)){rad.checked=true;}}});break;case"checkbox":var sources=$$('#id_'+calc.operands+' input[type="checkbox"]:checked');var outputs=sources.length?sources.collect(function(out){var dataCalcValue=out.getAttribute('data-calcvalue') if(dataCalcValue){return dataCalcValue} return typeof out.value==='string'?out.value.strip():out.value;}):output.strip();var checks=$$("#id_"+result+' input[type="checkbox"]');var toBeChecked=[];var calcBaseInputs=$$('[id^=input_'+calc.baseField+'_') var calcBaseIsRadio=calcBaseInputs.length&&calcBaseInputs[0].type==='radio';if(calcBaseIsRadio){var calcBaseInputValues=[] if('{'+calc.baseField+'}'===calc.equation){calcBaseInputValues=calcBaseInputs.map(function(calcBaseInput){if(calcBaseInput.dataset.calcvalue){return calcBaseInput.dataset.calcvalue;}else{return calcBaseInput.value;}});}else{var tempCalcs=JotForm.calculations;calcBaseInputValues=tempCalcs.filter(function(c){return c.baseField===calc.baseField&&c.resultField===calc.resultField;}).map(function(calcBaseInput){return calcBaseInput.equation;});} toBeChecked=checks.filter(function(check){return check.checked===true&&!calcBaseInputValues.include(check.value);});} $A(checks).each(function(chk){if(!JotForm.defaultValues[chk.id]){chk.checked=false;} if(typeof outputs==='string'&&calcBaseIsRadio&&outputs===chk.value){chk.checked=true;}else{const checkValue=chk.getAttribute('data-calcvalue')||chk.value;if(outputs.include(checkValue)){chk.checked=true;}}});toBeChecked.forEach(function(input){input.checked=true;});break;case"select":try{var source=$$('#id_'+calc.operands+' select');var out=(source[0]?source[0].value:output);var stripped=(/\s$/).test(out)?out.strip()+' ':out.strip();if(result.indexOf('|')>0){$('input_'+result.split('|').join('_field_')).setValue(stripped);}else{$('input_'+result).setValue(stripped);} break;}catch(error){console.log(error);} case"matrix":if("resultSubField"in calc){if($(calc.resultSubField)){$(calc.resultSubField).value=output;}} break;case"textarea":output=output.replace(/
|/gi,"\r\n");if(output&&output.length>0){$('input_'+result).removeClassName('form-custom-hint').removeAttribute('spellcheck');} var richAreaSelector=window.FORM_MODE=='cardform'?"#input_"+result+"_editor":".nicEdit-main" var richArea=$("id_"+result).down(richAreaSelector);if(richArea){richArea.innerHTML=output;richArea.setStyle({'color':''});} $('input_'+result).value=output;break;case"mixed":if($(mixedResult)){$(mixedResult).value=output;var parent=$(mixedResult).up();if(window.FORM_MODE=='cardform'&&parent&&!parent.hasClassName('isFilled')){parent.addClassName('isFilled');}} break;case"email":if($('input_'+result)){$('input_'+result).value=output;} var parent=$('input_'+result).parentElement;if(window.FORM_MODE=='cardform'&&parent&&!parent.hasClassName('isFilled')){parent.addClassName('isFilled');} break;case"appointment":var parsedOutput=calc.conditionTrue?parseInt(output):false;setTimeout(function(){if(calc.resultFieldProp==='startdate'){JotForm.appointments[result].forceStartDate(parsedOutput,calc.equation);} if(calc.resultFieldProp==='enddate'){JotForm.appointments[result].forceEndDate(parsedOutput);}},100);break;default:try{if($('input_'+result)&&$('input_'+result).hinted===true){$('input_'+result).clearHint();} if($('input_'+result)){if((calc.equation==='0'||calc.equation==='[0]')&&resultFieldType==='text'){$('input_'+result).value='0';}else{$('input_'+result).value=output;}} if($('input_'+result)&&output&&output.length===0&&$('input_'+result).hintClear){$('input_'+result).hintClear();} if($('input_'+result)&&$('input_'+result).readAttribute("data-masked")=="true"){JotForm.setQuestionMasking("#input_"+result,"textMasking",$('input_'+result).readAttribute("maskValue"));} if(resultFieldType==='widget'){var widgetEl=$('input_'+result);var iframe=document.getElementById('customFieldFrame_'+result);if(widgetEl&&iframe){if($(iframe).hasClassName('frame-xd-ready')){widgetEl.fire('widget:populate',{qid:result,value:output});widgetEl.triggerEvent('change');var clientID=iframe.getAttribute('data-client-id');JotForm.makeForceReloadWidgets(clientID,result);}else{iframe.addEventListener('load',function(){widgetEl.fire('widget:populate',{qid:result,value:output});widgetEl.triggerEvent('change');});}}} break;}catch(error){console.log(error);}} var infiniteLoop=function(){var checkVal=typeof output==='object'?JSON.stringify(output):output;var checkField=calc.resultSubField||calc.resultField;if(!("__antiLoopCache"in window)){window.__antiLoopCache={};} if(window.__antiLoopCache[checkField]===checkVal){return true;} window.__antiLoopCache[checkField]=checkVal;return false;} var calculationInfiniteLoop=function(){var timestamp=new Date().getTime();var msPart=timestamp%1000;if(msPart<500){msPart="0";}else{msPart="1";} var secPart=parseInt(timestamp/1000);var antiLoopKey=(calc.id||calc.resultField)+'-'+secPart+'-'+msPart;var maxLoopSize=19;window.lastCalculationTimeStamp=window.lastCalculationTimeStamp||new Date().getTime();var betweenLookUp=(timestamp-window.lastCalculationTimeStamp)/1000;if(betweenLookUp>10){window.__antiCalculationLoopCache={};window.lastCalculationTimeStamp=null;} if(!("__antiCalculationLoopCache"in window)){window.__antiCalculationLoopCache={};} if(antiLoopKey in window.__antiCalculationLoopCache){window.__antiCalculationLoopCache[antiLoopKey]++;if(window.__antiCalculationLoopCache[antiLoopKey]>maxLoopSize){return true;}}else{window.__antiCalculationLoopCache[antiLoopKey]=1;} return false;} const ignoreFields=['time','datetime','text'];const operands=(calc.operands&&calc.operands.split(','))||[];const baseFieldsForLoop=(calc.baseField&&calc.baseField.split(','))||[];const ignoreFieldCalculationLoopCheck=Boolean(([...baseFieldsForLoop,...operands]).find(operand=>ignoreFields.includes(JotForm.getInputType(operand))));const checkCalculationInfiniteLoop=this.loopMapExist||ignoreFieldCalculationLoopCheck;if(checkCalculationInfiniteLoop&&(infiniteLoop()||calculationInfiniteLoop())){if(JotForm.isConditionDebugMode){var index=JotForm.calculations.findIndex(val=>val===calc);console.log({calc:calc,sourceField:sourceField,index},'IN CHECK CALCULATION');if(typeof __conditionDebugger_logStatus==='function'){__conditionDebugger_logStatus([{title:'Loop Detected In',value:`Calculation-${index}`}]);}} return;} if(!mixedResult&&$('id_'+result).hasClassName("form-line-error")){$('id_'+result).select("select[class*='required'], textarea[class*='required'], input[class*='required']").each(function(el){if(el.validateInput){el.validateInput();}});} var triggerMe;var eventType;if(resultFieldType=="checkbox"||resultFieldType=="radio"){eventType="change";triggerMe=$('id_'+result)}else if(resultFieldType=="select"){eventType="change";if(result.indexOf('|')>0){if($('input_'+result.split('|').join('_field_'))){triggerMe=$('input_'+result.split('|').join('_field_'));}}else{if($('input_'+result)){triggerMe=$('input_'+result);}}}else if(resultFieldType=="mixed"){eventType="change";if(result.indexOf('|')>0){triggerMe=$('input_'+result.split('|').join('_field_'));}}else if(resultFieldType==='inline'){return;} else{eventType="keyup";if($(mixedResult)){triggerMe=$(mixedResult);}else if(!calc.isLabel){triggerMe=$('input_'+result)?$('input_'+result):$('id_'+result).select('input').first();}} var sourceFieldElement=sourceField&&$(sourceField);var preventRetriggerItself=sourceEvent&&sourceFieldElement&&sourceFieldElement.contains(triggerMe)&&eventType===sourceEvent;if(preventRetriggerItself)return;if(!triggerMe)return;if(document.createEvent){var evt=document.createEvent('HTMLEvents');evt.initEvent(eventType,true,true);triggerMe.dispatchEvent(evt);} if(triggerMe.fireEvent){triggerMe.fireEvent('on'+eventType);}},calcParanthesesBalance:function(str){var openPar=(str.match(/\(/g)||[]).length;var closePar=(str.match(/\)/g)||[]).length;return openPar===closePar;},getWidgetType:function(qid){try{const el=document.querySelector(`#id_${qid}`) if(!(el||el.querySelector('iframe')))return false;if(document.querySelector(`#input_${qid}`).value.indexOf("widget_metadata")>1){return JSON.parse(document.querySelector(`#input_${qid}`).value).widget_metadata.type;} const iframe=el.querySelector('iframe');const src=iframe.src const offlineReg=new RegExp('^file://.*/(.*?)/index.html');const offlineWidgetMatch=offlineReg.exec(src);if(offlineWidgetMatch){return offlineWidgetMatch[1]} const reg=new RegExp('jotform.io/(.*)/');const widget=reg.exec(src);if(!widget||widget.length<2||!widget[1])return false;return widget[1];}catch(e){console.error("get widget type error");return false;}},widgetsWithConditions:[],triggerWidgetCondition:function(id){if(JotForm.widgetsWithConditions.include(id)){if(document.createEvent){var evt=document.createEvent('HTMLEvents');evt.initEvent('change',true,true);$('input_'+id).dispatchEvent(evt);}else if($('input_'+id).fireEvent){return $('input_'+id).fireEvent('onchange');}}},getChecklistWidgetValues:function(data){var checkedPrefix="CHECKED: ";var uncheckedPrefix="UNCHECKED: ";var val=$('input_'+data).value;var itemLines=val.split(/\r\n|\r|\n/g);var checklistValue=itemLines.reduce(function(result,line){line=line.trim();if(line.indexOf(checkedPrefix)===0){result.checked.push(line.slice(checkedPrefix.length));}else if(line.indexOf(uncheckedPrefix)===0){result.unchecked.push(line.slice(uncheckedPrefix.length));}else{result.checked.push(line);} return result;},{checked:[],unchecked:[]});return checklistValue;},getFieldIdFromFieldRef:function(ref){try{if(typeof ref==="string"&&ref.indexOf("{")>-1&&ref.indexOf("}")>-1){const stripped=ref.strip().replace(/[\{\}]/g,"");let inputs=document.querySelectorAll('input[name*="_'+stripped+'["\],select[name*="_'+stripped+'\["]') if(!inputs||inputs.length==0){inputs=document.querySelectorAll('input[name*="_'+stripped+'"],select[name*="_'+stripped+'"]');} if(inputs.length>0){const field=inputs[0].closest(".form-line");if(field){return field.id.replace(/.*id_/,"");}}}}catch(e){console.log(e);} return false;},setConditionEvents:function(){try{$A(JotForm.conditions).each(function(condition){if(condition.disabled==true)return;if(condition.type=='field'||condition.type=='calculation'||condition.type=='require'||condition.type=='mask'||($A(condition.action).length>0&&condition.action.first().skipHide==='hidePage')){var fields=[];var keys={};$A(condition.terms).each(function(term){term.field=String(term.field);if(typeof term.value==='boolean'){term.value=String(term.value);} var tempField='';if(term.field.indexOf('|')>-1){var fieldSplit=term.field.split('|');if($('id_'+fieldSplit[0])&&$('id_'+fieldSplit[0]).readAttribute('data-type')=="control_inline"){tempField=term.field;}else{tempField=fieldSplit[0]+'_field_'+fieldSplit[1];}}else{tempField=term.field;} var key=term.operator+'|'+term.field;if(!keys[key]){keys[key]=true;fields.push(tempField);} var otherFieldRef=JotForm.getFieldIdFromFieldRef(term.value) if(otherFieldRef){fields.push(otherFieldRef);}});$A(fields).each(function(id){var inputTypeTemp=JotForm.getInputType(id);switch(inputTypeTemp){case"widget":case"signature":JotForm.setFieldConditions('input_'+id,'change',condition);JotForm.widgetsWithConditions.push(id);break;case"combined":case"email":if(id.indexOf('_field_')>-1){JotForm.setFieldConditions('input_'+id,'autofill',condition);}else{JotForm.setFieldConditions('id_'+id,'autofill',condition);} break;case"address":JotForm.setFieldConditions('id_'+id,'autofill',condition);JotForm.setFieldConditions('input_'+id+'_country','change',condition);JotForm.setFieldConditions('input_'+id+'_state','change',condition);break;case"datetime":JotForm.setFieldConditions('id_'+id,'date:changed',condition);break;case"birthdate":JotForm.setFieldConditions('input_'+id+'_day','change',condition);JotForm.setFieldConditions('input_'+id+'_month','change',condition);JotForm.setFieldConditions('input_'+id+'_year','change',condition);break;case"time":JotForm.setFieldConditions('input_'+id+'_hourSelect','change',condition);JotForm.setFieldConditions('input_'+id+'_minuteSelect','change',condition);JotForm.setFieldConditions('input_'+id+'_ampm','change',condition);case"select":case"file":if($('input_'+id)){JotForm.setFieldConditions('input_'+id,'change',condition);}else{$('id_'+id).select('select').each(function(el){JotForm.setFieldConditions(el.id,'change',condition);});} break;case"checkbox":case"radio":JotForm.setFieldConditions('id_'+id,'change',condition);break;case"number":JotForm.setFieldConditions('input_'+id,'number',condition);break;case"autocomplete":JotForm.setFieldConditions('input_'+id,'autocomplete',condition);break;case"grading":JotForm.setFieldConditions('id_'+id,'keyup',condition);break;case"text":case"textarea":JotForm.setFieldConditions('input_'+id,'autofill',condition);break;case"hidden":if($('input_'+id+"_donation")){JotForm.setFieldConditions('input_'+id+"_donation",'keyup',condition);}else{JotForm.setFieldConditions('input_'+id,'keyup',condition);} break;case"mixed":if(id.indexOf('_field_')>-1){var idSplit=id.split('_field_');var tempQid=idSplit[0];var tempQuestion;this.CardLayout.layoutParams.allQuestions.forEach(function(question){if(question.id==tempQid){tempQuestion=question;}});if(tempQuestion&&tempQuestion.fields){tempQuestion.fields.forEach(function(field){var tempSelector='input_'+tempQid+'_field_'+field.fieldID;JotForm.setFieldConditions(tempSelector,'change',condition);JotForm.widgetsWithConditions.push(tempSelector);});}} break;case"inline":var fieldSplit=id.split('|');var qid=fieldSplit[0];var tempSelector='id_'+qid;JotForm.setFieldConditions(tempSelector,'change',condition);break;default:JotForm.setFieldConditions('input_'+id,'keyup',condition);}});}else{$A(condition.terms).each(function(term){var id=term.field.toString();if(id.indexOf("_")!==-1){id=id.split("_")[0];} if(id.indexOf("|")!==-1){id=id.split("|")[0];} if(!$('id_'+id)){return;} var nextButton;if(window.FORM_MODE==='cardform'){nextButton=$('id_'+id).select('.forNext')[0];}else{nextButton=JotForm.getSection($('id_'+id)).select('.form-pagebreak-next')[0];} if(!nextButton){return;} nextButton.observe('mousedown',function(){JotForm.checkCondition(condition,nextButton.id,'mousedown');});});}});$H(JotForm.fieldConditions).each(function(pair){var field=pair.key;var event=pair.value.event;var conds=pair.value.conditions;if(!$(field)){return;} if(event=="autocomplete"){$(field).observe('blur',function(){$A(conds).each(function(cond){JotForm.checkCondition(cond,field,'blur');});}).run('blur');$(field).observe('keyup',function(){$A(conds).each(function(cond){JotForm.checkCondition(cond,field,'keyup');});}).run('keyup');}else if(event=="number"){$(field).observe('change',function(){$A(conds).each(function(cond){JotForm.checkCondition(cond,field,'change');});}).run('change');$(field).observe('keyup',function(){$A(conds).each(function(cond){JotForm.checkCondition(cond,field,'keyup');});}).run('keyup');}else if(event=="autofill"){$(field).observe('blur',function(){$A(conds).each(function(cond){JotForm.checkCondition(cond,field,'blur');});}).run('blur');$(field).observe('keyup',function(){$A(conds).each(function(cond){JotForm.checkCondition(cond,field,'keyup');});}).run('keyup');if(!(!Prototype.Browser.IE9&&!Prototype.Browser.IE10&&Prototype.Browser.IE)){$(field).observe('change',function(){$A(conds).each(function(cond){JotForm.checkCondition(cond,field,'change');});}).run('change');}}else{$(field).observe(event,function(){$A(conds).each(function(cond){JotForm.checkCondition(cond,field,event);});});if(!$(field).id.match(/input_[0-9]+_quantity_[0-9]+_[0-9]+/)){$(field).run(event);}else{JotForm.runConditionForId(field.replace('input_',''));}}});}catch(e){JotForm.error(e);}},setFieldsToPreserve:function(preset){const gateways=["braintree","dwolla","stripe","paypal","paypalpro","paypalexpress","authnet"];const paymentElements=document.querySelectorAll('input[name="simple_fpc"]') const getPaymentFields=paymentElements.length>0&&gateways.indexOf(paymentElements[0].getAttribute('data-payment_type'))>-1;const paymentExtras=[{type:"phone",pattern:/Phone|Contact/i},{type:"email",pattern:/email|mail|e-mail/i},{type:"company",pattern:/company|organization/i}];const eligibleFields=document.querySelectorAll('.form-line[data-type*="email"],'+'.form-line[data-type*="textbox"],'+'.form-line[data-type*="phone"],'+'.form-line[data-type*="dropdown"],'+'.form-line[data-type*="radio"]');const sortedFields=Array.from(eligibleFields).sort(function(a,b){return Number(a.id.replace("id_",""))-Number(b.id.replace("id_",""));});const paymentFieldsToPreserve={};sortedFields.forEach(function(field){const fieldId=field.id.replace('id_','');const fieldName=field.querySelector('input, select').name.replace(/q\d+_/,"");const fieldType=field.getAttribute('data-type').replace('control_','');if(getPaymentFields&&Object.keys(paymentFieldsToPreserve).length<3){paymentExtras.forEach(function(extra){if(fieldType=='textbox'||fieldType==extra.type){const label=field.querySelector('label').innerHTML.strip();if(extra.pattern.exec(label)&&!paymentFieldsToPreserve[extra.type]){paymentFieldsToPreserve[extra.type]=fieldId;if(JotForm.fieldsToPreserve.indexOf(fieldId)===-1){JotForm.fieldsToPreserve.push(fieldId);}}}});} if(preset&&JotForm.fieldsToPreserve.indexOf(fieldId)&&(preset.indexOf(fieldName)>-1||preset.indexOf(fieldId)>-1)) {JotForm.fieldsToPreserve.push(fieldId);}});},changePaymentStrings:function(text){const couponHeader=document.querySelector('#coupon-header');const shippingText=document.querySelector('#shipping-text');const taxText=document.querySelector('#tax-text');const subTotalText=document.querySelector('#subtotal-text');const totalText=document.querySelector('#total-text');if(couponHeader&&text.couponEnter){couponHeader.innerHTML=text.couponEnter;} if(shippingText&&text.shippingShipping){shippingText.innerHTML=text.shippingShipping;} if(taxText&&text.taxTax){taxText.innerHTML=text.taxTax;} if(subTotalText&&text.totalSubtotal){subTotalText.innerHTML=text.totalSubtotal;} if(totalText&&text.totalTotal){totalText.innerHTML=text.totalTotal;}},handleSubscriptionPrice:function(){if(navigator.userAgent.toLowerCase().indexOf('safari/')>-1){document.querySelectorAll('.form-product-custom_price').forEach(function(inp){inp.onclick=function(e){e.preventDefault();};})} const inputs=document.querySelectorAll('input[data-price-source]');if(inputs.length<1){return;} const priceSources=[];const events={};inputs.forEach(function(inp){var sourceId=inp.getAttribute('data-price-source');var source=document.querySelector('#input_'+sourceId);if(!source){return;} if(!events[sourceId]){events[sourceId]=[];} const getVal=function(){let val=source.value;if(typeof val!=='number'){val=val.replace(/[^0-9\.]/gi,"");} return!isNaN(val)&&val>0?val:0;} priceSources.push(source);events[sourceId].push(function(){inp.value=getVal();});});priceSources.forEach(function(source){const id=source.id.replace('input_','');source.onkeyup=function(){events[id].forEach(function(evt){evt();});JotForm.countTotal();};});},handleDonationAmount:function(){var donationField=JotForm.donationField=document.querySelector('input[id*="_donation"]');JotForm.paymentTotal=donationField.value||0;var prevInput='';if(window.FORM_MODE==="cardform"){var donationPredefinedRadios=document.querySelectorAll('input[class*="js-donation-suggestion"]');donationPredefinedRadios.forEach(function(radio){radio.addEventListener('click',function(e){JotForm.paymentTotal=e.target.value;})})} donationField.addEventListener('input',function(){var donationRegex=new RegExp(/^([0-9]{0,15})(\.[0-9]{0,2})?$/);if(this.value.match(donationRegex)){JotForm.paymentTotal=prevInput=this.value;}else{JotForm.paymentTotal=this.value=prevInput;}});if(donationField.getAttribute('data-custom-amount-field')>0){JotForm.donationSourceField=document.querySelector(`#input_${donationField.getAttribute('data-custom-amount-field')}`);if(!JotForm.donationSourceField){donationField.removeAttribute('readonly');return;} setTimeout(function(){JotForm.updateDonationAmount();donationField.triggerEvent('keyup');},1000);JotForm.donationSourceField.addEventListener('keyup',JotForm.updateDonationAmount);JotForm.donationSourceField.addEventListener('change',JotForm.updateDonationAmount);}else if(donationField.hasAttribute('data-min-amount')){var currency=donationField.nextSibling.textContent.strip();var minAmount=parseFloat(donationField.readAttribute('data-min-amount'));donationField.validateMinimum=function(){var val=this.getValue();if(isNaN(val)||val0?val:0;} JotForm.donationField.value=JotForm.paymentTotal=getVal();if(window.FORM_MODE&&window.FORM_MODE=='cardform'){JotForm.donationField.parentNode.addClassName('isFilled');}},isComparePaymentFormV1:function(){var queryParameters=window.location.search.substring(1);return queryParameters==="comparePaymentForm=v1"?true:false;},isPaymentSelected:function(){var selected=false;var inputSimpleFpc=document.querySelector('input[name="simple_fpc"]');var paymentFieldId=inputSimpleFpc&&inputSimpleFpc.value;var paymentField=$('id_'+paymentFieldId);if(!paymentField){return!!inputSimpleFpc;} if(paymentField.hasClassName('form-field-hidden')||paymentField.up('ul.form-section').hasClassName('form-field-hidden')||(paymentField.up('ul.form-section-closed')&&paymentField.up('ul.form-section-closed').hasClassName('form-field-hidden'))) {return false;} if(!inputSimpleFpc){return false;} if(paymentField&&(paymentField.getStyle('display')==="none"||!JotForm.isVisible(paymentField)&&JotForm.getSection(paymentField).id)){return false;} if(window.paymentType==='product'&&(window.JFAppsManager&&window.JFAppsManager.checkoutKey&&window.JFAppsManager.cartProductItemCount>0)){return true;} if(window.productID){$H(window.productID).each(function(pair){var elem=$(pair.value);if(elem&&elem.checked){var quantityField=elem.up().select('select[id*="_quantity_"],input[id*="_quantity_"]');selected=quantityField.length===0||(quantityField.length===1&&quantityField[0].getValue()>0);if(quantityField.length>1){selected=quantityField.any(function(qty){return qty.getValue()>0;});} if(selected){throw $break;}}});}else if($('input_'+paymentFieldId+'_donation')){var elem=$('input_'+paymentFieldId+'_donation');if(/^\d+(?:\.\d+)?$/.test(elem.getValue())){selected=elem.getValue()>0;}}else{var productField=$$('input[name*="q'+paymentFieldId+'"][type="hidden"]');if(productField.length<1){return false;} if(productField[0].readAttribute('selected')==='false'){productField[0].remove();return false;} return true;} return selected;},togglePaypalButtons:function(show){var paymentFieldId=$$('input[name="simple_fpc"]')[0].value;if($('input_'+paymentFieldId+'_paymentType_express')&&!$('input_'+paymentFieldId+'_paymentType_express').checked){show=false;} if($$('.paypal-button').length<1||!$('use_paypal_button')){return;} $$('.form-submit-button').each(function(btn){if(show){if(btn.up().down('.paypal-button')){btn.up().down('.paypal-button').show();btn.hide();}}else{if(btn.up().down('.paypal-button')){btn.up().down('.paypal-button').hide();} btn.show();}});},handlePaypalButtons:function(){var products=window.productID;var requiredPayment=false;var paymentFieldId=$$('input[name="simple_fpc"]')[0].value;if(products){$H(products).each(function(p){if($(p.value).getAttribute('class').indexOf('[required]')>-1){requiredPayment=true;throw $break;}});}else if($('input_'+paymentFieldId+'_donation')){requiredPayment=$('input_'+paymentFieldId+'_donation').getAttribute('class').indexOf('required')>-1;} JotForm.togglePaypalButtons(requiredPayment||JotForm.isPaymentSelected());if(!requiredPayment){$H(products).each(function(p){$(p.value).observe('click',function(){JotForm.togglePaypalButtons(JotForm.isPaymentSelected());});});}},paymentDropdownHandler:function(uid,onChange){var dropdown=null;if(uid){dropdown=document.getElementById(uid);}else if(document.querySelectorAll('.payment-dropdown').length>0){dropdown=document.querySelectorAll('.payment-dropdown')[0];} if(!dropdown){return;};var selectArea=dropdown.querySelector('.select-area');var selectedValueArea=selectArea.querySelector('.selected-value');var options=dropdown.querySelectorAll('.option');var productCategoryDropdown=document.querySelector('#payment-category-dropdown');options.forEach(function(option){option.addEventListener('click',function(event){var option=event.target;var optionVal=option.getAttribute('data-value');var selectedOption={};options.forEach(function(opt){if(opt.getAttribute('data-value')===optionVal){selectedOption={label:opt.innerText.trim(),value:optionVal};}});if(!selectedOption.value||selectedOption.value==='clear'){dropdown.classList.remove('option-selected');}else{dropdown.classList.add('option-selected');} if(selectedOption.value!=='clear'){selectedValueArea.innerText=selectedOption.label;}else{selectedValueArea.innerText='';} dropdown.classList.remove('open');selectArea.setAttribute('aria-expanded','false');onChange(selectedOption);});});selectArea.addEventListener('click',function(){if(dropdown.classList.contains('open')){dropdown.classList.remove('open');selectArea.setAttribute('aria-expanded','false');}else{dropdown.classList.add('open');selectArea.setAttribute('aria-expanded','true');}});window.addEventListener('click',function(event){if(event.target&&!event.target.closest('#payment-sorting-products-dropdown')){dropdown.classList.remove('open');} if(event.target&&!event.target.closest('#payment-category-dropdown')){if(productCategoryDropdown&&productCategoryDropdown.classList.contains('open')){productCategoryDropdown.classList.remove('open');}}});},multiSelectDropdownHandler:function(onChange){var dropdown=document.querySelector('.multi-select-dropdown');if(!dropdown){return;} var selectArea=dropdown.querySelector('.select-area');var selectedValueArea=selectArea.querySelector('.selected-values');var options=dropdown.querySelectorAll('.option');var dropdownHint=selectArea.querySelector('.dropdown-hint');options.forEach(function(option){option.addEventListener('click',function(event){var clickedItem=event.target;var closestOption=clickedItem.closest('.option')||clickedItem;var input=closestOption.querySelector('input');var clickedItemValue=input.value;var selectedOptions=[];if(clickedItem.nodeName!=='INPUT'){input.checked=!input.checked;} if(input.checked){if(clickedItemValue==='All'){options.forEach(function(opt){var inp=opt.select('input')[0];if(inp.value!=='All'){inp.checked=false;opt.classList.remove('selected');}});}else{options[0].classList.remove('selected');options[0].querySelector('input').checked=false;} closestOption.classList.add('selected');}else{closestOption.classList.remove('selected');} options.forEach(function(opt){if(opt.classList.contains('selected')){selectedOptions.push({label:opt.querySelector('span').innerText,value:opt.querySelector('input').value});}});if(dropdown.classList.contains('hasSelectAll')&&selectedOptions.length===0){options[0].classList.add('selected');options[0].querySelector('input').checked=true;selectedOptions.push({label:options[0].querySelector('span').innerText,value:options[0].querySelector('input').value});} if(selectedOptions[0]==='All'){dropdownHint.show();}else{dropdownHint.hide();} var selectedOptionsValues=selectedOptions.map(function(s){return s.value;});var selectedOptionsLabel=selectedOptions.map(function(s){return s.label;});selectedValueArea.innerText=selectedOptionsLabel.join(', ');if(selectedOptions[0].value==='All'||(JotForm.isVisible(dropdownHint)&&selectedOptions[0].value==='All')){selectedValueArea.classList.add('all_selected');}else if(selectedValueArea.hasClassName('all_selected')){selectedValueArea.classList.remove('all_selected');} onChange(selectedOptions,selectedOptionsLabel,selectedOptionsValues);});});selectArea.addEventListener('click',function(){dropdown.classList.toggle('open');selectArea.setAttribute('aria-expanded',dropdown.classList.contains('open').toString());});window.addEventListener('click',function(event){if(event.target&&(!event.target.closest('#payment-category-dropdown')&&!event.target.closest('#payment-sorting-products-dropdown'))){dropdown.classList.remove('open');}});},handleProductCategoryDropdown:function(){this.multiSelectDropdownHandler(function(selectedCategories,selectedCategoriesLabels,selectedCategoriesValues){var dropdown=document.getElementById('payment-category-dropdown');var allCategoryTitles=document.querySelectorAll('.form-product-category-item');var isCategoryTitleEnabled=dropdown&&dropdown.hasClassName('category-title-enabled');var products=document.querySelectorAll('.form-product-item');var productSortingProductsDropdown=document.querySelector('#payment-sorting-products-dropdown');if(products.length===0){return;} products.forEach(function(p){var product=p;product.classList.remove('not-category-found');if(selectedCategories[0].value!=='All'){if(!isCategoryTitleEnabled){var productCategories=product.getAttribute('categories')?product.getAttribute('categories').split(','):[];if(productCategories){var isCategoryFound=false;productCategories.forEach(function(productCategory){if(selectedCategoriesValues.includes(productCategory)){isCategoryFound=true;}});if(!isCategoryFound){product.classList.add('not-category-found');}}}else{if(!selectedCategoriesValues.includes(product.getAttribute('active-category'))){product.classList.add('not-category-found');}}}});if(allCategoryTitles.length===0&&!isCategoryTitleEnabled){return;} allCategoryTitles.forEach(function(categoryTitle){categoryTitle.classList.remove('not-category-found');if(selectedCategories[0].value!=='All'){if(!selectedCategoriesValues.includes(categoryTitle.getAttribute('category'))){categoryTitle.classList.add('not-category-found');}else{categoryTitle.classList.remove('not-category-found');}}});window.addEventListener('click',function(event){if(event.target&&!event.target.closest('#payment-category-dropdown')){dropdown.classList.remove('open');} if(event.target&&!event.target.closest('#payment-sorting-products-dropdown')){if(productSortingProductsDropdown&&productSortingProductsDropdown.classList.contains('open')){productSortingProductsDropdown.classList.remove('open');}}});});if(isIframeEmbedFormPure()){document.querySelectorAll('.form-product-category-item').forEach(function(productCategory){productCategory.addEventListener('click',callIframeHeightCaller);});}},initPaymentProperties:function(initValues){try{if(!initValues){return;} if(Object.keys(initValues).length===0){return;} JotForm.paymentProperties=JSON.parse(initValues);}catch(err){console.error(err);}},checkEmbed:function(){if(window!==window.top){appendHiddenInput('embedUrl',document.referrer) if(JotForm.debug){console.log(document.referrer);}}},checkPwa:function(){if(window.location.href.indexOf('jotform_pwa=1')>-1){if(window.location.href.indexOf('pwa_id=')===-1){return new Error('AppId couldn\'t be found!');} var hiddenInputs=[{name:'jotform_pwa',val:1},{name:'pwa_id',val:document.get.pwa_id},{name:'pwa_isPWA'},{name:'pwa_device'}];hiddenInputs.forEach(function(inp){if(inp.val||document.get[inp.name]){appendHiddenInput(inp.name,inp.val||document.get[inp.name]);}});}},handlePaypalExpress:function(){if(typeof _paypalExpress!=="function"||$('express_category').getAttribute('data-digital_goods')==="No"){return;} var paypalExpress=new _paypalExpress();paypalExpress.init();},handleEcheck:function(){if(typeof _echeck!=="function"){return;} var echeck=new _echeck();echeck.init();},handleBraintree:function(){if(window.location.pathname.match(/^\/edit/)||(["edit","inlineEdit","submissionToPDF"].indexOf(document.get.mode)>-1&&document.get.sid)){return;} if(typeof __braintree!=="function"){alert("Braintree payment script didn't work properly. Form will be reloaded");location.reload();return;} JotForm.braintree=__braintree();JotForm.braintree.init();},handlePagseguro:function(){if(window.location.pathname.match(/^\/edit/)||(["edit","inlineEdit","submissionToPDF"].indexOf(document.get.mode)>-1&&document.get.sid)){return;} if(typeof __pagseguro!=="function"){alert("PagSeguro payment script didn't work properly. Form will be reloaded");location.reload();return;} JotForm.pagseguro=__pagseguro();JotForm.pagseguro.init();},handleSquare:function(){if((window.location.href.match(/mode=inlineEdit/)||window.location.pathname.match(/^\/\/edit/)||window.location.pathname.match(/^\/edit/)||window.location.href.match(/mode=submissionToPDF/))&&document.get.sid){return;} if(window===window.top){if(window.location.protocol!=='https:'){window.location.href=window.location.href.replace('http','https');return;}} if(typeof __square!=="function"){alert("Square payment script didn't work properly. Form will be reloaded");location.reload();return;} JotForm.squarePayment=__square();JotForm.squarePayment.loadSquareScript(function(){JotForm.squarePayment.init();});},handleSensepass:function(){if(JotForm.isEditMode()||JotForm.isDirectFlow==='No')return;if(typeof __sensepass!=="function"){alert("Sensepass payment script didn't work properly. Form will be reloaded");location.reload();return;} JotForm.sensepassPayment=__sensepass();JotForm.sensepassPayment.init();},handleStripeACH:function(){if(JotForm.isEditMode())return;if(typeof __stripeACH==="undefined"){alert("Stripe ACH payments script didn't work properly. Form will be reloaded. ");location.reload();return;} JotForm.stripeACH=__stripeACH;JotForm.stripeACH.init();},handleMollie:function(){if(JotForm.isEditMode())return;if(typeof __mollie==="undefined"){alert("Mollie script didn't work properly. Form will be reloaded. ");location.reload();return;} JotForm.mollie=__mollie;JotForm.mollie.init();},handleBluepay:function(){if(JotForm.isEditMode())return;if(typeof __bluepay==="undefined"){alert("Bluepay script didn't work properly. Form will be reloaded. ");location.reload();return;} JotForm.bluepay=__bluepay;JotForm.bluepay.init();},handlePaypalSPB:function(){JotForm.paypalSPB=__paypalSPB;try{JotForm.paypalSPB.init();JotForm.paypalSPB.render();}catch(e){console.error(e);if(typeof e==='string'){alert(e);return;} alert("There was a problem with PayPal Smart Payment Buttons integration.");}},handlePaymentSubProducts:function(){var heights=[];var optionValues=[];var sections=document.querySelectorAll('.form-section');var productPage=false;document.querySelectorAll('.form-product-has-subproducts').forEach(function(sp){var formLine=sp.closest(".form-line");var wasHidden=false;if(formLine&&formLine.classList.contains("form-field-hidden")){formLine.style.display='';wasHidden=true;} if(sections.length>1){productPage=productPage?productPage:sections.filter(function(p){var closestFormSection=sp.closest('.form-section');return closestFormSection&&closestFormSection===p;})[0];if(!productPage.isVisible()){productPage.setStyle({'display':'block'});heights[sp.id]=[sp.parentNode.offsetHeight,document.querySelector('label[for="'+sp.id+'"]').offsetHeight];productPage.setStyle({'display':'none'});}else{heights[sp.id]=[sp.parentNode.offsetHeight,document.querySelector('label[for="'+sp.id+'"]').offsetHeight];}}else{heights[sp.id]=[sp.parentNode.offsetHeight,document.querySelector('label[for="'+sp.id+'"]').offsetHeight];} sp.addEventListener('click',function(){showSubProducts(this);JotForm.countTotal();});if(wasHidden){var formLine=sp.closest(".form-line");if(formLine){formLine.style.display='none';}}});function showSubProducts(el){var productSpan=el.parentNode;if(!el.checked){productSpan.shift({height:heights[el.id][1],duration:0.3,onEnd:JotForm.handleIFrameHeight});if(el.value&&el.value.indexOf('_expanded')>-1&&productSpan.querySelector('.form-product-description')&&productSpan.querySelector('.form-product-description').childNodes[0]&&productSpan.querySelector('.form-product-description').childNodes[0].nodeValue.trim()!==""){productSpan.shift({height:heights[el.id][1]+20});} optionValues[el.id]=[];JotForm.clearProductValues(el,optionValues);}else{productSpan.shift({height:heights[el.id][0]-10,duration:0.3,onEnd:JotForm.handleIFrameHeight});JotForm.populateProductValues(el,optionValues);} setTimeout(function(){JotForm.totalCounter(JotForm.prices)},300);};},clearProductValues:function(el,optionValues){document.querySelectorAll('#'+el.id+'_subproducts select,'+'#'+el.id+'_subproducts input[type="text"]').forEach(function(field){var fieldValue=field.tagName==="select"?field.options[field.selectedIndex].value:field.value;if(fieldValue){optionValues[el.id].push([field.id,fieldValue]);} field.stopObserving();if(field.tagName==="SELECT"){field.selectedIndex=0;}else{field.value=0;}});},clearProductValuesV1:function(el,optionValues){document.querySelectorAll('#'+el.id+'_subproducts select,'+'#'+el.id+'_subproducts input[type="text"]').forEach(function(field){var fieldValue=field.tagName==="select"?field.options[field.selectedIndex].value:field.value;if(fieldValue){optionValues[el.id].push([field.id,fieldValue]);} field.stopObserving('blur');field.stopObserving('focus');if(field.tagName==="SELECT"){field.selectedIndex=0;}else{field.value=0;}});},populateProductValues:function(el,optionValues){if(optionValues[el.id]&&optionValues[el.id].length>0){optionValues[el.id].each(function(vv){$(vv[0]).stopObserving();$$("#"+vv[0]+".form-product-custom_quantity").each(function(el){el.observe('blur',function(){isNaN(this.value)||this.value<1?this.value='0':this.value=parseInt(this.value)})});$$("#"+vv[0]+".form-product-custom_quantity").each(function(el){el.observe('focus',function(){this.value==0?this.value='':this.value})});;if($(vv[0]).tagName==="SELECT"){$(vv[0]).selectOption(vv[1]);}else{$(vv[0]).value=vv[1];}});}},populateProductValuesV1:function(el,optionValues){if(optionValues[el.id]&&optionValues[el.id].length>0){optionValues[el.id].each(function(vv){$(vv[0]).stopObserving('blur');$(vv[0]).stopObserving('focus');$$("#"+vv[0]+".form-product-custom_quantity").each(function(el){el.observe('blur',function(){isNaN(this.value)||this.value<1?this.value='0':this.value=parseInt(this.value)})});$$("#"+vv[0]+".form-product-custom_quantity").each(function(el){el.observe('focus',function(){this.value==0?this.value='':this.value})});;if($(vv[0]).tagName==="SELECT"){if(vv[1]!=="0"){$(vv[0]).selectOption(vv[1]);}}else{$(vv[0]).value=vv[1];}});}},handlePaymentSubProductsV1:function(){const selectedValues=[];document.querySelectorAll('.form-product-has-subproducts').forEach(function(sp){sp.addEventListener('click',function(){const formProductItem=sp.closest(".form-product-item");if(sp.checked){formProductItem.classList.remove('sub_product');formProductItem.classList.add('show_sub_product');JotForm.populateProductValuesV1(sp,selectedValues);}else{formProductItem.classList.remove('show_sub_product');formProductItem.classList.add('sub_product');selectedValues[sp.id]=[];JotForm.clearProductValuesV1(sp,selectedValues);if(typeof PaymentStock!=='undefined'){PaymentStock.handleStockManagement();}} JotForm.countTotal();});});},handleProductLightbox:function(){document.querySelectorAll('.form-product-image-with-options').forEach(function(image){image.addEventListener('click',function(){const pid=image.closest('.form-product-item').getAttribute('pid');if(isIframeEmbedFormPure()){onProductImageClicked(pid,true);}else{onProductImageClicked(pid,false);}});});},setCurrencyFormat:function(curr,useDecimal,decimalMark){var noDecimal=['BIF','CLP','DJF','GNF','JPY','KMF','KRW','MGA','PYG','RWF','VUV','XAF','XOF','XPF'];var decimalPlaces=noDecimal.indexOf(curr)>-1||!useDecimal?0:2;this.currencyFormat={curr:curr,dSeparator:decimalMark=="comma"?",":".",tSeparator:decimalMark=="comma"?".":",",decimal:decimalPlaces,decimalMark:decimalMark};},setCustomPriceSource:function(pairKey){if(pairKey){const customFirstPaymentPriceData=document.querySelector(`[id="${pairKey}_custom_first_payment_price"]`);const customPriceSourceData=document.querySelector(`[id="${pairKey}_custom_price"]`);if(customFirstPaymentPriceData&&customFirstPaymentPriceData.hasAttribute('data-price-source')){const firstCustomPriceSourceKey=customFirstPaymentPriceData.getAttribute('data-price-source');if(firstCustomPriceSourceKey){const firstCustomPriceSourceInput=document.getElementById('input_'+firstCustomPriceSourceKey);if(firstCustomPriceSourceInput){firstCustomPriceSourceInput.value=customFirstPaymentPriceData.value;}}} if(customPriceSourceData&&customPriceSourceData.hasAttribute('data-price-source')){var customPriceSourceKey=customPriceSourceData.getAttribute('data-price-source');if(customPriceSourceKey){const customPriceSourceInput=document.getElementById('input_'+customPriceSourceKey);if(customPriceSourceInput){customPriceSourceInput.value=customPriceSourceData.value;}}}}},countTotal:function(prices){var prices=prices||JotForm.prices;var discounted=false;var roundAmount=function(num,decimalPlaces){return parseFloat(JotForm.morePreciseToFixed(num,decimalPlaces));} if(Object.keys(JotForm.discounts).length>0){discounted=true;if(JotForm.discounts.total||JotForm.discounts.shipping){var type=JotForm.discounts.type,rate=JotForm.discounts.rate,minimum=JotForm.discounts.minimum,code=JotForm.discounts.code;}else{for(var pid in prices){for(var kkey in JotForm.discounts){if(pid.indexOf(kkey)!==-1){prices[pid].discount=JotForm.discounts[kkey];}}}}}else{$H(prices).each(function(p){delete prices[p.key].discount;});} var total=0;var totalWithoutDiscount=0;var subTotal=0;var subTotalWithoutDiscount=0;var itemSubTotal=[];var shippingTotal=0;var taxTotal=0;var taxTotalWithoutDiscount=0;var otherTotal=0;var otherTotalWithoutDiscount=0;var taxRate=0;var currency=JotForm.currencyFormat.curr;var decimal=JotForm.currencyFormat.decimal;var dSeparator=JotForm.currencyFormat.dSeparator;var tSeparator=JotForm.currencyFormat.tSeparator;var decimalMark=JotForm.currencyFormat.decimalMark;var flatShipping=0;var products=0;var formProductItem=null;var firstPaymentVal=0;var recurringVal=0;var firstPaymentDiscount;var recurPaymentDiscount;var pricingInformations=[];var noCostItems=[];if(JotForm.discounts&&Object.keys(JotForm.discounts).length>0&&window.paymentType==='subscription'&&document.querySelector('.form-payment-discount')){document.querySelector('.form-payment-discount').remove();} $H(prices).each(function(pair){var subproduct=false;var parentProductKey;var price=parseFloat(pair.value.price)||0;var parsedPair=pair.key.split("_");var label=parsedPair[0]+'_'+parsedPair[1]+'_'+parsedPair[2];formProductItem=$(label)?$(label).up('.form-product-item'):null;formProductInput=formProductItem&&formProductItem.down('.form-product-input');firstPaymentDiscount=0;recurPaymentDiscount=0;if(pair.key.split('_').length===4){subproduct=true;parentProductKey=pair.key.split('_');parentProductKey.pop();parentProductKey=parentProductKey.join("_");itemSubTotal[parentProductKey]=itemSubTotal[parentProductKey]||0;}else{parentProductKey=pair.key;} if((!JotForm.couponApplied&&formProductInput&&!formProductInput.checked)&&pair.value.specialPriceField===undefined){if($(parentProductKey+'_item_subtotal')&&!isNaN(price)&&JotForm.categoryConnectedProducts&&Object.keys(JotForm.categoryConnectedProducts).length>0&&JotForm.categoryConnectedProducts[pair.key.split('_')[2]]){JotForm.categoryConnectedProducts[pair.key.split('_')[2]].forEach(pid=>{const itemArr=parentProductKey.split('_');itemArr[2]=pid;if($(itemArr.join('_')+'_item_subtotal')){$(itemArr.join('_')+'_item_subtotal').update(parseFloat(0).formatMoney(decimal,dSeparator,tSeparator));}});} return;} var itemName=formProductItem&&formProductItem.down('.form-product-name')&&formProductItem.down('.form-product-name').textContent.trim();if(!itemName){itemName=$$('#'+label+'+ .product__header')[0]&&$$('#'+label+'+ .product__header .product__title')[0].textContent.trim();} if(pair.value.price=="custom"){if($(pair.key)&&$(pair.key).checked){JotForm.setCustomPriceSource(pair.key);subTotal=parseFloat($(pair.key+'_custom_price').getValue());subTotalWithoutDiscount=subTotal;if(JotForm.discounts&&JotForm.discounts[parsedPair[2]]){var customDiscount=JotForm.discounts[parsedPair[2]].split('-');rate=customDiscount[0];type=customDiscount[1];}}}else if(pair.value.recurring&&pair.value.firstPaymentVal&&pair.value.customFirstPaymentPrice==='1'){JotForm.setCustomPriceSource(pair.key);if($(pair.key)&&$(pair.key).checked&&$(pair.key+'_custom_first_payment_price')&&JotForm.discounts&&JotForm.discounts[parsedPair[2]]){var customDiscount=JotForm.discounts[parsedPair[2]].split('-');rate=customDiscount[0];type=customDiscount[1];}} if($(pair.value.quantityField)){if(pair.value.quantityField&&!(parseInt($(pair.value.quantityField).getValue())>0)){if(!$(pair.value.quantityField).hasClassName('form-subproduct-quantity')){return;} var isSelectedParentProduct=$(parentProductKey).checked;if($(pair.value.quantityField).hasClassName('form-subproduct-quantity')&&(!isSelectedParentProduct||$(pair.value.quantityField).getValue()==='0')) {return;}} try{var parentSelector=pair.key.split("_").slice(0,-1).join("_");if($(parentSelector)&&$(parentSelector).type==="radio"&&!$(parentSelector).checked){if($(pair.value.quantityField).value>0){$(pair.value.quantityField).value=0;if($(parentSelector+'_item_subtotal')){$(parentSelector+'_item_subtotal').update("0.00");}} if(window.FORM_MODE==="cardform"){$$("ul.products")[0]&&$$("ul.products")[0].querySelector('li[data-input="'+parentSelector+'"]')&&$$("ul.products")[0].querySelector('li[data-input="'+parentSelector+'"]').classList.remove("product--selected");$(pair.value.quantityField).up().querySelector(".jfDropdown-chip.isSingle").innerText=0;} return;}}catch(e){console.warn(e);}} var isSetupFee=pair.value.recurring?true:false;total=parseFloat(total);var productShipping=0;var priceWithoutDiscount=price;var taxAmount=0;var taxAmountWithoutDiscount=0;var recur=pair.value.recurring;var isSpecialPricing=false;var quantity=1;var specialName=[];var unitProductAmountForSpecialPrice=0;var priceIndex;if($(pair.value.specialPriceField)){var specialPriceField=$(pair.value.specialPriceField);if(pair.value.child&&pair.value.specialPriceField.split("_").length===4){var idx=pair.value.specialPriceField.split("_")[3];var specialPriceVal=pair.value.specialPriceList[idx]===''?'0':pair.value.specialPriceList[idx];price=parseFloat(specialPriceVal);}else{if(isNaN($(specialPriceField).options[0].value)||$(specialPriceField).options[0].value>0||$(specialPriceField.options[0].innerHTML.strip()!="")){priceIndex=specialPriceField.getSelected().index;}else{priceIndex=specialPriceField.getSelected().index-1} var item=null;if($(pair.value.quantityField)&&$(pair.value.quantityField).up("tr")){item=$(pair.value.quantityField).up("tr").querySelector("th").textContent.trim();}else{var specialPriceLabel=document.querySelector('label[for='+pair.value.specialPriceField+']');item=specialPriceLabel&&specialPriceLabel.textContent.trim();} if(item){specialName.push({name:item,value:$(specialPriceField).getSelected().value});} if(priceIndex>-1){price=parseFloat(pair.value.specialPriceList[priceIndex]);if($(pair.key+'_price')){$(pair.key+'_price').siblings('.freeCurr').each(function(el){el.style.display='inline';});}}else{var defaultSpecial=pair.value.specialPriceList[priceIndex+1];price=0;}} isSpecialPricing=true;unitProductAmountForSpecialPrice=pair.value.specialPriceList[priceIndex];} priceWithoutDiscount=price;if(pair.value.discount){var discount=pair.value.discount.split('-');priceWithoutDiscount=price;if(!discount[2]){price=price-((discount[1]==='fixed')?discount[0]:roundAmount(price*(discount[0]/100)));price=price<0?0:price;var paymentFieldId=$$('input[name="simple_fpc"]')[0]&&$$('input[name="simple_fpc"]')[0].value;if(paymentFieldId){var isSpecialPrice=pair.value.specialPriceField&&!isNaN(specialPriceVal);JotForm.pricesAfterCoupon[pair.key.split('input_'+paymentFieldId+'_')[1]]={oldPrice:JotForm.morePreciseToFixed(isSpecialPrice?specialPriceVal:pair.value.price),newPrice:JotForm.morePreciseToFixed(price)};}}else{if(discount[2]==="all"||discount[2]==="product"){if(isSetupFee){var reduced=((discount[1]==='fixed')?discount[0]:roundAmount(recur*(discount[0]/100)));recurPaymentDiscount=reduced;recur=recur-reduced;recur=recur<0?0:roundAmount(recur);}else{recurPaymentDiscount=((discount[1]==='fixed')?discount[0]:roundAmount(price*(discount[0]/100)));} var reduced=((discount[1]==='fixed')?discount[0]:roundAmount(price*(discount[0]/100)));if(pair.value.firstPaymentVal){firstPaymentDiscount=reduced;} price=price-reduced;price=price<0?0:price;if(pair.value.price==='custom'&&rate&&type){recurPaymentDiscount=type==="fixed"?rate:roundAmount(((rate/100)*parseFloat(subTotal)));}}else if(discount[2]==="first"){if(isSetupFee){var reduced=((discount[1]==='fixed')?discount[0]:roundAmount(price*(discount[0]/100)));firstPaymentDiscount=reduced;price=price-reduced;price=price<0?0:price;}}else if(discount[2]==="stripe_native"){if(isSetupFee){var setupFee=roundAmount(price-recur);var reduced=((discount[1]==='fixed')?discount[0]:roundAmount(recur*(discount[0]/100)));price=recur-reduced;if(!discount[3]){recur=roundAmount(price);recurPaymentDiscount=reduced;} if(pair.value.firstPaymentVal&&pair.value.customFirstPaymentPrice==='0'){firstPaymentDiscount=reduced} price=roundAmount(price+Number(setupFee));}else{var reduced=((discount[1]==='fixed')?discount[0]:roundAmount(price*(discount[0]/100)));if($(pair.key)&&$(pair.key).checked){recurPaymentDiscount=reduced;} price=price-reduced;price=price<0?0:price;}}} price=roundAmount(price);} if(!pair.value.recurring){var priceText=$(pair.key+'_price')?$(pair.key+'_price'):$(pair.key.replace(pair.key.substring(pair.key.lastIndexOf("_")),"")+'_price')||null;if(priceText){var oldPriceText=priceText.innerHTML;if(price=="0"&&pair.value.specialPriceList&&defaultSpecial){$(priceText).update(parseFloat(defaultSpecial||0).formatMoney(decimal,dSeparator,tSeparator));}else if(pair.value.price=="0"&&!pair.value.specialPriceList){$(priceText).update(oldPriceText);}else{$(priceText).parentNode.show();$(priceText).update(parseFloat(price).formatMoney(decimal,dSeparator,tSeparator));if(JotForm.categoryConnectedProducts&&Object.keys(JotForm.categoryConnectedProducts).length>0){var cP=JotForm.categoryConnectedProducts[pair.key.split('_')[2]];if(cP){cP.forEach(function(connectedProduct){var splitVal=pair.key.split('_');splitVal[2]=connectedProduct;var pairKey=splitVal.join('_');var _priceText=$(pairKey+'_price')?$(pairKey+'_price'):$(pairKey.replace(pairKey.substring(pairKey.lastIndexOf("_")),"")+'_price')||null;if(_priceText){$(_priceText).update(parseFloat(price).formatMoney(decimal,dSeparator,tSeparator));}});}}}}}else{var setupfeeText=$(pair.key+'_setupfee');priceText=$(pair.key+'_price');if(priceText){var priceAmount=isSetupFee?recur:price;$(priceText).update(parseFloat(priceAmount).formatMoney(decimal,dSeparator,tSeparator));} if(setupfeeText){$(setupfeeText).update(parseFloat(price).formatMoney(decimal,dSeparator,tSeparator));}} if(pair.value.tax){var tax=pair.value.tax;taxRate=parseFloat(tax.rate)||0;var locationField=$$('select[id*="input_'+tax.surcharge.field+'"], input#input_'+tax.surcharge.field)[0]||false;if(locationField&&!!locationField.value){JotForm.surchargeFieldId=tax.surcharge.field.split('_')[0];$H(tax.surcharge.rates).each(function(rate){if(typeof rate.value==='object'){var location=rate.value[1],surcharge=rate.value[0];if(location&&surcharge&&location.toLowerCase()===locationField.value.toLowerCase()){taxRate+=Number(surcharge);throw $break;}}});}} if(pair.value.addons){price+=pair.value.addons;} if($(pair.key)&&$(pair.key).checked){products++;if($(pair.value.quantityField)||$(pair.value.specialPriceField)){if($(pair.value.quantityField)&&(pair.value.specialPriceField!==pair.value.quantityField)){if($(pair.value.quantityField).readAttribute('type')=="text"){price=$(pair.value.quantityField).value?roundAmount(price*Math.abs(parseInt($(pair.value.quantityField).value,10))):0;priceWithoutDiscount=$(pair.value.quantityField).value?roundAmount(priceWithoutDiscount*Math.abs(parseInt($(pair.value.quantityField).value,10))):0;quantity=Math.abs(parseInt($(pair.value.quantityField).value,10));} else{price=roundAmount(price*parseInt(($(pair.value.quantityField).getSelected().text||0),10));priceWithoutDiscount=roundAmount(priceWithoutDiscount*parseInt(($(pair.value.quantityField).getSelected().text||0),10));quantity=parseFloat($(pair.value.quantityField).getSelected().text);} specialName.push({name:"Quantity",value:quantity,});if(document.querySelector('#'+parentProductKey+'_subproducts')){specialName.push({name:document.querySelector('#'+parentProductKey+'_subproducts th:first-child').textContent.trim(),value:$(pair.value.quantityField).up("tr").querySelector("th").textContent.trim()});}} if(subproduct){itemSubTotal[parentProductKey]=roundAmount(itemSubTotal[parentProductKey]+price);} if($(parentProductKey+'_item_subtotal')&&!isNaN(price)){const itemSubtotal=!subproduct?price:itemSubTotal[parentProductKey];$(parentProductKey+'_item_subtotal').update(parseFloat(itemSubtotal).formatMoney(decimal,dSeparator,tSeparator));if(JotForm.categoryConnectedProducts&&Object.keys(JotForm.categoryConnectedProducts).length>0&&JotForm.categoryConnectedProducts[pair.key.split('_')[2]]){JotForm.categoryConnectedProducts[pair.key.split('_')[2]].forEach(pid=>{const itemArr=parentProductKey.split('_');itemArr[2]=pid;if($(itemArr.join('_')+'_item_subtotal')){$(itemArr.join('_')+'_item_subtotal').update(parseFloat(itemSubtotal).formatMoney(decimal,dSeparator,tSeparator));}});}} if($(pair.value.quantityField)){if($(pair.value.quantityField).nodeName==="INPUT"){quantity=Math.abs(parseInt($(pair.value.quantityField).value,10));}else if($(pair.value.quantityField).nodeName==="SELECT"){quantity=parseFloat($(pair.value.quantityField).getSelected().text);}}} if(pair.value.tax){if(pair.value.price==='custom'&&window.paymentType==='subscription'){taxAmount=subTotal*(taxRate/100);taxAmountWithoutDiscount=subTotalWithoutDiscount*(taxRate/100);}else{taxAmount=price*(taxRate/100);taxAmountWithoutDiscount=priceWithoutDiscount*(taxRate/100);} taxAmount=roundAmount(taxAmount);taxAmountWithoutDiscount=roundAmount(taxAmountWithoutDiscount);} if(pair.value.shipping){var shipping=pair.value.shipping;if(shipping.firstItem){var qty=$(pair.value.quantityField)?($(pair.value.quantityField).readAttribute('type')==="text"?parseInt($(pair.value.quantityField).value):parseInt($(pair.value.quantityField).getSelected().text||0)):1;if(qty===1){productShipping=parseFloat(shipping.firstItem);} if(qty>1){productShipping=!parseFloat(shipping.addItem)?parseFloat(shipping.firstItem):parseFloat(shipping.firstItem)+parseFloat(shipping.addItem)*(qty-1);} productShipping=roundAmount(productShipping);}else if(flatShipping==0&&shipping.flatRate){shippingTotal=flatShipping=parseFloat(shipping.flatRate);}} taxTotal=roundAmount(taxTotal+taxAmount);taxTotalWithoutDiscount=roundAmount(taxTotalWithoutDiscount+taxAmountWithoutDiscount);if(!flatShipping){shippingTotal=roundAmount(shippingTotal+productShipping);} subTotal=roundAmount(subTotal+price);subTotalWithoutDiscount=roundAmount(subTotalWithoutDiscount+priceWithoutDiscount);otherTotal=roundAmount(otherTotal+(productShipping+taxAmount));otherTotalWithoutDiscount=roundAmount(otherTotalWithoutDiscount+(productShipping+taxAmountWithoutDiscount));}else{if($(pair.key+'_item_subtotal')){$(pair.key+'_item_subtotal').update("0.00");}} if(window.paymentType==='subscription'&&document.getElementById(pair.key).checked){function getDiscountedVal(val,firstOrAll){if(rate&&type&&discount[2]){var reduce=type==='fixed'?rate:roundAmount(((rate/100)*parseFloat(val)));if(discount[2]==='first'&&((pair.value.price==='custom'&&pair.value.firstPaymentVal)||(pair.value.customFirstPaymentPrice==='1'&&pair.value.firstPaymentVal&&pair.value.price&&pair.value.recurring))){firstPaymentDiscount=reduce;} if(firstOrAll==='all'){recurPaymentDiscount=reduce;}else if(firstOrAll==='first'){firstPaymentDiscount=reduce;} return parseFloat(val)>parseFloat(reduce)?roundAmount(parseFloat(val)-parseFloat(reduce)):0;} return val;} if(pair.value.firstPaymentVal){if($(pair.key+'_custom_first_payment_price')){firstPaymentVal=$(pair.key+'_custom_first_payment_price').getValue();}else{firstPaymentVal=(price||pair.value.firstPaymentVal);} firstPaymentVal=getDiscountedVal(firstPaymentVal,'first');} recurringVal=pair.value.recurring?recur:subTotal;recurringVal=0>recurringVal?0:recurringVal;if(recurringVal&&pair.value.price==='custom'&&rate&&type&&(discount[2]==="all"||discount[2]==="stripe_native")){recurringVal=getDiscountedVal(recurringVal,'all');} var recurPaymentContainer=document.querySelector('.form-payment-recurringpayments');if(recurPaymentContainer&&recurPaymentDiscount){var discountHTML=recurPaymentContainer.innerHTML.replace(/Total|Total:/,'Discount:').replace('payment_recurringpayments','discount_recurringpayments').replace('',' - ');var spanEl=document.createElement('span');spanEl.className='form-payment-discount';spanEl.innerHTML=discountHTML.replace('id="total-text"','');JotForm.discounts.container=spanEl;recurPaymentContainer.insertAdjacentElement('beforebegin',JotForm.discounts.container);$('discount_recurringpayments').update(parseFloat(recurPaymentDiscount).formatMoney(decimal,dSeparator,tSeparator));}} if($(pair.key)||JotForm.couponApplied){if($('coupon-button')&&$(pair.key).checked===true&&window.paymentType==='subscription'&&Array.from(document.querySelectorAll('.jfCard')).filter(function(el){return el.dataset.type==='control_stripe'}).length>0){selected_product_id=$(pair.key).value;JotForm.checkCouponAppliedProducts();};if($(pair.key).checked){var amount=isSpecialPricing?priceWithoutDiscount:parseFloat(pair.value.price);var description="";if(isSpecialPricing){specialName.forEach(function(text){description+=text.name+':'+text.value+' ';});} var paypalGatewayTypes=["paypalSPB","paypalcomplete"];var isPaypal=paypalGatewayTypes.indexOf(JotForm.payment)>-1;if(price>0){pricingInformations.push({productID:pair.key?pair.key.split('_').pop():'',finalProductID:pair.key?pair.key.replace(/input_\d+_/,''):'',name:itemName,unit_amount:Number(amount),total_amount:roundAmount(price),quantity:isSpecialPricing?1:quantity,description:description.substr(0,124),isSetupfee:isSetupFee,isSpecialPricing:isSpecialPricing,unitProductAmountForSpecialPrice:Number(unitProductAmountForSpecialPrice)});} else if(isPaypal&&!isNaN(quantity)&&quantity>0){noCostItems.push({name:itemName,unit_amount:Number(amount),quantity:isSpecialPricing?1:quantity,description:description.substr(0,124),isSetupfee:isSetupFee});}}}});if($('coupon-button')){var couponInput=$($('coupon-button').getAttribute('data-qid')+'_coupon');} if(JotForm.discounts.total){if(subTotal>=minimum){var reduce=type==="fixed"?rate:roundAmount(((rate/100)*parseFloat(subTotal)));subTotal=subTotal>reduce?roundAmount(subTotal-reduce):0;couponInput.value=code;}else{reduce=0;couponInput.value='';} var paymentTotal=document.querySelector('.form-payment-total');if(paymentTotal){paymentTotal.parentNode.insertBefore(JotForm.discounts.container,paymentTotal);$('discount_total').update(parseFloat(reduce).formatMoney(decimal,dSeparator,tSeparator));}} if(JotForm.payment==="paypalSPB"||JotForm.payment==="Stripe"){otherTotal=parsePriceWithoutComma(otherTotal);otherTotalWithoutDiscount=parsePriceWithoutComma(otherTotalWithoutDiscount);} total=roundAmount(subTotal+otherTotal);totalWithoutDiscount=roundAmount(subTotalWithoutDiscount+otherTotalWithoutDiscount);total=flatShipping>0?total+flatShipping:total;totalWithoutDiscount=flatShipping>0?roundAmount(totalWithoutDiscount+flatShipping):totalWithoutDiscount;if(total===0||isNaN(total)){total="0.00";totalWithoutDiscount="0.00";} if((total===0||total==="0.00"||isNaN(total))&&(window.JFAppsManager&&window.JFAppsManager.checkoutKey&&window.JFAppsManager.cartTotal>0)){total=window.JFAppsManager.cartTotal;totalWithoutDiscount=total;} var shippingDiscountVal;var oldShippingTotal=shippingTotal;if(JotForm.discounts.shipping&&shippingTotal>0&&subTotal>=minimum){var reduce=type==="fixed"?rate:roundAmount((rate/100)*parseFloat(shippingTotal));shippingDiscountVal=parseFloat(reduce)>parseFloat(shippingTotal)?shippingTotal:reduce;shippingTotal=shippingTotal>reduce?roundAmount(shippingTotal-reduce):0;total=roundAmount(total-(oldShippingTotal-shippingTotal));totalWithoutDiscount=roundAmount(totalWithoutDiscount-(oldShippingTotal-shippingTotal));} var itemTotal=parsePriceWithoutComma(subTotalWithoutDiscount);var shipping=parsePriceWithoutComma(shippingTotal);totalWithoutDiscount=parsePriceWithoutComma(totalWithoutDiscount)||0;total=parsePriceWithoutComma(total)||0;taxTotalWithoutDiscount=parsePriceWithoutComma(taxTotalWithoutDiscount);taxTotal=parsePriceWithoutComma(taxTotal);this.paymentTotal=Number(total);var stripeFormID=$$('input[name="formID"]')[0].value;if(JotForm.stripe&&typeof JotForm.stripe!=='undefined'&&(window.location.search==='?stripeLinks=1'||(typeof JotForm.stripeLink!=='undefined'&&JotForm.stripeLink==='Yes')||(typeof JotForm.tempStripeCEForms!=='undefined'&&!JotForm.tempStripeCEForms.includes(stripeFormID)))){JotForm.stripe.updateElementAmount();} if($('creditCardTable')){if(products>0&&this.paymentTotal===0&&discounted){JotForm.setCreditCardVisibility(false);}else if($$('input[id*="paymentType_credit"]').length>0&&$$('input[id*="paymentType_credit"]')[0].checked){JotForm.setCreditCardVisibility(true);}} if($("payment_subtotal")){$("payment_subtotal").update(parseFloat(subTotal).formatMoney(decimal,dSeparator,tSeparator));} if($("payment_tax")){$("payment_tax").update(parseFloat(taxTotal).formatMoney(decimal,dSeparator,tSeparator));} if($("payment_shipping")){$("payment_shipping").update(parseFloat(shippingTotal).formatMoney(decimal,dSeparator,tSeparator));} if($("payment_total")){$("payment_total").update(parseFloat(total).formatMoney(decimal,dSeparator,tSeparator));if($("payment_total").up(".form-line")&&$("payment_total").up(".form-line").triggerEvent){$("payment_total").up(".form-line").triggerEvent("keyup");}} if($("payment_footer_total")){$("payment_footer_total").update(parseFloat(total).formatMoney(decimal,dSeparator,tSeparator));} if(document.querySelector('#payment_recurringpayments')){$("payment_recurringpayments").update(parseFloat(recurringVal).formatMoney(decimal,dSeparator,tSeparator));if($("payment_recurringpayments").up(".form-line")&&$("payment_recurringpayments").up(".form-line").triggerEvent){$("payment_recurringpayments").up(".form-line").triggerEvent("keyup");}} var count=0;for(var propt in JotForm.discounts){count++;} var isDiscount=count>0;var discount=parsePriceWithoutComma(Math.abs(roundAmount(itemTotal+shipping+taxTotal)-total));discount=isDiscount?discount:0;JotForm.pricingInformations={items:pricingInformations,noCostItems:noCostItems,general:{net_amount:total,total_amount:totalWithoutDiscount,item_total:itemTotal,tax_total:taxTotal,shipping:shipping,discount:discount,currency:currency,subtotal:subTotal,taxTotalWithoutDiscount,oldShippingTotal}};if(shippingDiscountVal&&shippingDiscountVal>0){JotForm.pricingInformations.general.shippingDiscountVal=shippingDiscountVal;} if(window.paymentType==='subscription'){if(firstPaymentDiscount){JotForm.pricingInformations.general.firstPaymentDiscount=firstPaymentDiscount;} if(recurPaymentDiscount){JotForm.pricingInformations.general.recurPaymentDiscount=recurPaymentDiscount;}} if(JotForm.paypalCompleteJS&&window.paypal&&window.paypal.Messages){JotForm.paypalCompleteJS.payLaterFuncs.changeMessageAmount();}else if(JotForm.paypalSPB&&window.paypal&&window.paypal.Messages){JotForm.paypalSPB.renderMessages();} function parsePriceWithoutComma(price){if(decimalMark==="comma"){return price;} return parseFloat(parseFloat(price).formatMoney(decimal||2,dSeparator,""));}},prices:{},morePreciseToFixed:function(num,decimalPlaces){decimalPlaces=typeof decimalPlaces=='undefined'?2:decimalPlaces;var num_sign=num>=0?1:-1;return(Math.round((num*Math.pow(10,decimalPlaces))+(num_sign*0.0001))/Math.pow(10,decimalPlaces)).toFixed(decimalPlaces);},setCreditCardVisibility:function(show){if(show){document.querySelector('#creditCardTable').style.display='';}else{document.querySelector('#creditCardTable').style.display='none';}},findAncestor:function(el,cls){while((el=el.parentElement)&&!el.classList.contains(cls));return el;},totalCounter:function(prices){if(!Number.prototype.formatMoney){Number.prototype.formatMoney=function(c,d,t){var temp=(typeof this.toString().split('.')[1]!=='undefined'&&this.toString().split('.')[1].length>c&&this.toString().charAt(this.toString().length-1)==='5')?this.toString()+'1':this.toString();var n=parseFloat(temp),c=isNaN(c=Math.abs(c))?2:c,d=d===undefined?".":d,t=t===undefined?",":t,s=n<0?"-":"",i=parseInt(n=Math.abs(+n||0).toFixed(c))+"",j=(j=i.length)>3?j%3:0;return s+(j?i.substr(0,j)+t:"")+i.substr(j).replace(/(\d{3})(?=\d)/g,"$1"+t)+(c?d+Math.abs(n-i).toFixed(c).slice(2):"");};} JotForm.prices=prices;window.addEventListener('load',function(){if($('draftID')){return;} JotForm.countTotal(prices);});if(window.self!==window.top){document.observe('dom:loaded',function(){if($('draftID')){return;} JotForm.countTotal(prices);});} $H(prices).each(function(pair){if($(pair.key)){$(pair.key).stopObserving('click');$(pair.key).observe('click',function(){JotForm.countTotal(prices);});} if(pair.value.price=="custom"){$(pair.key+'_custom_price').stopObserving('keyup');$(pair.key+'_custom_price').observe('keyup',function(){JotForm.countTotal(prices);});} if($(pair.key+'_custom_first_payment_price')){$(pair.key+'_custom_first_payment_price').stopObserving('keyup');$(pair.key+'_custom_first_payment_price').observe('keyup',function(){JotForm.countTotal(prices);});} if(pair.value.tax){var surcharge=pair.value.tax.surcharge;var selectSurcharge=document.querySelector('select[id*="input_'+surcharge.field+'"]');if(selectSurcharge){selectSurcharge.stopObserving('change');selectSurcharge.observe('change',function(){setTimeout(JotForm.countTotal(),500);});} var inputSurcharge=document.querySelector('input[id="input_'+surcharge.field+'"]');if(inputSurcharge){inputSurcharge.stopObserving('keyup');inputSurcharge.observe('keyup',function(){setTimeout(JotForm.countTotal(),500);});}} var triggerAssociatedElement=function(el){var prodID=$(el).id.match(/input_([0-9]*)_quantity_/)||$(el).id.match(/input_([0-9]*)_custom_/);setTimeout(function(){if(prodID&&$('id_'+prodID[1])&&typeof $('id_'+prodID[1]).triggerEvent==='function'){$('id_'+prodID[1]).triggerEvent('click');} var productItem=el.up(".form-product-item");if(productItem&&productItem.down("input")&&productItem.down("input").validateInput){productItem.down("input").validateInput();}},100);};if($(pair.value.quantityField)){function countQuantityTotal(){if(JotForm.isVisible($(pair.value.quantityField))){if($(pair.value.quantityField).tagName!=='SELECT'||$(pair.value.quantityField).getSelected().index>0||$(pair.value.quantityField).getValue()==="0") {var productItem=$(pair.key)?$(pair.key).up('.form-product-item'):false;var productWithSubProducts=productItem?productItem.down('.form-product-has-subproducts'):false;var subProducts=productItem.select('.form-subproduct-quantity');if($(pair.value.quantityField).getValue()==="0"){var subTotalSpan=$(pair.key+'_item_subtotal');if(subTotalSpan)subTotalSpan.update("0.00");} if(productWithSubProducts){if(productWithSubProducts.getAttribute('data-is-default-required')==='true'){productWithSubProducts.checked=true;}else{productWithSubProducts.checked=false;} var isAllSubProductsZero=true;$A(subProducts).each(function(pr){if(!($(pr).getValue()<=0)){productWithSubProducts.checked=true;isAllSubProductsZero=false;}});if(isAllSubProductsZero){try{var subProductKeyPieces=pair.key.split('_');subProductKeyPieces.splice(-1,1);subProductKeyPieces=subProductKeyPieces.join('_');var subTotalSpanForSubProduct=$(subProductKeyPieces+'_item_subtotal');if(subTotalSpanForSubProduct)subTotalSpanForSubProduct.update("0.00");}catch(e){console.log(e);}}}else{if($(pair.key)){$(pair.key).checked=!($(pair.value.quantityField).getValue()<=0);var productValue=pair.key.split('_');productValue.splice(-1,2);productValue=productValue.join('_');JotForm.runConditionForId(productValue);}}} JotForm.countTotal(prices);}} var quantityCorrectionForTextInput=function(qty){var qtyField=$(pair.value.quantityField);qty.forEach(function(e){var hasSubproductList=document.getElementsByClassName('form-checkbox form-product-has-subproducts form-product-input');var pairProductCheck=hasSubproductList[$(pair.key).id.slice(0,-2)];if(e[1].match(qtyField.id)){qtyField.value=qtyField.getValue()<="0"||!(Number(qtyField.getValue()))?(e[0]==="0"&&!pairProductCheck.value.includes('_expanded')?"1":e[0]):qtyField.value;}})} function setQuantityFieldEventsForTotalCalculation(){var qtyValueList=[];Array.from(document.getElementsByClassName("form-product-custom_quantity")).forEach(function(el){qtyValueList.push([el.value,el.id]);});$(pair.value.quantityField).observe('change',function(e){setTimeout(countQuantityTotal,50);quantityCorrectionForTextInput(qtyValueList);triggerAssociatedElement(this);const productItem=JotForm.findAncestor(e.target,'form-product-item');const productInput=productItem&&productItem.querySelector('.form-product-input.form-product-has-subproducts');if(productInput&&productInput.type==='radio'){const pid=productItem.getAttribute('pid');const allProductItems=document.querySelectorAll('.form-product-item');let otherProductsWithSubproduct=Array.from(allProductItems).filter(item=>item.getAttribute('pid')!==pid&&item.querySelector('.form-product-input.form-product-has-subproducts'));if(JotForm.categoryConnectedProducts&&JotForm.categoryConnectedProducts[pid]){const connectedPids=JotForm.categoryConnectedProducts[pid];otherProductsWithSubproduct=otherProductsWithSubproduct.filter(item=>!connectedPids.includes(item.getAttribute('pid')));} otherProductsWithSubproduct.forEach(item=>{const quantityDropdowns=item.querySelectorAll('.form-subproduct-quantity');quantityDropdowns.forEach(input=>input.value=0);});}});$(pair.value.quantityField).observe('keyup',function(){setTimeout(countQuantityTotal,50);triggerAssociatedElement(this);});} var inputSimpleFpc=document.querySelector('input[name="simple_fpc"]');var paymentFieldId=inputSimpleFpc&&inputSimpleFpc.value;var paymentField=$('id_'+paymentFieldId);if(!JotForm.isPaymentSelected()&&paymentField&&paymentField.hasClassName('jf-required')){setTimeout(function(){setQuantityFieldEventsForTotalCalculation();},1800);}else{setQuantityFieldEventsForTotalCalculation();}} if($(pair.value.specialPriceField)){function countSpecialTotal(){if(JotForm.isVisible($(pair.value.specialPriceField))){if($(pair.value.specialPriceField).tagName!=='SELECT'||$(pair.value.specialPriceField).getSelected().index>0){if($(pair.key)){$(pair.key).checked=true;var productValue=pair.key.split('_');productValue.splice(-1,2);productValue=productValue.join('_');JotForm.runConditionForId(productValue);}} JotForm.countTotal(prices);}} $(pair.value.specialPriceField).observe('change',function(){setTimeout(countSpecialTotal,50);triggerAssociatedElement(this);});$(pair.value.specialPriceField).observe('keyup',function(){setTimeout(countSpecialTotal,50);});}});},getPaymentTotalAmount:function(){var totalAmount=JotForm.pricingInformations?parseFloat(JotForm.pricingInformations.general.net_amount):parseFloat(JotForm.paymentTotal);return totalAmount||0;},paymentCategoryHandler:function(showCategory,showCategoryTitle,products,pairedProducts){function categoryCollapsible(){document.querySelectorAll('.form-product-category-item').forEach(function(categoryItem){if(categoryItem){categoryItem.addEventListener('click',function(){var category=this.getAttribute('category');var categoryProducts=document.querySelectorAll('.form-product-item[active-category="'+category+'"]');var selectedProducts=0;categoryProducts.forEach(function(categoryProduct){var formInput=categoryProduct.querySelector('.form-product-input');if(formInput&&formInput.checked){selectedProducts+=1;} if(categoryProduct.classList.contains('not-category-found')){categoryProduct.classList.remove('not-category-found');}else{categoryProduct.classList.add('not-category-found');}});if(this.classList.contains('title_collapsed')){this.classList.remove('title_collapsed');}else{this.classList.add('title_collapsed');var selectedItemsIcon=this.querySelector('.selected-items-icon');if(selectedItemsIcon){selectedItemsIcon.innerText='x'+selectedProducts;if(selectedProducts>0){this.classList.add('has_selected_product');}else{this.classList.remove('has_selected_product');}}}});}});} categoryCollapsible();if(products&&Object.keys(products).length>0&&showCategoryTitle){JotForm.categoryMainProducts=products;JotForm.categoryConnectedProducts=pairedProducts;var mainProducts=[];var connectedProducts=[];Object.entries(products).forEach(function([connectedProductPid,mainProductPid]){connectedProducts.push(connectedProductPid);if(!mainProducts.includes(mainProductPid)){mainProducts.push(mainProductPid);} var connectedProductItem=document.querySelector('.form-product-item[pid="'+connectedProductPid+'"]');if(connectedProductItem){var connectedProductInputs=connectedProductItem.querySelectorAll('input, select');connectedProductInputs.forEach(function(input){var newElement=input.cloneNode(true);newElement.setAttribute('name','');input.parentNode.replaceChild(newElement,input);});}});function handleConnectedSubproductClick(modifiedId){const modifiedElement=document.getElementById(modifiedId);const productItem=modifiedElement.closest('.form-product-item');const productItemInput=productItem.querySelector('.form-product-input');if(productItemInput.checked){productItem.classList.remove('sub_product');productItem.classList.add('show_sub_product');}else{productItem.classList.add('sub_product');productItem.classList.remove('show_sub_product');}} function refreshRelatedCategoryProductCount(product_item){const categories=document.querySelectorAll('.form-product-category-item');const connectedCategoriesString=product_item.getAttribute('categories');const filteredCategories=[];categories.forEach((category)=>{if(connectedCategoriesString.includes(category.getAttribute('category'))){filteredCategories.push(category);}}) filteredCategories.forEach((category)=>{if(category.classList.contains('title_collapsed')){const categoryProducts=document.querySelectorAll('.form-product-item[active-category="'+category.getAttribute('category')+'"]');let selectedProducts=0;Array.from(categoryProducts).forEach((categoryProduct)=>{const formInput=categoryProduct.querySelector('.form-product-input');if(formInput&&formInput.checked){selectedProducts+=1;}});if(category.querySelector('.selected-items-icon')){category.querySelector('.selected-items-icon').innerText=`x${selectedProducts}`;if(selectedProducts>0){category.classList.add('has_selected_product');}else{category.classList.remove('has_selected_product');}}}})} function mainProductObserver(product_item,product_item_input,input,mainProductPid,isSubproduct){var productConnectedProducts=pairedProducts[mainProductPid];$A(productConnectedProducts).each(function(connectedProductPid){var modifiedId=$(input).id.replace(mainProductPid,connectedProductPid);if(!$(modifiedId)){return false;} if(input.nodeName==='INPUT'&&['checkbox','radio'].indexOf($(input).readAttribute('type'))>-1){$(modifiedId).checked=$(input).checked;}else{$(modifiedId).setValue($(input).getValue());} if(isSubproduct&&(JotForm.newDefaultTheme||JotForm.newPaymentUI)){handleConnectedSubproductClick(modifiedId);}else if(isSubproduct){$(modifiedId).triggerEvent('click');} if(($(input).id.indexOf('_quantity_')>-1||$(input).id.indexOf('_custom_')>-1)&&(JotForm.newDefaultTheme||JotForm.newPaymentUI)){setTimeout(function(){var connected_product_item_input=$$('.form-product-item[pid="'+connectedProductPid+'"] .form-product-input')[0];if(product_item_input.checked!==connected_product_item_input.checked){$(connected_product_item_input).click();}},100);}});refreshRelatedCategoryProductCount(product_item);if(input.nodeName==='INPUT'&&$(input).readAttribute('type')==='radio'){Object.keys(products).forEach(function(item){if(!productConnectedProducts.includes(item)){$$('.form-product-item[pid="'+item+'"] .form-product-input')[0].checked=false;}});}} function connectedProductObserver(connected_product_item,connected_product_item_input,input,pairedMainProductPid,connectedProductPid,isSubproduct){var productConnectedProducts=pairedProducts[connectedProductPid];$A(productConnectedProducts).each(function(changedConnectedProductPid){var modifiedId=$(input).id.replace(connectedProductPid,changedConnectedProductPid);var isMainProduct=pairedMainProductPid===changedConnectedProductPid;if(!$(modifiedId)){return false;} if(input.nodeName==='INPUT'&&['checkbox','radio'].indexOf($(input).readAttribute('type'))>-1){$(modifiedId).checked=$(input).checked;}else{$(modifiedId).setValue($(input).getValue());} if(isSubproduct&&(JotForm.newDefaultTheme||JotForm.newPaymentUI)){handleConnectedSubproductClick(modifiedId);} if(isMainProduct&&$(modifiedId).hasClassName('form-product-input')){$(modifiedId).triggerEvent('click');} setTimeout(function(){if(isMainProduct&&!$(modifiedId).hasClassName('form-product-input')){$(modifiedId).triggerEvent('change');}},100);});refreshRelatedCategoryProductCount(connected_product_item) if(input.nodeName==='INPUT'&&$(input).readAttribute('type')==='radio'){var cid=products[$(input).getValue()];Object.keys(products).forEach(function(key){if(products[key]!==cid){$$('.form-product-item[pid="'+key+'"] .form-product-input')[0].checked=false;}});}} $A(mainProducts).each(function(mainProductPid){var product_item=$$('.form-product-item[pid="'+mainProductPid+'"]')[0];var product_item_input=$$('.form-product-item[pid="'+mainProductPid+'"] .form-product-input')[0];if($(product_item)){var isSubproduct=!!$(product_item).down('.form-product-has-subproducts');var inputs=$(product_item).select('input,select');$A(inputs).each(function(input){if(JotForm.newDefaultTheme||JotForm.newPaymentUI){$(input).observe('change',function(){mainProductObserver(product_item,product_item_input,input,mainProductPid,isSubproduct);});}else{$(input).addEventListener('change',function(){mainProductObserver(product_item,product_item_input,input,mainProductPid,isSubproduct);});}});}});$A(connectedProducts).each(function(connectedProductPid){var connected_product_item=$$('.form-product-item[pid="'+connectedProductPid+'"]')[0];var connected_product_item_input=$$('.form-product-item[pid="'+connectedProductPid+'"] .form-product-input')[0];if($(connected_product_item)){var isSubproduct=!!$(connected_product_item).down('.form-product-has-subproducts');var pairedMainProductPid=products[connectedProductPid];var inputs=$(connected_product_item).select('input,select');$A(inputs).each(function(input){if(JotForm.newDefaultTheme||JotForm.newPaymentUI){$(input).observe('change',function(){connectedProductObserver(connected_product_item,connected_product_item_input,input,pairedMainProductPid,connectedProductPid,isSubproduct);});}else{$(input).addEventListener('change',function(){connectedProductObserver(connected_product_item,connected_product_item_input,input,pairedMainProductPid,connectedProductPid,isSubproduct);});}});}});} JotForm.showCategoryTitle=showCategoryTitle;},discounts:{},pricesAfterCoupon:{},handleCategoryCouponPrices:function(action,displayOldPrice){try{for(item in JotForm.pricesAfterCoupon){var productId=item.split('_')[0];var subInputId=item.split('_')[1];var connectedPids=JotForm.categoryConnectedProducts[productId];if(connectedPids&&connectedPids.length>0){var oldTextTag=(JotForm.newDefaultTheme||JotForm.newPaymentUI)?'div':'label';var paymentFieldId=$$('input[name="simple_fpc"]')[0].value;connectedPids.forEach(function(pid){var subproductPrice=document.querySelector('#input_'+paymentFieldId+'_'+pid+'_subproducts .form-product-child-price #input_'+paymentFieldId+'_'+pid+'_'+subInputId+'_price');var isSubproduct=subInputId&&subproductPrice;var connectedId=isSubproduct?pid+'_'+subInputId:pid;var mainId=isSubproduct?productId+'_'+subInputId:productId;if(action==='reset'){$('input_'+paymentFieldId+'_'+connectedId+'_price').innerText=JotForm.pricesAfterCoupon[mainId].oldPrice;}else if(action==='apply'){var detailEl=isSubproduct?subproductPrice.up('.form-product-child-price'):$$(oldTextTag+'[for*="'+pid+'"] span.form-product-details b')[0];if(detailEl){displayOldPrice(detailEl,connectedId);} $('input_'+paymentFieldId+'_'+connectedId+'_price').innerText=JotForm.pricesAfterCoupon[mainId].newPrice;}});}} if(action==='reset'){JotForm.pricesAfterCoupon={};}}catch(error){console.log('error on showing discounted prices on connectedproducts',error);}},handleCoupon:function(){var $this=this;if(JotForm.showCategoryTitle&&JotForm.categoryConnectedProducts&&Object.keys(JotForm.categoryConnectedProducts).length>0){JotForm.handleCategoryCouponPrices('reset');} JotForm.countTotal(JotForm.prices);if($('coupon-button')){var cb=$('coupon-button'),cl=$('coupon-loader'),ci=$('coupon-input');var couponButtonMessage=$this.paymentTexts.couponApply;if(typeof FormTranslation!=='undefined'){couponButtonMessage=FormTranslation.translate(couponButtonMessage);} cb.innerHTML=couponButtonMessage||'Apply';var formID=$$('input[name="formID"]')[0].value;ci.observe('keypress',function(e){if(e.keyCode===13){e.preventDefault();cb.click();ci.blur();}});ci.enable();$$('input[name="coupon"]')[0].value="";cb.observe('click',function(){var couponMessage='';var cm=$('coupon-message');if(ci.value){cb.hide();cl.show();ci.value=ci.value.replace(/\s/g,"");cb.disable();var isStripe=((ci.hasAttribute('stripe')||ci.hasAttribute('data-stripe'))&&window.paymentType==='subscription');var isStripeCheckout=((ci.hasAttribute('stripe')||ci.hasAttribute('data-stripe'))&&['subscription','product'].indexOf(window.paymentType)>-1)&&$(ci).up('.form-line').getAttribute('data-type')==='control_stripeCheckout';JotForm._xdr(JotForm.getAPIEndpoint()+'/payment/checkcoupon','POST',JotForm.serialize({coupon:ci.value,formID:formID,stripe:isStripe,stripecheckout:isStripeCheckout,editMode:JotForm.isEditMode(),paymentID:$$('input[name="simple_fpc"]')[0].value}),function(response){try{JSON.parse(response.content);cl.hide();cb.show();couponMessage=$this.paymentTexts.couponValid||'Coupon is valid.';if(typeof FormTranslation!=='undefined'){couponMessage=FormTranslation.translate(couponMessage);} cm.innerHTML=couponMessage;cm.removeClassName('invalid') cm.addClassName('valid');JotForm.applyCoupon(response.content);}catch(e){if(response.content==="expired"){couponMessage=$this.paymentTexts.couponExpired||'Coupon is expired. Please try another one.';}else if(response.content==="ratelimiter"){couponMessage=$this.paymentTexts.couponRatelimiter||'You have reached the rate limit. Please try again after one minute.';}else{couponMessage=$this.paymentTexts.couponInvalid||'Coupon is invalid. Please try another one.';} if(typeof FormTranslation!=='undefined'){couponMessage=FormTranslation.translate(couponMessage);} cm.innerHTML=couponMessage;cm.removeClassName('valid');cm.addClassName('invalid');ci.select();cl.hide();cb.show();cb.enable();}},function(){cm.innerHTML=$this.paymentTexts.couponInvalid||'Coupon is invalid';cm.removeClassName('valid');cm.addClassName('invalid');ci.select();cl.hide();cb.show();cb.enable();});}else{couponMessage=$this.paymentTexts.couponBlank||'Please enter a coupon.';if(typeof FormTranslation!=='undefined'){couponMessage=FormTranslation.translate(couponMessage);} $('coupon-message').innerHTML=couponMessage;cm.removeClassName('valid');cm.addClassName('invalid');}}.bind(this));}},checkCouponAppliedProducts:function(){var cb=$('coupon-button'),cm=$('coupon-message');if(window.discounted_products){var discounted_products=Array.from(window.discounted_products);cleared_discounted_products=[];discounted_products.forEach(function(element,index){if(typeof(element)==="string"||typeof(element)==="number"){cleared_discounted_products[index]=element.toString();if(cleared_discounted_products.includes(selected_product_id)===true||cleared_discounted_products[0]==="all"){cb.innerHTML='Change';cm.innerHTML="Coupon is valid.";}else{cb.enable();var coupon_code_entered=document.querySelectorAll('div#coupon-container > div#coupon-table > div.jfField.isFilled').length;if(coupon_code_entered&&coupon_code_entered!==0){cm.innerHTML="Coupon code is not valid for this product.";};} $('coupon-button').addEventListener('click',function(){cm.innerHTML="";});}});}},applyCoupon:function(discount){var $this=this;discount=JSON.parse(discount);window.discounted_products=[];if(discount.products&&discount.products[0]){discount.products.forEach(function(element,index){window.discounted_products[index]=element;});} JotForm.discounts={};var cb=$('coupon-button'),cm=$('coupon-message'),ci=$('coupon-input'),cf=$(cb.getAttribute('data-qid')+'_coupon');cb.stopObserving('click');if(cf){cf.value=discount.code;} cb.enable();ci.disable();var couponButtonMessage=$this.paymentTexts.couponChange;if(typeof FormTranslation!=='undefined'){couponButtonMessage=FormTranslation.translate(couponButtonMessage);} cb.innerHTML=couponButtonMessage||'Change';cb.observe('click',function(){if(JotForm.isEditMode()){return;} cf.value='';$H(oldPrices).each(function(pair){pair[1].remove();});if(JotForm.discounts.container){JotForm.discounts.container.remove();} $$('span[id*="_price"]').each(function(field){$(field).removeClassName('underlined');});$$('span[id*="_setupfee"]').each(function(field){$(field).removeClassName('underlined');});JotForm.discounts={};cb.stopObserving('click');cm.innerHTML="";cm.removeClassName('valid');couponButtonMessage=$this.paymentTexts.couponApply;if(typeof FormTranslation!=='undefined'){couponButtonMessage=FormTranslation.translate(couponButtonMessage);} cb.innerHTML=couponButtonMessage||'Apply';ci.enable();ci.select();JotForm.handleCoupon();});var oldPrices={};var displayOldPrice=function(container,id){oldPrices[id]=document.createElement('span');var span=document.createElement('span');span.className='old_price';span.style.display='inline-block';if(window.FORM_MODE==='cardform'){span.style.textDecoration='line-through';} span.innerHTML=container.innerHTML.replace("price","price_old");var spanHidden=document.createElement('span');Object.assign(spanHidden.style,{width:'0',height:'0',opacity:'0',position:'absolute'});spanHidden.innerHTML='Discount Price';oldPrices[id].insert(span);oldPrices[id].insert(spanHidden);container.insert({top:oldPrices[id]});} if(discount.products&&discount.products.length>0){if(discount.products.include('all')){discount.products=[];for(var key in productID){discount.products.push(productID[key].slice(-4));}}} if(!discount.paymentType||(discount.paymentType&&discount.paymentType==="product")){if(discount.apply==="product"){var oldTextTag=(JotForm.newDefaultTheme||JotForm.newPaymentUI)?'div':'label';$A(discount.products).each(function(pid){JotForm.discounts[pid]=discount.rate+'-'+discount.type;$$('span[id*="_price"]').each(function(field){if(field.id.indexOf(pid)>-1){$(field).addClassName('underlined');}});var detailEl=$$(oldTextTag+'[for*="'+pid+'"] span.form-product-details b')[0];if(detailEl){displayOldPrice(detailEl,pid);JotForm.couponApplied=true;} if($$('[id*='+pid+'_subproducts]').length>0&&$$('[id*='+pid+'_subproducts]')[0].down('.form-product-child-price')){$$('#'+$$('[id*='+pid+'_subproducts]')[0].id+' .form-product-child-price').each(function(field,id){displayOldPrice(field,pid+'_'+id);});}});if(JotForm.couponApplied&&JotForm.showCategoryTitle&&JotForm.categoryConnectedProducts&&Object.keys(JotForm.categoryConnectedProducts).length>0){JotForm.handleCategoryCouponPrices('apply',displayOldPrice);}}else if(discount.apply==="total"){JotForm.discounts={total:true,code:discount.code,minimum:discount.minimum,type:discount.type,rate:discount.rate};var totalContainer=document.querySelector('.form-payment-total');if(totalContainer){var discountHTML=totalContainer.innerHTML.replace(/Total|Total:/,'Discount:').replace('payment_total','discount_total').replace('',' - ');var spanEl=document.createElement('span');spanEl.className='form-payment-discount';spanEl.innerHTML=discountHTML.replace('id="total-text"','');JotForm.discounts.container=spanEl;}}else{JotForm.discounts={shipping:true,code:discount.code,minimum:discount.minimum,type:discount.type,rate:discount.rate};}}else{if(discount.paymentType&&discount.paymentType==="subscription"){JotForm.couponApplied=true;} $A(discount.products).each(function(pid){JotForm.discounts[pid]=discount.rate+'-'+discount.type;if(discount.apply){JotForm.discounts[pid]+="-"+discount.apply;} if(discount.duration&&discount.duration===1){JotForm.discounts[pid]+="-once";} $$('span[id*="_price"]').each(function(field){if(field.id.indexOf(pid)>-1&&$$('span[id*="'+pid+'_setupfee"]').length>0&&discount.apply==="all"){$(field).addClassName('underlined');throw $break;}});$$('span[id*="_setupfee"]').each(function(field){if(field.id.indexOf(pid)>-1){$(field).addClassName('underlined');throw $break;}});});} JotForm.countTotal(JotForm.prices);},setStripeSettings:function(pubkey,add_qid,shipping_qid,email_qid,phone_qid,custom_field_qid){if(JotForm.isEditMode()||document.get.sid){return;} var scaTemplate=$$('#stripe-templates .stripe-sca-template')[0];var oldTemplate=$$('#stripe-templates .stripe-old-template')[0];if(pubkey){var clean_pubkey=pubkey.replace(/\s+/g,'');if(clean_pubkey==''){console.log('Stripe publishable key is empty. You need to connect your form using Stripe connect.');return;} var scriptVersion="v3";this.loadScript('https://js.stripe.com/'+scriptVersion+'/',function(){if(typeof _StripeSCAValidation||typeof _StripeValidation){var stripeV=new _StripeSCAValidation();JotForm.stripe=stripeV;if(oldTemplate){oldTemplate.remove();} stripeV.setFields(add_qid,shipping_qid,email_qid,phone_qid,custom_field_qid);stripeV.init(pubkey);console.log('Stripe V3 loaded');}else{if(scaTemplate){scaTemplate.remove();} if(oldTemplate){$$('.stripe-old-template input').forEach(function(input){input.setAttribute('disabled',true);})}} setTimeout(JotForm.handleIFrameHeight,300);});}else{var paymentQuestion=document.querySelector("li[data-type='control_stripe']");var isQuestionRequired='';if(window.FORM_MODE==='cardform'){isQuestionRequired=paymentQuestion.childElements()[0].querySelector(".jfRequiredStar");}else{isQuestionRequired=paymentQuestion.classList.contains('jf-required');} if(isQuestionRequired){JotForm.errored(paymentQuestion,'A connection error has occurred. Please contact form administrator for assistance.');};}},setFilePickerIOUpload:function(options){if(options&&typeof filepicker==="object"&&typeof _JF_filepickerIO==="function"){var fp=new _JF_filepickerIO(options);fp.init();}else{console.error("filepicker OR _JF_filepickerIO object library are missing");}},initCaptcha:function(id){setTimeout(function(){const UA=navigator.userAgent.toLowerCase(),IE=(UA.indexOf('msie')!=-1)?parseInt(UA.split('msie')[1],10):false;if(IE&&IE<9){if(UA.indexOf('windows nt 5.1')!=-1||UA.indexOf('windows xp')!=-1||UA.indexOf('windows nt 5.2')!=-1){JotForm.server="https://www.jotform.com/server.php";}} new Ajax.Jsonp(JotForm.url+"captcha",{evalJSON:'force',onComplete:function(t){t=t.responseJSON||t;if(t.success){document.querySelector(`#${id}_captcha`).src=t.img;document.querySelector(`#${id}_captcha_id`).value=t.num;}}});},150);},reloadCaptcha:function(id){document.querySelector(`#${id}_captcha`).src=JotForm.url+'images/blank.gif';JotForm.initCaptcha(id);},addZeros:function(n,totalDigits){n=n.toString();var pd='';if(totalDigits>n.length){for(i=0;i<(totalDigits-n.length);i++){pd+='0';}} return pd+n.toString();},formatDate:function(d){var date=d.date;var month=JotForm.addZeros(date.getMonth()+1,2);var day=JotForm.addZeros(date.getDate(),2);var year=date.getYear()<1000?date.getYear()+1900:date.getYear();var id=d.dateField.id.replace(/\w+\_/gim,'');document.querySelector('#month_'+id).value=month;document.querySelector('#day_'+id).value=day;document.querySelector('#year_'+id).value=year;if(document.querySelector('#lite_mode_'+id)){var lite_mode=document.querySelector('#lite_mode_'+id);var seperator=lite_mode.getAttribute('seperator')||lite_mode.getAttribute('data-seperator');var format=lite_mode.getAttribute('format')||lite_mode.getAttribute('data-format');var newValue=month+seperator+day+seperator+year;if(format=='ddmmyyyy'){newValue=day+seperator+month+seperator+year;}else if(format=='yyyymmdd'){newValue=year+seperator+month+seperator+day;} lite_mode.value=newValue;} if(document.querySelector('#input_'+id)){var input=document.querySelector('#input_'+id);var newValue=year+'-'+month+'-'+day;input.value=newValue;} var dateChangedEvent=document.createEvent('HTMLEvents');dateChangedEvent.initEvent('dataavailable',true,true);dateChangedEvent.eventName='date:changed';document.querySelector('#id_'+id).dispatchEvent(dateChangedEvent);},highLightLines:function(){const formLineList=document.querySelectorAll('.form-line');formLineList.forEach((formLine)=>{const highLightableList=formLine.querySelectorAll('input, select, textarea, div, table div, button, div div span[tabIndex]:not([tabIndex="-1"]), a, iframe');highLightableList.forEach(highLightable=>{highLightable.addEventListener('focus',()=>{const parentElement=formLine.parentElement;const isCollapsedLine=JotForm.isCollapsed(formLine);const isFormSectionRelated=parentElement&&(parentElement.classList.contains('form-section')||parentElement.classList.contains('form-section-closed'));const isNotCollapsingSection=isFormSectionRelated&&isCollapsedLine&&!parentElement.classList.contains('form-section-opening');if(isNotCollapsingSection||(!isFormSectionRelated&&isCollapsedLine)){const collapseBar=JotForm.getCollapseBar(formLine);collapseBar.dispatchEvent(new Event('click'));} if(!JotForm.highlightInputs){return;} formLine.classList.add('form-line-active');if(formLine.__classAdded){formLine.__classAdded=false;}});highLightable.addEventListener('blur',()=>{if(!JotForm.highlightInputs){return;} formLine.classList.remove('form-line-active');});});});},handleWidgetMessage:function(){window.addEventListener("message",function(message){try{var shittyParseMessageData=function(msg){if(typeof msg==='string'){var parsed=JSON.parse(msg);return typeof parsed.data==='string'?JSON.parse(parsed.data):parsed.data;}else if(typeof msg==='object'&&typeof msg.data==='string'&&msg.data[0]=='{'){return JSON.parse(msg.data);}else if(typeof msg==='object'&&typeof msg.data==='object'){return msg.data;} return msg;};var parsedMessageData=shittyParseMessageData(message);if(parsedMessageData&&parsedMessageData.type){switch(parsedMessageData.type){case'collapse':JotForm.widgetSectionCollapse(parsedMessageData.qid);break;case'fields:fill':JotForm.runAllCalculations();break;default:break;}}}catch(e){console.error('ErrorOnHandleWigetMessage',e);}},false);},widgetSectionCollapse:function(qid){if(qid){var el=document.getElementById('cid_'+qid);if(JotForm.isCollapsed(el)){JotForm.getCollapseBar(el).run('click');}}},getForm:function(element){if(typeof element==='string'){element=document.getElementById(element);} if(!element||!element.parentNode){return false;} if(element&&element.tagName=="BODY"){return false;} if(element.tagName=="FORM"){return element;} return JotForm.getForm(element.parentNode);},getContainer:function(element){if(typeof element==='string'){element=document.getElementById(element);} if(!element||!element.parentNode){return false;} if(element&&element.tagName=="BODY"){return false;} if(element.classList.contains("form-line")){return element;} return JotForm.getContainer(element.parentNode);},getSection:function(element){if(typeof element==='string'){element=document.getElementById(element);} if(!element||!element.parentNode){return false;} if(element&&element.tagName=="BODY"){return false;} if((element.classList.contains("form-section-closed")||element.classList.contains("form-section"))&&!element.id.match(/^section_/)){return element;} return JotForm.getSection(element.parentNode);},getCollapseBar:function(element){if(typeof element==='string'){element=document.getElementById(element);} if(!element||!element.parentNode){return false;} if(element&&element.tagName=="BODY"){return false;} if(element.classList.contains("form-section-closed")||element.classList.contains("form-section")){return element.querySelector('.form-collapse-table');} return JotForm.getCollapseBar(element.parentNode);},isCollapsed:function(element){if(typeof element==='string'){element=document.getElementById(element);} if(!element||!element.parentNode){return false;} if(element&&element.tagName=="BODY"){return false;} if(element.className=="form-section-closed"){return true;} return JotForm.isCollapsed(element.parentNode);},isVisible:function(element){if(typeof element==='string'){element=document.getElementById(element);} if(!element||!element.parentNode){return false;} if(element.classList.contains('always-hidden')){return false;} if(element&&element.tagName=="BODY"){return true;} if(element.classList.contains("form-textarea")&&element.parentNode.querySelector('.nicEdit-main')&&(element.closest('.form-line')&&JotForm.isVisible(element.closest('.form-line')))){return true;} if(element.style.display=="none"||element.style.visibility=="hidden"||element.classList.contains('js-non-displayed-page')){return false;} return JotForm.isVisible(element.parentNode);},sectionHasVisibleiFrameWidgets:function(section){var elements=section.select('.custom-field-frame');var hasVisible=false;elements.each(function(el){if(JotForm.isVisible(el)){hasVisible=true;throw $break;}});return hasVisible;},enableDisableButtonsInMultiForms:function(){const allButtons=document.querySelectorAll('.form-submit-button');allButtons.forEach(function(b){if(b.closest('ul.form-section')){if(b.closest('ul.form-section').style.display=="none"||b.closest('ul.form-section').classList.contains('js-non-displayed-page')){b.disabled=true;}else{if(b.className.indexOf("disabled")==-1&&!b.classList.contains("conditionallyDisabled")){b.disabled=false;}}}});},enableButtons:function(){setTimeout(function(){document.querySelectorAll('.form-submit-button').forEach(function(b){if(!b.classList.contains("conditionallyDisabled")){b.disabled=false;} if(b.innerHTML.indexOf('0){var zeroValue='0';if(!!JotForm.currencyFormat.decimal){zeroValue='0'+JotForm.currencyFormat.dSeparator+'00';} document.querySelectorAll('span[id*="_item_subtotal"]').forEach(function(el){el.innerHTML=zeroValue;});} document.querySelectorAll('.form-product-input').forEach(function(item){if(window.FORM_MODE!=='cardform'&&item.checked===true){item.click();}});JotForm.countTotal();} if(JotForm.browserIs.chrome()&&document.querySelector('#coupon-button')){setTimeout(function(){if(document.querySelector('#payment_total')){JotForm.totalCounter(JotForm.prices);}},40);return true;}} document.querySelectorAll(".form-line-error").forEach(function(tmp){tmp.classList.remove("form-line-error");});document.querySelectorAll(".form-error-message",".form-button-error").forEach(function(tmp){tmp.remove();});document.querySelectorAll(".form-textarea-limit-indicator > span").forEach(function(tmp){var raw=tmp.innerHTML;tmp.innerHTML=raw.replace(raw.substring(0,raw.indexOf("/")),"0");});document.querySelectorAll("span[id^=grade_point_]").forEach(function(tmp){tmp.innerHTML=0;});document.querySelectorAll(".form-grading-error").forEach(function(tmp){tmp.innerHTML="";});var autofill=document.querySelectorAll('form')[0].getAttribute('data-autofill');if(autofill){setTimeout(function(){for(var inputId in JotForm.defaultValues){var input=document.querySelector('#'+inputId);if(input&&(input.type=="radio"||input.type=="checkbox")){input.checked=true;}} var formID=document.querySelector('form').getAttribute('id')+document.querySelector('form').getAttribute('name');var autoFillInstance=AutoFill.getInstance(formID);if(autoFillInstance){if(window.location.href.indexOf('jotform.pro')===-1){autoFillInstance.saveAllData();}}},40);} setTimeout(function(){document.querySelectorAll('.custom-hint-group').forEach(function(element){element.hasContent=(element.value&&element.value.replace(/\n/gim,"
")!=element.getAttribute('data-customhint'))?true:false;element.showCustomPlaceHolder();});},30);setTimeout(function(){document.querySelectorAll('.nicEdit-main').forEach(function(richArea){var txtarea=richArea.closest('.form-line').querySelector('textarea');if(txtarea){if(txtarea.classList.contains('custom-hint-group')&&!txtarea.hasContent){richArea.setStyle({'color':'#babbc0'});}else{richArea.setStyle({'color':''});} richArea.innerHTML=txtarea.value;}});},40);setTimeout(function(){if(document.querySelector('#coupon-button')&&document.querySelector('#coupon-button').triggerEvent){document.querySelector('#coupon-button').triggerEvent("click");} if(document.querySelector('#payment_total')){JotForm.totalCounter(JotForm.prices);}},40);setTimeout(function(){document.querySelectorAll('input.form-widget').forEach(function(node){node.value='';let clearWidgetEvent=document.createEvent('HTMLEvents');clearWidgetEvent.initEvent('dataavailable',true,true);clearWidgetEvent.eventName='widget:clear';clearWidgetEvent.memo={qid:parseInt(node.id.split('_')[1])} node.dispatchEvent(clearWidgetEvent)});},40);setTimeout(function(){document.querySelectorAll('.currentDate').forEach(function(el){var id=el.id.replace(/day_/,"");JotForm.formatDate({date:(new Date()),dateField:document.querySelector('#id_'+id)});});document.querySelectorAll('.currentTime').forEach(function(el){if(el.closest(".form-line")){var id=el.closest(".form-line").id.replace("id_","");if(document.querySelector("#hour_"+id)){JotForm.displayLocalTime("hour_"+id,"min_"+id,"ampm_"+id);}else{JotForm.displayLocalTime("input_"+id+"_hourSelect","input_"+id+"_minuteSelect","input_"+id+"_ampm","input_"+id+"_timeInput",false)}}});},40);setTimeout(function(){JotForm.runAllConditions();},50);};});},setPrintButtonActions:function(){document.querySelectorAll('.form-submit-print').forEach(function(print_button){print_button.addEventListener("click",function(){print_button.parentNode.style.display='none';const hidden_nicedits_arr=[];const nicedit_textarea_to_hide=[];document.querySelectorAll('.form-textarea, .form-textbox').forEach(function(el){if(el.classList.contains("form-textarea")&&"nicEditors"in window){document.querySelectorAll("#cid_"+el.id.split("_")[1]+" > div:nth-child(1)").forEach(function(tmpel){if(tmpel.getAttribute('unselectable')=="on"){const[toolbarEl,containerEl]=Array.from(document.querySelectorAll("#cid_"+el.id.split("_")[1]+" > div"));toolbarEl.style.display='none';containerEl.style.borderTopColor='rgb(204, 204, 204)';containerEl.style.borderTopStyle='solid';containerEl.style.borderWidth='1px';hidden_nicedits_arr.push(toolbarEl);nicedit_textarea_to_hide.push(el);}});}});window.print();for(let i=0;i0;var minTotalOrderAmount=hasMinTotalOrderAmount===true?minTotalOrderAmountHiddenField[0].value:'0';JotForm.minTotalOrderAmount=minTotalOrderAmount;return hasMinTotalOrderAmount;},isValidMinTotalOrderAmount:function(){if(JotForm.hasMinTotalOrderAmount()&&parseInt(JotForm.minTotalOrderAmount)>0){if(!!(JotForm.pricingInformations&&JotForm.pricingInformations.general&&JotForm.pricingInformations.general.discount>0)){return(JotForm.getPaymentTotalAmount()+JotForm.pricingInformations.general.discount)>=parseInt(JotForm.minTotalOrderAmount)} return JotForm.getPaymentTotalAmount()>=parseInt(JotForm.minTotalOrderAmount);} return true;},handleMinTotalOrderAmount:function(){if(JotForm.isPaymentSelected()===true&&!this.isValidMinTotalOrderAmount()){JotForm.corrected(document.querySelectorAll('[data-payment]')[0]);var errorTxt=JotForm.texts.ccDonationMinLimitError.replace('{minAmount}',JotForm.minTotalOrderAmount).replace('{currency}',JotForm.currencyFormat.curr);JotForm.errored(document.querySelectorAll('[data-payment]')[0],errorTxt);return true;} return false;},hasHiddenValidationConflicts:function(input){const hiddenOBJ=input.closest('li.form-line');return hiddenOBJ&&(hiddenOBJ.classList.contains('form-field-hidden')||hiddenOBJ.closest('ul.form-section').classList.contains('form-field-hidden'));},initGradingInputs:function(){const _this=this;document.querySelectorAll('.form-grading-input').forEach(item=>{item.validateGradingInputs=function(){const item=this;const id=item.id.replace(/input_(\d+)_\d+/,"$1");let total=0;let _parentNode=item.parentNode.parentNode;const numeric=/^(\d+[\.]?)+$/;let isNotNumeric=false;if(window.FORM_MODE==='cardform'){_parentNode=_parentNode.parentNode;} item.errored=false;_parentNode.querySelectorAll(".form-grading-input").forEach(sibling=>{if(sibling.value&&!numeric.test(sibling.value)){isNotNumeric=true;throw{};} total+=parseFloat(sibling.value)||0;});if(_this.hasHiddenValidationConflicts(item))return JotForm.corrected(item);if(isNotNumeric){return JotForm.errored(item,JotForm.texts.numeric);} const gradeTotalElement=document.querySelector(`#grade_total_${id}`);if(gradeTotalElement){const gradeErrorElement=document.querySelector(`#grade_error_${id}`);gradeErrorElement.innerHTML="";const allowed_total=parseFloat(gradeTotalElement.innerHTML);document.querySelector(`#grade_point_${id}`).innerHTML=total;if(total>allowed_total){gradeErrorElement.innerHTML=' '+JotForm.texts.lessThan+' '+allowed_total+'.';return JotForm.errored(item,JotForm.texts.gradingScoreError+" "+allowed_total);} else{return JotForm.corrected(item);}}else{return JotForm.corrected(item);}} item.addEventListener('blur',()=>{item.validateGradingInputs();});item.addEventListener('keyup',()=>{item.validateGradingInputs();});});},initSpinnerInputs:function(){document.querySelectorAll('.form-spinner-input').forEach(function(item){item.addEventListener('blur',function(){item.validateSpinnerInputs();}) item.addEventListener('change',function(){item.validateSpinnerInputs();});const c_parent=item.closest('.form-spinner') const c_up=c_parent.querySelector('.form-spinner-up');const c_down=c_parent.querySelector('.form-spinner-down');c_up.addEventListener('click',function(){item.validateSpinnerInputs();});c_down.addEventListener('click',function(){item.validateSpinnerInputs();});item.validateSpinnerInputs=function(){var item=this,numeric=/^(-?\d+[\.]?)+$/,numericDotStart=/^([\.]\d+)+$/,userInput=item.value||0;item.errored=false;if(!JotForm.isVisible(item))return JotForm.corrected(item);if(userInput&&!numeric.test(userInput)&&!numericDotStart.test(userInput)){return JotForm.errored(item,JotForm.texts.numeric);} if(item.hasClassName("disallowDecimals")&&userInput%1!=0){return JotForm.errored(item,JotForm.texts.disallowDecimals);} var min_val=parseInt(item.readAttribute('data-spinnermin')),max_val=parseInt(item.readAttribute('data-spinnermax'));if((min_val||min_val==0)&&userInputmax_val){return JotForm.errored(item,JotForm.getValidMessage(JotForm.texts.inputCarretErrorB,max_val));} else{return JotForm.corrected(item);}}});},initTestEnvForNewDefaultTheme:function(){if(window&&window.location&&window.location.search){var params=window.location.search;if(params.indexOf('ndtTestEnv=1')>-1){var formSection=document.querySelector('.form-all')||null;if(formSection)formSection.classList.add('ndt-test-env');}}},initTimev2Inputs:function(){const inputs=document.querySelectorAll('input[id*="timeInput"][data-version="v2"]');let userClickDetected=false;let userTouchDetected=false;if(navigator.userAgent.match(/Android/i)){window.addEventListener('click',function(){userClickDetected=true;setTimeout(function(){userClickDetected=false;},500);});window.addEventListener('touchstart',function(){userTouchDetected=true;setTimeout(function(){userTouchDetected=false;},500);});} const dateTimeOnComplete=function(e){const values=e.target.value.split(':');const hh=e.target.parentElement.querySelector('input[id*="hourSelect"]');const mm=e.target.parentElement.querySelector('input[id*="minuteSelect"]');hh.value=values[0];mm.value=values[1];hh.dispatchEvent(new Event('change'));mm.dispatchEvent(new Event('change'));JotForm.runConditionForId(e.target.up('li.form-line').id.replace('id_',''));} const timeInputEvent=function(e){if(e.target.value&&/^[0-9]{2}:[0-9]{2}$/.test(e.target.value)){dateTimeOnComplete(e);}} for(let i=0;i0){inputs[i].addEventListener('blur',function(e){if(!userClickDetected&&!userTouchDetected){const timeDropdownSelector=e.target.id.replace('timeInput','ampm');const timeDropdown=document.getElementById(timeDropdownSelector);timeDropdown.focus();}});}}}catch(e){return;}}},renderTermsAndConditions:function(settings){if(settings.data.data==='termsAndConditions'){var main=document.querySelector('.form-all');var container=document.createElement('div');container.id='terms_conditions_modal';container.style.display='block';var content=document.createElement('div');content.className='terms-conditions-content';var sectionPart=document.createElement('section');sectionPart.className="terms-header";content.appendChild(sectionPart);var headerText=document.createElement('h1');headerText.textContent='Terms and Conditions';var otherText=document.createElement('h3');otherText.textContent='Please read carefully our latest terms and conditions.';var buttonCancel=document.createElement('button');buttonCancel.type='button';buttonCancel.id='terms_conditions_modal_cancel';buttonCancel.textContent='X';buttonCancel.addEventListener('click',closeModel);sectionPart.appendChild(headerText);sectionPart.appendChild(otherText);sectionPart.appendChild(buttonCancel);var iframe=document.createElement('iframe');iframe.src=linkValidation(settings.data.settings.termsLink);iframe.allow='fullscreen';iframe.className='iframeModel';content.appendChild(iframe);var agreeButton=document.createElement('button');agreeButton.type='button';agreeButton.id='terms_conditions_modal_accept';agreeButton.textContent='I Agree';agreeButton.addEventListener('click',sendData);content.appendChild(agreeButton);container.appendChild(content);main.appendChild(container);} function sendData(){var id='#customFieldFrame_'+settings.data.settings.qid;var widgetIframe=document.querySelector(id).contentWindow;widgetIframe.postMessage({data:'termsAndConditions',settings:{qid:settings.data.settings.qid,status:'accepted'}},'*');closeModel();} function closeModel(){container.style.display='none';} function linkValidation(link){if(link&&link.length>0){var validation=link.search("http:\/\/");link=(validation>=0||link.toLowerCase().indexOf('https')>=0)?link:'https:\/\/'+link;}else{link="https://www.jotform.com";} return link;}},getMessageFormTermsAndCondition:function(){if(window.location.href.indexOf('ndt=1')===-1)return;window.addEventListener('message',this.renderTermsAndConditions,true);},makeReadyWidgets:function(){var widgetList=['5345402093a2afcc5f000004'];var widgetsFrames=document.querySelectorAll('iframe.custom-field-frame');for(var i=0;i0){if(typeof FormTranslation!=='undefined'){JotForm.onTranslationsFetch(initDateV2LiteModeInputs);} JotForm.onLanguageChange(initDateV2LiteModeInputs);}},dropDownColorChange:function(){const dropDownFields=document.querySelectorAll('select.form-dropdown');if(dropDownFields){for(let i=0;imax_val){return JotForm.errored(item,JotForm.getValidMessage(JotForm.texts.maxCharactersError,max_val));} else{let error=false if(item.closest('.form-matrix-table')){item.closest('.form-matrix-table').querySelectorAll('input').forEach(function(el){if((el!==item)&&el.classList.contains('form-validation-error')){error=true;}});} if(!error){return JotForm.corrected(item);}}}})},handleZeroQuantityProducts:function(){try{const field=document.querySelectorAll('input[name="simple_fpc"]');const paymentField=field&&field[0]?field[0].closest('.form-line'):null;if(paymentField!==null&&!(window.FORM_MODE&&window.FORM_MODE=='cardform')){const productsElement=document.querySelectorAll('.form-product-item');productsElement.forEach(function(item){item.querySelectorAll('select, input').forEach(function(elems){if((elems.hasAttribute('id')&&elems.getAttribute('id').indexOf('quantity')>-1)||elems.className.includes('form-product-input')){['change','blur'].forEach(function(eventName){elems.addEventListener(eventName,function(){JotForm.preventProductQuantityEmpty();})})}});});}}catch(e){console.log('Empty Product Prevent :: handleZeroQuantityProducts ::',e);}},checkProductSelectionWithQuantity:function(productElement){try{let quantityCount=0;let hasQuantity=false;if(productElement.querySelectorAll('table').length>0){productElement.querySelectorAll('.form-subproduct-quantity').forEach(function(quantityEl){quantityCount+=parseInt(quantityEl.value);hasQuantity=true;})}else{productElement.querySelectorAll('select, input').forEach(function(inputs){if(inputs.getAttribute('id').indexOf('quantity')>-1){quantityCount+=parseInt(inputs.value);hasQuantity=true;}});} return hasQuantity?quantityCount!==0:true;}catch(e){console.log('Empty Product Prevent :: getEmptyRequiredProduct ::',e);}},erroredQuantityFields:function(productElement,addORRemove){try{const action=(typeof addORRemove=='undefined'||addORRemove==null||addORRemove=='add')?'add':'remove';if(productElement.querySelectorAll('table').length>0){productElement.querySelectorAll('.form-subproduct-quantity').forEach(function(quantityEl){if(action=='add'){quantityEl.classList.add('form-validation-error');}else{quantityEl.classList.remove('form-validation-error');}})}else{productElement.querySelectorAll('select, input').forEach(function(inputs){if(inputs.getAttribute('id').indexOf('quantity')>-1){if(action=='add'){inputs.classList.add('form-validation-error');}else{inputs.classList.remove('form-validation-error');}}});}}catch(e){console.log('errorQuantityFields :: ',e);}},preventProductQuantityEmpty:function(){const field=document.querySelectorAll('input[name="simple_fpc"]');const erroredProducts={};const correctedProducts=[];const paymentField=field&&field[0]?field[0].closest('.form-line'):null;try{if(paymentField!==null&&paymentField!==undefined&&JotForm.isVisible(paymentField)&&!(window.FORM_MODE&&window.FORM_MODE=='cardform')){document.querySelectorAll('.form-product-item').forEach(function(item){const productCheckbox=item.querySelector('.form-product-input');if(productCheckbox!==undefined&&productCheckbox.checked){if(!JotForm.checkProductSelectionWithQuantity(item)){erroredProducts[item.getAttribute('pid')]=item;}else{erroredProducts[item.getAttribute('pid')]=null;correctedProducts.push(item);}}else{erroredProducts[item.getAttribute('pid')]=null;correctedProducts.push(item);}});const erroredProductsArr=Object.values(erroredProducts);erroredProductsArr.forEach(function(item){if(item!==null){JotForm.erroredQuantityFields(item,'add');}});correctedProducts.forEach(function(item){JotForm.erroredQuantityFields(item,'remove');});const count=erroredProductsArr.filter(function(item){return item!==null});if(count.length>0){JotForm.errored(paymentField,'Selected product quantity cannot be less than 1.');}else{JotForm.corrected(paymentField);} return!(count.length>0);} return true;}catch(e){if(paymentField!==null&&paymentField!==undefined&&JotForm.isVisible(paymentField)){JotForm.errored(paymentField,'Selected product quantity cannot be less than 1.');} return false;}},initNumberInputs:function(){document.querySelectorAll('.form-number-input').forEach(function(item){item.addEventListener('blur',function(){item.validateNumberInputs();}) item.addEventListener('change',function(){item.validateNumberInputs();}) item.addEventListener('keyup',function(){item.validateNumberInputs();}) item.addEventListener('keypress',function(event){if(event.metaKey||event.ctrlKey){return;} const controlKeys=[8,9,13,35,36,37,39];const isControlKey=controlKeys.join(",").match(new RegExp(event.which));if(!event.which||(48<=event.which&&event.which<=57)||(46==event.which)||(45==event.which)||(43==event.which)||isControlKey){if(event.which!=8&&event.which!=0&&event.which!=13&&(parseInt(this.value.length)>=parseInt(item.readAttribute('maxlength'))||(event.which<45||event.which>57))){event.preventDefault();}else{return;}}else{event.preventDefault();}}) item.addEventListener('wheel',function(event){event.preventDefault();}) item.addEventListener('paste',function(event){const pastedText=(event.clipboardData||window.clipboardData).getData('text');if(isNaN(parseFloat(pastedText))||pastedText.trim()===''){event.preventDefault();}}) item.validateNumberInputs=function(){const item=this;const numeric=/^-?(\d+[\.]?)+$|([\.]\d+)+$/;item.errored=false;if(!JotForm.isVisible(item))return JotForm.corrected(item);if(item.value!==''&&!numeric.test(item.value)&&item.hinted!==true){return JotForm.errored(item,JotForm.texts.numeric);} const min_val=parseInt(item.readAttribute('data-numbermin'));const max_val=parseInt(item.readAttribute('data-numbermax'));const max_len=parseInt(item.readAttribute('maxlength'));if(max_len&&item.value&&item.value.length>max_len){return JotForm.errored(item,JotForm.texts.maxDigitsError+" "+max_len);} else if((min_val||min_val==0)&&parseFloat(item.value)max_val){return JotForm.errored(item,JotForm.getValidMessage(JotForm.texts.inputCarretErrorB,max_val));} else{let error=false if(item.closest('.form-matrix-table')){item.closest('.form-matrix-table').querySelectorAll('input').forEach(function(el){if((el!==item)&&el.classList.contains('form-validation-error')){error=true;}});} if(!error){return JotForm.corrected(item);}}}});},backStack:[],currentSection:false,visitedPages:{},autoNext:function(id){if(!$("cid_"+id))return;var prev=$("cid_"+id).previous();if(!prev)return;var type=prev.readAttribute('data-type');if(type!=='control_radio'&&type!=='control_dropdown')return;var isEmpty=function(target){if(!target){return true;} if(target.tagName.toLowerCase()==="input"){return target.checked===false;} var targetOptions=target.querySelectorAll('input:checked[type=radio], option:checked:not([value=""])');return targetOptions.length===0;} prev.observe("change",function(e){if(!JotForm.isVisible(prev)||isEmpty(e.target)){return;} if(e.target.hasClassName('form-radio-other')){return;} var nextButton=$("cid_"+id).down('.form-pagebreak-next') if(nextButton&&nextButton.triggerEvent){nextButton.focus();nextButton.setStyle({'fontWeight':'bold'});setTimeout(function(){if(JotForm.currentSection===JotForm.getSection(prev)){nextButton.setStyle({'fontWeight':'inherit'}) nextButton.triggerEvent('mousedown');nextButton.triggerEvent('click');}},800);}});},handlePages:function(){var $this=this;var pages=[];var last;var formLabelLeftList=document.querySelectorAll('.form-label-left') if(formLabelLeftList.length>0){var labelWidth=parseInt(document.defaultView.getComputedStyle(formLabelLeftList[0]).width);var formWidth=parseInt(document.defaultView.getComputedStyle(document.querySelector('.form-all')).width);var backButtonWidth=labelWidth>formWidth/2?formWidth/2:labelWidth;document.querySelectorAll('.form-pagebreak-back-container').forEach(back=>{if(back.style.width===''){back.style.width=(backButtonWidth-14)+'px';}});} document.querySelectorAll('.form-pagebreak').forEach(function(page,i){const section=page.parentNode.parentNode;if(i>=1){section.style.display='none';}else{JotForm.currentSection=section;JotForm.visitedPages[i+1]=true;} pages.push(section);section.pagesIndex=i+1;function stopEnterKey(evt){var evt=(evt)?evt:((event)?event:null);var isSpace=evt.which==32||evt.code==='Space';var isEnter=evt.keyCode==13||evt.code==='Enter';var node=(evt.target)?evt.target:((evt.srcElement)?evt.srcElement:null);if(isEnter&&["text","email","tel","number","radio","checkbox","select-one","select-multiple"].include(node.type)){return false;} if((isEnter||isSpace)&&evt.target.classList.contains('form-pagebreak-next')&&evt.target.triggerEvent){evt.target.triggerEvent('mousedown');}} document.onkeypress=stopEnterKey;var checkLanguageDropdownPage=function(){if(typeof FormTranslation!=='undefined'&&FormTranslation.properties&&FormTranslation.properties.firstPageOnly==='1'){var ddList=document.querySelectorAll('.language-dd');var dd=ddList.length>0?ddList[0]:false;if(!dd)return;var displayValue=JotForm.currentSection===pages[0]?'':'none';dd.style.display=displayValue;}} var form=JotForm.getForm(section) section.querySelectorAll('.form-pagebreak-next').forEach(el=>{el.addEventListener('click',()=>{if(JotForm.saving||JotForm.loadingPendingSubmission){return;} if((JotForm.validateAll(form,section))||getQuerystring('qp')!==""){if(!$this.noJump&&window.parent&&window.parent!=window){window.parent.postMessage('scrollIntoView::'+form.id,'*');} if(!JotForm.nextPage){var sections=[...document.querySelectorAll('.form-all > .page-section')];for(var i=sections.indexOf(section);i{el.remove();});document.querySelectorAll('.form-pagebreak-next').forEach(nextButton=>{if(JotForm.isSourceTeam){return;} var errorBox=document.createElement('div');errorBox.className='form-button-error';errorBox.append(JotForm.texts.generalPageError);nextButton.parentNode.parentNode.append(errorBox);});}catch(e){}} JotForm.setPagePositionForError();});});section.querySelectorAll('.form-pagebreak-back').forEach(el=>{el.addEventListener('click',()=>{if(!$this.noJump&&window.parent&&window.parent!=window){window.parent.postMessage('scrollIntoView::'+form.id,'*');} if(JotForm.saving||JotForm.loadingPendingSubmission){return;} JotForm.hideFormSection(section);var sections=[...document.querySelectorAll('.form-all > .page-section')];var prevPage=JotForm.backStack.pop();while(JotForm.backStack.length>0){var pageNumber=sections.indexOf(prevPage)+1;if(JotForm.hidePages[pageNumber]===true){prevPage=JotForm.backStack.pop();continue;} break;} JotForm.currentSection=JotForm.showFormSection(prevPage);if(!$this.noJump&&window.parent==window){scrollTo(0,0);} JotForm.nextPage=false;JotForm.enableDisableButtonsInMultiForms();if(JotForm.saveForm){if(window.JFFormUserHelper&&window.JFFormUserHelper.SCLManager){window.JFFormUserHelper.SCLManager.hiddenSubmit();}else{JotForm.hiddenSubmit(JotForm.getForm(section));}} document.querySelectorAll('.form-button-error').forEach(el=>{el.remove();});JotForm.iframeHeightCaller();checkLanguageDropdownPage();prevPage.querySelectorAll('.form-line[data-type=control_widget]').forEach(function(e){var field=e.id.split('_').last();JotForm.showWidget(field,true);});setTimeout(function(){JotForm.runAllCalculations(true);},10);JotForm.updateErrorNavigation(false);})});});if(pages.length>0){var allSections=document.querySelectorAll('.form-section:not([id^=section_])');if(allSections.length>0){last=allSections[allSections.length-1];} if(last){last.pagesIndex=allSections.length;pages.push(last);last.style.display='none';var mergeWithSubmit=false;var targetSubmit=null;if(JotForm.newDefaultTheme||JotForm.extendsNewTheme){var submitButtons=last.querySelectorAll('li[data-type="control_button"] .form-buttons-wrapper');if(submitButtons.length>0){mergeWithSubmit=true;targetSubmit=submitButtons[(submitButtons.length-1)];targetSubmit.classList.add("form-pagebreak");}} var backCont=document.createElement('div');backCont.className='form-pagebreak-back-container';var backButtonContainers=document.querySelectorAll('.form-pagebreak-back-container');var back=backButtonContainers[0].querySelector('button');var penultimateBack=backButtonContainers[backButtonContainers.length-1].querySelector('button');var isHiddenButton=penultimateBack.classList.contains('button-hidden');back.textContent=penultimateBack?penultimateBack.textContent:back.textContent back.className=back.className.replace(/\bform-submit-button-\S+/g,"");var submitButtonElement=document.querySelector('li[data-type="control_button"] .submit-button');if(submitButtonElement){if(isHiddenButton){submitButtonElement.classList.add('button-hidden');} submitButtonElement.classList.forEach(cls=>{if(cls.startsWith('form-submit-button-')||cls=='button-hidden'){back.setAttribute("class",cls+" form-pagebreak-back jf-form-buttons")}});} if(!isHiddenButton){back.classList.remove('button-hidden');} backCont.append(back);if(mergeWithSubmit){targetSubmit.prepend(backCont);var buttonOrder=['form-pagebreak-back-container','form-submit-preview','form-submit-print','form-submit-reset','paypal-submit-button-wrapper','form-sacl-button','form-submit-button:not(.form-sacl-button)','useJotformSign-button','form-pagebreak-next-container'];buttonOrder.forEach(btnClass=>{[...targetSubmit.children].forEach(child=>{if(child.matches('.'+btnClass)){targetSubmit.append(child);}});});}else{var li=document.createElement('li');li.classList.add('form-input-wide');var cont=document.createElement('div');cont.classList.add('form-pagebreak');cont.append(backCont);li.append(cont);last.append(li);} back.addEventListener('click',function(){if(JotForm.saving){return;} last.style.display='none';JotForm.nextPage=false;});}}},jumpToPage:function(page,validatePages){if(!page&&document.get.jumpToPage&&JotForm.submissionToken&&(JotForm.sessionID||'').indexOf('JF-S4L')>-1)return;var page=page||document.get.jumpToPage;const sections=Array.from(document.querySelectorAll('.form-section:not([id^=section_])'));const currentSection=sections[page-1];if(!(page&&page>0)||page>sections.length)return;for(let i=0;i1)JotForm.backStack=sections.splice(0,page-1);JotForm.runAllCalculations(true);currentSection.querySelectorAll('.form-line[data-type=control_widget]').forEach(function(e){const field=e.id.split('_').last();JotForm.showWidget(field,true);});},doubleValidationFlag:function(){if(getQuerystring('doubleValidation')==='0')return false;return true;},isInputAlwaysHidden:function(input){if(window.FORM_MODE==='cardform'){return!JotForm.isVisible(input);} const jfField=input.closest('.jfField');if(jfField&&jfField.classList.contains('isHidden')){return true;} const addressLineWrapper=input.closest('.form-address-line-wrapper')||input.closest('.form-address-line');if(addressLineWrapper){if(addressLineWrapper.style.display=="none"||addressLineWrapper.style.visibility=="hidden"){return true;} if(!!input.closest('.form-address-hiddenLine')){return true;}} const collapseSection=input.closest('.form-section[id^="section_"], .form-section-closed[id^="section_"]');if(collapseSection){const hiddenWithStyles=collapseSection.style.display=="none"||collapseSection.style.visibility=="hidden";const hiddenWithClasses=collapseSection.classList.contains('always-hidden')||collapseSection.classList.contains('form-field-hidden');if(hiddenWithStyles||hiddenWithClasses){return true;}} const paymentDummyInputIds=['stripesca_dummy','stripePe_dummy','mollie_dummy','square_dummy','braintree_dummy','paypal_complete_dummy'];if(paymentDummyInputIds.indexOf(input.id)>-1){return true;} if(JotForm.payment==='paypalpro'&&input.closest('#creditCardTable')&&input.closest('#creditCardTable').style.display==="none"){return true;} const cont=JotForm.getContainer(input);return cont.classList.contains('always-hidden')||cont.classList.contains('form-field-hidden')||(cont.style&&cont.style.display=="none")||(cont.style&&cont.style.visibility=="hidden");},isSectionTouched:function(section){if(!section)return false;var isPageBreak=!!document.querySelector('.form-pagebreak');if(!isPageBreak)return true;var pagesIndex=section.pagesIndex;if(typeof pagesIndex==='undefined'&§ion.parentNode){pagesIndex=section.parentNode.pagesIndex;} if(pagesIndex>JotForm.currentSection.pagesIndex)return false;if(JotForm.visitedPages[pagesIndex]&&!JotForm.hidePages[pagesIndex])return true;},hideFormSection:function(section){section.classList.add('js-non-displayed-page') section.style.display='none';section.style.position='absolute';section.style.top='-9999px';section.style.left='-9999px';return section;},showFormSection:function(section){section.classList.remove('js-non-displayed-page');section.style.display='';section.style.position='';section.style.top='';section.style.left='';JotForm.visitedPages[section.pagesIndex]=true;var visitedPages=Object.keys(JotForm.visitedPages);for(var i=0;isection.pagesIndex){delete JotForm.visitedPages[visitedPages[i]];}} if(!this.noJump&&(window!==window.top||JotForm.isFullSource===true)){var form=JotForm.forms[0]||document.querySelector('.jotform-form');if(form){setTimeout(function(){form.scrollIntoView(true);},50);}} return section;},getDimensions:element=>{const computedStyles=window.getComputedStyle(element);if(computedStyles.display&&computedStyles.display!=='none'){return{width:element.offsetWidth,height:element.offsetHeight};} const{visibility,position,display}=element.style;element.style.display='block';element.style.visibility='hidden';element.style.position=position!=='fixed'?'absolute':position;const dimensions={width:element.offsetWidth,height:element.offsetHeight};element.style.display=display;element.style.position=position;element.style.visibility=visibility;return dimensions;},handleFormCollapse:function(){var openBar=false;var openCount=0;var height=JotForm.newDefaultTheme||JotForm.extendsNewTheme?84:60;var collapseTableList=document.querySelectorAll('.form-collapse-table');collapseTableList.forEach(bar=>{var section=bar.parentNode.parentNode;if(section.className=="form-section-closed"){section.closed=true;}else{if(section.querySelectorAll('.form-collapse-hidden').length<0){openBar=section;openCount++;}} bar.setAttribute("role","button");bar.setAttribute("tabindex",0);bar.setAttribute("aria-pressed",false);function handleFormCollapseChecker(){if(section.closed){section.style.height='auto';section.style.overflow='visible';var h=JotForm.getDimensions(section).height;if(openBar&&openBar!=section&&openCount<=1){openBar.className="form-section-closed";openBar.shift({height:height,duration:0.25});openBar.querySelectorAll('.form-collapse-right-show').forEach(e=>{e.classList.add('form-collapse-right-hide');e.classList.remove('form-collapse-right-show');});openBar.style.overflow='hidden';openBar.closed=true;} openBar=section;section.style.overflow='hidden';section.style.height=`${height}px`;setTimeout(function(){section.scrollTop=0;section.className="form-section";},1);section.shift({height:h,duration:0.5,onStart:function(){section.querySelectorAll('.form-line[data-type=control_widget]').forEach(e=>{var field=e.id.split('_').last();JotForm.showWidget(field,true);});section.classList.add('form-section-opening');},onEnd:function(e){e.scrollTop=0;e.style.height='auto';e.style.overflow='visible';if(!JotForm.noJump){e.scrollIntoView();}},onStep:function(){if(window.parent&&window.parent!=window){window.parent.postMessage('setHeight:'+$$('body')[0].getHeight(),'*');}}});section.querySelectorAll('.form-collapse-right-hide').forEach(e=>{e.classList.add('form-collapse-right-show');e.classList.remove('form-collapse-right-hide');});section.closed=false;if(bar.errored){var collapseMid=bar.querySelector(".form-collapse-mid");collapseMid.style.color='';collapseMid.querySelector('img').remove();bar.errored=false;} bar.setAttribute("aria-pressed",true);}else{section.scrollTop=0;section.shift({height:height,duration:0.5,onEnd:function(e){e.className="form-section-closed";},onStep:function(){if(window.parent&&window.parent!=window){window.parent.postMessage('setHeight:'+$$('body')[0].getHeight(),'*');}}});section.style.overflow='hidden';if(!openBar){openBar=section;} if(openBar){openBar.querySelectorAll('.form-collapse-right-show').forEach(e=>{e.classList.add('form-collapse-right-hide');e.classList.remove('form-collapse-right-show');});} section.closed=true;bar.setAttribute("aria-pressed",false);} setTimeout(function(){JotForm.handleIFrameHeight();},510);} bar.addEventListener('click',()=>{handleFormCollapseChecker();});bar.addEventListener('keyup',(e)=>{if(e.keyCode===13){handleFormCollapseChecker();}});})},setPagePositionForError:function(){const firstError=document.querySelectorAll('.form-error-message')[0];if(firstError){if(JotForm.isCollapsed(firstError)){JotForm.getCollapseBar(firstError).dispatchEvent(new Event('click'));} const erroredLine=firstError.closest('.form-line') if(!JotForm.noJump&&erroredLine){erroredLine.scrollIntoView();const firstInput=erroredLine.querySelector('input,select,textarea');if(firstInput&&firstInput.isVisible()){firstInput.focus();}else{const erroredLineLabel=erroredLine.querySelector('.form-label');if(erroredLineLabel){const target=document.getElementById(erroredLineLabel.getAttribute('for'));if(target){target.focus();}}}}}},justNumber:function(ev){var paste="";if(typeof ev.clipboardData!=='undefined'){paste=(ev.clipboardData||window.clipboardData).getData("text");} var reg=/^\d+$/;if(typeof ev.key!=='undefined'&&(!reg.test(ev.key))||(paste!==""&&!reg.test(paste))){ev.preventDefault();}},PCIGatewaysCardInputValidate:function(){[document.querySelector('.cc_ccv'),document.querySelector('.cc_number')].forEach(function(el){el.addEventListener('paste',function(ev){JotForm.justNumber(ev)});el.addEventListener('keypress',function(ev){JotForm.justNumber(ev)});});var thisForm=$$('.jotform-form')[0];var paymentFieldId=$$('input[name="simple_fpc"]')[0].value;Event.observe(thisForm,'submit',function(event){var ccFields=$$('#id_'+paymentFieldId+' input[class*="cc"]','#id_'+paymentFieldId+' select[class*="cc"]');ccFields.each(function(input){JotForm.corrected(input);}) if(JotForm.isEditMode()){return true;} if(JotForm.isPaymentSelected()&&JotForm.paymentTotal>0){var errors;var erroredFields=[];ccFields.each(function(cc){if(!cc.getValue()){errors=JotForm.texts.ccMissingDetails;erroredFields.push(cc);}});if(errors){Event.stop(event);setTimeout(function(){erroredFields.forEach(function(input){JotForm.errored(input,errors);});var cc_number=$$('.cc_number')[0];if(!cc_number.isVisible()&&!cc_number.up('li').hasClassName('form-field-hidden')&&!cc_number.up('ul').hasClassName('form-field-hidden')&&$$('ul.form-section.page-section').length>1) {var visibleButtons=[];$$('.form-submit-button').each(function(btn){if(btn.isVisible()){visibleButtons.push(btn);}});if(visibleButtons.length<1){return;} var lastButton=visibleButtons[visibleButtons.length-1];$$('.form-card-error').invoke('remove');var errorBox=document.createElement('div');errorBox.className='form-button-error form-card-error';errorBox.innerHTML='

'+errors+'

';$(lastButton.parentNode.parentNode).insert(errorBox);} JotForm.enableButtons();},500);}}});},handleAuthNet:function(){this.PCIGatewaysCardInputValidate();},handleBluesnap:function(){this.PCIGatewaysCardInputValidate();if(JotForm.isEditMode()||document.get.sid){return;} else if(!JotForm.paymentProperties){return;} else if(JotForm.paymentProperties.sca!=='Yes'){return;} try{var bluesnapJS=new _bluesnapJS();bluesnapJS.initialization();}catch(err){console.error("ERR::",err);JotForm.errored(document.querySelector('li[data-type="control_bluesnap"]'),err);}},isCardinalValidationInitialized:false,handleSignatureEvents:function(){function handleCanavasMousedDown(wrapperElem){wrapperElem.removeClassName('signature-placeholder');this.removeEventListener('mousedown',handleCanavasMousedDown);this.removeEventListener('pointerdown',handleCanavasMousedDown);} var signatureElems=document.querySelectorAll('.jotform-form .signature-pad-wrapper');if(!signatureElems||signatureElems.length===0){return;} Array.from(signatureElems).forEach(function(signatureElem){var canvasElem=signatureElem.querySelector('canvas');var wrapperElem=signatureElem.querySelector('.signature-line.signature-wrapper');var clearButton=signatureElem.querySelector('.clear-pad-btn.clear-pad');canvasElem.addEventListener('mousedown',handleCanavasMousedDown.bind(this,wrapperElem));canvasElem.addEventListener('touchstart',handleCanavasMousedDown.bind(this,wrapperElem));canvasElem.addEventListener('pointerdown',handleCanavasMousedDown.bind(this,wrapperElem));clearButton.addEventListener('click',function(){wrapperElem.addClassName('signature-placeholder');canvasElem.addEventListener('mousedown',handleCanavasMousedDown.bind(this,wrapperElem));var signImage=wrapperElem.querySelector('img');var pad=wrapperElem.querySelector('.pad');if(signImage){pad.style.display='block';signImage.remove();}});});},htmlEncode:function(str){var htmlEscapes={'&':'&','<':'<','>':'>','"':'"',"'":'''};return String(str).replace(/[&<>"']/g,function(match){return htmlEscapes[match];});},populateSignature:function(qid,value){var signatureWrapper=$('id_'+qid).select('.signature-pad-wrapper');var signatureLine=signatureWrapper.first().select('.signature-line').first();var pad=signatureLine.select('.pad').first();if(value){pad.addClassName('edit-signature').hide();signatureLine.removeClassName('signature-placeholder');signatureLine.select('#input_'+qid).first().setValue(value);var sigimage=(value&&value.indexOf('data:image/png;')>-1)?value:'/'+value+'?nc=1';sigimage=JotForm.htmlEncode(sigimage);signatureLine.insert('');} var clearButton=signatureWrapper[0].select('.clear-pad')[0];clearButton.removeClassName('clear-pad').addClassName('edit-signature-pad').writeAttribute('data-id',qid);},handleSignSignatureInputs:function(){var historyState=history.state;if(historyState&&historyState.signatureValues&&historyState.signatureValues.length>0&&!this.isEditMode()){var signatureValues=historyState.signatureValues;signatureValues.forEach(function(sign){var qid=sign.id.replace('input_','');JotForm.populateSignature(qid,sign.value);}) history.replaceState(Object.assign({},history.state,{signatureValues:[]}),null,null);} if(window.JotForm.isSignForm!=="Yes")return;var signatures=document.querySelectorAll('li[data-type="control_signature"]') if(signatures&&signatures.length>0){Array.from(signatures).forEach(function(inputContainer){var signatureInput=inputContainer.querySelector('input[type="hidden"]');var signatureTrigger=inputContainer;if(signatureInput&&signatureTrigger&&window.JFFormSignature){var labelTitle=inputContainer.querySelector('label').innerText;var onUse=function(output){var pad=inputContainer.querySelector('.pad');if(jQuery(pad).jSignature){var data30="data:image/jsignature;base30,tR_6I";jQuery(pad).jSignature("setData",data30);if(output.value===""){jQuery(pad).jSignature("reset");}} signatureInput.value=output.value;signatureInput.setAttribute('data-mode',output.mode);signatureInput.setAttribute('data-font',output.font);signatureInput.setAttribute('data-color',output.color);signatureInput.setAttribute('data-text',output.text);if(signatureInput.validateInput){signatureInput.validateInput();} signatureInput.triggerEvent('change');if(pad){pad.style.display='flex';pad.style.alignItems='center';var canvas=pad.querySelector('canvas');if(canvas){canvas.style.display='none';} var image=pad.querySelector('img');if(!image){image=new Image();pad.appendChild(image);} image.src=output.value;}};var getInitialValue=function(){var signatureImage=inputContainer.querySelector('#signature-pad-image');var sigValue=signatureInput.value.indexOf("data:image")===-1&&signatureImage?signatureImage.src:signatureInput.value;return{value:sigValue,mode:signatureInput.dataset.mode,font:signatureInput.dataset.font,color:signatureInput.dataset.color,text:signatureInput.dataset.text};} var isDisabled=function(){return signatureInput.hasClassName('conditionallyDisabled');} window.JFFormSignature({trigger:signatureTrigger,onUse:onUse,getInitialValue:getInitialValue,isDisabled:isDisabled,labelTitle:labelTitle,renderMode:'embed',initialMode:'type'});}});}},handleFITBInputs:function(){function getInputWidth(fitbInput){var width=0;var textElement=document.createElement('span');var fitbFontSize=getComputedStyle(fitbInput,null).getPropertyValue('font-size')||'15'+'px';var fitbFontFamily=getComputedStyle(fitbInput,null).getPropertyValue('font-family')||'sans-serif';textElement.innerText=fitbInput.value||fitbInput.parentNode.querySelector('label').innerText;textElement.style.cssText='position: absolute; text-wrap: nowrap; white-space: pre; font-size:'+(fitbFontSize)+'; font-family:'+(fitbFontFamily)+'; display: inline-block;' fitbInput.parentNode.appendChild(textElement);width=textElement.offsetWidth;fitbInput.parentNode.removeChild(textElement);return width;} function getContWidth(fitbInput){return fitbInput.parentNode.parentNode.offsetWidth;} var visibleFitbInputs=Array.from(document.querySelectorAll('.FITB input:not([type="checkbox"]):not([type="radio"])')).filter(function(field){return JotForm.isVisible(field);});if(visibleFitbInputs&&visibleFitbInputs.length>0){Array.from(visibleFitbInputs).forEach(function(fitbInput){var contWidth=getContWidth(fitbInput);var initWidth=getInputWidth(fitbInput)+8;fitbInput.style.width=initWidth+'px';if(contWidth){fitbInput.style.maxWidth=contWidth+'px';} fitbInput.addEventListener('input',function(){if(fitbInput.offsetWidth0){Array.from(fitbSignatures).forEach(function(inputContainer){var signatureImage=inputContainer.querySelector('.FITB-sign-image');var signatureInput=inputContainer.querySelector('input[type="hidden"]');var signatureTrigger=inputContainer.querySelector('.FITB-sign-button');if(signatureImage&&signatureInput&&signatureTrigger&&window.JFFormSignature){var onUse=function(output){signatureInput.value=output.value;signatureImage.setAttribute('src',output.value);signatureInput.setAttribute('data-mode',output.mode);signatureInput.setAttribute('data-font',output.font);signatureInput.setAttribute('data-color',output.color);signatureInput.setAttribute('data-text',output.text);if(signatureInput.validateInput){signatureInput.validateInput();} signatureInput.triggerEvent('change');};var getInitialValue=function(){return{value:signatureInput.value,mode:signatureInput.dataset.mode,font:signatureInput.dataset.font,color:signatureInput.dataset.color,text:signatureInput.dataset.text};} signatureTrigger.addEventListener('keypress',function(e){if(e.keyCode===32||e.keyCode===13){e.preventDefault();e.target.click();}});var isDisabled=function(){return signatureInput.hasClassName('conditionallyDisabled');} window.JFFormSignature({trigger:signatureTrigger,onUse:onUse,getInitialValue:getInitialValue,isDisabled:isDisabled});}});} var timeInputs=document.querySelectorAll('.FITB span[data-type="timebox"] input[id*="timeInput"]');for(var i=0;i0){var errors="";JotForm.corrected($$('.paymentTypeRadios')[0]);if(!$$('.paymentTypeRadios')[0].checked&&!$$('.paymentTypeRadios')[1].checked){errors="You must select a payment method";} if($('input_'+paymentFieldId+'_paymentType_credit').checked){$$('#input_'+paymentFieldId+'_cc_number').each(function(cc){if(!cc.getValue()){errors="All fields are required";throw $break;}});} if(errors){JotForm.errored($$('.paymentTypeRadios')[0],errors);Event.stop(event);}else{JotForm.corrected($$('.paymentTypeRadios')[0]);} var isSubscription=document.getElementById('payment-wrapper-songbird').getAttribute('data-paymenttype')==='subscription';var is3DSecurityEnabled=document.getElementById('payment-wrapper-songbird').getAttribute('data-sca')==='Yes';if(typeof Cardinal!=="undefined"&&is3DSecurityEnabled&&$('input_'+paymentFieldId+'_paymentType_credit').checked&&!isSubscription){Event.stop(event);JotForm.disableButtons();var cardinalAPIkey=document.getElementById('payment-wrapper-songbird').getAttribute('data-cardinalapikey');var cardinalAPIidentifier=document.getElementById('payment-wrapper-songbird').getAttribute('data-cardinalapiindentifier');var cardinalOrgUnitID=document.getElementById('payment-wrapper-songbird').getAttribute('data-cardinalorgunitid');var songBird=new songBirdInit();songBird.init({cardinalAPIkey:cardinalAPIkey,cardinalAPIidentifier:cardinalAPIidentifier,cardinalOrgUnitID:cardinalOrgUnitID});if(!JotForm.isCardinalValidationInitialized){JotForm.isCardinalValidationInitialized=true;Cardinal.on("payments.validated",function(data){var form=(JotForm.forms[0]==undefined||typeof JotForm.forms[0]=="undefined")?$($$('.jotform-form')[0].id):JotForm.forms[0];JotForm.corrected($('creditCardTable'));switch(data.ActionCode){case"SUCCESS":case"NOACTION":var PAResStatus=createHiddenInputElement({name:'PAResStatus',value:data.Payment.ExtendedData.PAResStatus});var Enrolled=createHiddenInputElement({name:'Enrolled',value:data.Payment.ExtendedData.Enrolled});var CAVV=createHiddenInputElement({name:'CAVV',value:data.Payment.ExtendedData.CAVV!==undefined?data.Payment.ExtendedData.CAVV:""});var ECIFlag=createHiddenInputElement({name:'ECIFlag',value:data.Payment.ExtendedData.ECIFlag!==undefined?data.Payment.ExtendedData.ECIFlag:""});var XID=createHiddenInputElement({name:'XID',value:data.Payment.ExtendedData.XID!==undefined?data.Payment.ExtendedData.XID:""});var DSTRANSACTIONID=createHiddenInputElement({name:'DSTRANSACTIONID',value:data.Payment.ExtendedData.DSTransactionId!==undefined?data.Payment.ExtendedData.DSTransactionId:""});var THREEDSVERSION=createHiddenInputElement({name:'THREEDSVERSION',value:data.Payment.ExtendedData.ThreeDSVersion!==undefined?data.Payment.ExtendedData.ThreeDSVersion:""});var docFrag=document.createDocumentFragment();[PAResStatus,Enrolled,CAVV,ECIFlag,XID,DSTRANSACTIONID,THREEDSVERSION].forEach(function(el){docFrag.appendChild(el);});form.appendChild(docFrag);JotForm.ignoreDirectValidation=true;form.submit();break;case"FAILURE":JotForm.errored($('creditCardTable'),"Failed Authentication");JotForm.enableButtons();break;case"ERROR":JotForm.errored($$('.paymentTypeRadios')[0],"Failed to connect payment service please try later");JotForm.enableButtons();break;}});}}}});$$('.paymentTypeRadios').each(function(radio){radio.observe('click',function(){if(radio.checked&&radio.value==="express"){JotForm.setCreditCardVisibility(false);} if(radio.checked&&radio.value==="credit"&&(JotForm.paymentTotal>0||Object.keys(JotForm.discounts).length===0)){JotForm.setCreditCardVisibility(true);} JotForm.corrected($$('.paymentTypeRadios')[0]);JotForm.togglePaypalButtons(radio.checked&&radio.value==="express");});});}},handlePaypalComplete:function(){if(JotForm.isEditMode()||document.get.sid){return;} try{var paypalComplete=new _paypalCompleteJS();JotForm.paypalCompleteJS=paypalComplete paypalComplete.initialization();}catch(err){console.log("ERR::",err);JotForm.errored($$('li[data-type="control_paypalcomplete"]')[0],err);if($$('li[data-type="control_paypalcomplete"]')[0]){$$('li[data-type="control_paypalcomplete"] .form-textbox').each(function(q){q.disabled=true;});}}},handleCybersource:function(){this.PCIGatewaysCardInputValidate() if(window.location.pathname.match(/^\/edit/)||(["edit","inlineEdit","submissionToPDF"].indexOf(document.get.mode)>-1&&document.get.sid)){return;} if(typeof __cybersource!=="function"){alert("PagSeguro payment script didn't work properly. Form will be reloaded");location.reload();return;} JotForm.cybersource=__cybersource();JotForm.cybersource.init();},description:function(input,message){if(message=="20"){return;} var lineDescription=false;if(!$(input)){var id=input.replace(/[^\d]/gim,'');if($("id_"+id)){input=$("id_"+id);lineDescription=true;}else if($('section_'+id)){input=$('section_'+id);lineDescription=true;}else{return;}} if($(input).setSliderValue){input=$($(input).parentNode);} var cont=JotForm.getContainer(input);if(!cont){return;} var right=false;var bubble=document.createElement('div');bubble.className='form-description';var arrow=document.createElement('div');arrow.className='form-description-arrow';var arrowsmall=document.createElement('div');arrowsmall.className='form-description-arrow-small';var content=document.createElement('div');content.className='form-description-content';var indicator;if("desc"in document.get&&document.get.desc=='v2'){right=true;indicator=document.createElement('div');indicator.className='form-description-indicator';cont.appendChild(indicator);bubble.addClassName('right');} content.insert(message);bubble.insert(arrow).insert(arrowsmall).insert(content).hide();cont.insert(bubble);if((cont.getWidth()/2) '}).setStyle({color:'red'});} else{collapse.select(".form-collapse-mid")[0].insert({top:' '}).setStyle({color:'red'});} collapse.errored=true;}} var container=JotForm.getContainer(input);if(!container)return false;input.errored=true;input.addClassName('form-validation-error');container.addClassName('form-line-error');var insertEl=container;insertEl=container.select('.form-input')[0];if(!insertEl){insertEl=container.select('.form-input-wide')[0];} if(!insertEl){insertEl=container;} insertEl.select('.form-error-message').invoke('remove');error_message_span=document.createElement('span');error_message_span.className='error-navigation-message';error_message_span.innerText=message;var formErrorMessageEl=document.createElement('div');formErrorMessageEl.className='form-error-message';formErrorMessageEl.role='alert';var formErrorArrowEl=document.createElement('div');formErrorArrowEl.className='form-error-arrow';var formErrorArrowInnerEl=document.createElement('div');formErrorArrowInnerEl.className='form-error-arrow-inner';formErrorArrowEl.appendChild(formErrorArrowInnerEl);insertEl.insert(formErrorMessageEl.insert(' ').insert(error_message_span).insert(formErrorArrowEl));JotForm.iframeHeightCaller();JotForm.updateErrorNavigation();return false;},corrected:function(input){input=$(input);if(input){input.errored=false;} var container=JotForm.getContainer(input);if(!container){return true;} var inputs=container.select('*[class*="validate"]');inputs.each(function(subInput){subInput.errored=false;});if(JotForm.isPaymentSelected()&&!JotForm.isValidMinTotalOrderAmount()&&container.classList.contains("form-minTotalOrderAmount-error")){return;} if(JotForm.paymentFields.indexOf($(container).readAttribute('data-type'))>-1&&typeof PaymentStock!=='undefined'&&!PaymentStock.validations.checkStock()){return;} if(container.select('.form-error-message').length!==0&&container.select('.form-error-message')[0].id!=='mollie_dummy'){container.select('.form-error-message').invoke('remove');} container.select(".form-validation-error").invoke('removeClassName','form-validation-error');container.removeClassName('form-line-error');if(JotForm.isCollapsed(input)){var collapse=JotForm.getCollapseBar(input);if(collapse.errored&&(collapse.up('.form-section-closed')&&collapse.up('.form-section-closed').select('.form-validation-error').length==0)){collapse.select(".form-collapse-mid")[0].setStyle({color:''}).select('img')[0].remove();collapse.errored=false;}} setTimeout(function(){if($$('.form-validation-error').length==0){JotForm.hideButtonMessage();}},100);JotForm.iframeHeightCaller();JotForm.updateErrorNavigation();return true;},hideButtonMessage:function(){if(window.FORM_MODE=='cardform'){document.querySelectorAll('.form-submit-button').forEach(function(button){const buttonParentNode=button.parentNode.parentNode;const errorBox=buttonParentNode.querySelector('.form-button-error');if(errorBox&&buttonParentNode.classList.contains('jfCard')){const buttonParentNodeRect=buttonParentNode.getBoundingClientRect();const errorBoxRect=errorBox.getBoundingClientRect();const qContainer=buttonParentNode.querySelector('.jfCard-question');if(qContainer){const qContainerRect=qContainer.getBoundingClientRect(qContainer);buttonParentNode.style.maxHeight=buttonParentNodeRect.height+errorBoxRect.height;qContainer.style.maxHeight=qContainerRect.height+errorBoxRect.height;buttonParentNode.parentNode.style.paddingBottom='unset';}}});} const errorElements=document.querySelectorAll('.form-button-error');errorElements.forEach((element)=>{element.parentNode.removeChild(element);});},showButtonMessage:function(txt){this.hideButtonMessage();document.querySelectorAll('.form-submit-button').forEach(function(button){if(JotForm.isSourceTeam){return;} if(button&&button.getAttribute('class').indexOf('form-sacl-button')>-1){return;} const errorBox=document.createElement('div');errorBox.className='form-button-error';errorBox.role='alert';errorBox.innerHTML='

'+(typeof txt!=="undefined"?txt:JotForm.texts.generalError)+'

';const buttonParentNode=button.parentNode.parentNode;buttonParentNode.appendChild(errorBox);if(buttonParentNode.classList.contains('jfCard')){const buttonParentNodeRect=buttonParentNode.getBoundingClientRect();const progressWrapper=document.querySelector('#cardProgress');const progressRect=progressWrapper.getBoundingClientRect();const errorBoxRect=errorBox.getBoundingClientRect();if(errorBoxRect.bottom>progressRect.top&&getComputedStyle(progressWrapper).display!=='none'){const qContainer=buttonParentNode.querySelector('.jfCard-question');if(qContainer){const qContainerRect=qContainer.getBoundingClientRect(qContainer);buttonParentNode.style.maxHeight=buttonParentNodeRect.height-errorBoxRect.height;qContainer.style.maxHeight=qContainerRect.height-errorBoxRect.height;buttonParentNode.parentNode.style.paddingBottom=errorBoxRect.height;}}}});},_errTimeout:null,updateErrorNavigation:function(render){if(typeof window.ErrorNavigation==='undefined'||!(JotForm.newDefaultTheme||JotForm.extendsNewTheme)){return;} var nav=document.querySelector('.error-navigation-container');JotForm.renderErrorNavigation=(typeof render==='undefined'&&!nav)?true:render;if(JotForm._errTimeout){clearTimeout(JotForm._errTimeout);} JotForm._errTimeout=setTimeout(function(){window.ErrorNavigation.update(JotForm.currentSection,JotForm.renderErrorNavigation);clearTimeout(JotForm._errTimeout);},50);},disableGoButton:function(){const isMobile=/iPhone|iPad|Android/i.test(navigator.userAgent);if(isMobile){document.querySelectorAll('input').forEach(function(input){input.addEventListener('keydown',function(e){const code=(e.keyCode?e.keyCode:e.which);if(code===13){e.preventDefault();}});});}},disableSubmitForCard:function(action,isConditionMatch){if(window.FORM_MODE!=='cardform'||!window.CardForm||!window.CardForm.cards)return;JotForm.disableSubmitButton=isConditionMatch;JotForm.disableSubmitButtonMessage=(action&&action.disableSubmitErrorMessage)?action.disableSubmitErrorMessage:'You are not eligible to submit this form.';if(!isConditionMatch){JotForm.toggleDisableSubmitMessage();}},toggleDisableSubmitMessage:function(){var submitButtonCardIndex=window.CardForm.getLastVisibleIndex();if(typeof(submitButtonCardIndex)==="number"&&document.getElementsByClassName('jfCard')){var jfCardElement=document.getElementsByClassName('jfCard')[submitButtonCardIndex];var disableSubmitErrorMessageElement=jfCardElement&&jfCardElement.querySelector('.jfCard-disableSubmitError');if(!jfCardElement||!disableSubmitErrorMessageElement)return;disableSubmitErrorMessageElement.innerHTML='

'+JotForm.disableSubmitButtonMessage+'

';disableSubmitErrorMessageElement.style.display=JotForm.disableSubmitButton?'block':'none';if(JotForm.disableSubmitButton){jfCardElement.classList.add('jfCard-submitErrored');}else{jfCardElement.classList.remove('jfCard-submitErrored');}}},removeNonselectedProducts:function(form){var nonSelectedProducts=[];if(JotForm.newPaymentUI){nonSelectedProducts=form.querySelectorAll('.form-product-item.new_ui:not(.p_selected)');}else{nonSelectedProducts=form.querySelectorAll('.form-product-item').filter(function(item){return item.querySelector('.form-product-input')&&!item.querySelector('.form-product-input').checked;});} if(!(nonSelectedProducts.length>0)){return;} nonSelectedProducts.forEach(function(node){node.parentNode.removeChild(node)});},validator:function(){JotForm.validatorExecuted=true;if(this.debugOptions&&this.debugOptions.stopValidations){this.info('Validations stopped by debug parameter');return true;} var $this=this;if(!$A(JotForm.forms).length){trackExecution('forms-list-empty');} trackExecution('validator-called');$A(JotForm.forms).each(function(form){if(form.validationSet){return;} form.validationSet=true;var handleFormSubmit=function(e){try{trackSubmitSource('form');if($('payment_total_checksum')){$('payment_total_checksum').value=JotForm.paymentTotal;} if($('payment_discount_value')&&JotForm.pricingInformations&&JotForm.pricingInformations.general){$('payment_discount_value').value=JotForm.pricingInformations.general.shippingDiscountVal||JotForm.pricingInformations.general.discount;} if($('firstPaymentDiscount')&&JotForm.pricingInformations&&JotForm.pricingInformations.general&&JotForm.pricingInformations.general.firstPaymentDiscount){$('firstPaymentDiscount').value=JotForm.pricingInformations.general.firstPaymentDiscount;} if($('recurPaymentDiscount')&&JotForm.pricingInformations&&JotForm.pricingInformations.general&&JotForm.pricingInformations.general.recurPaymentDiscount){$('recurPaymentDiscount').value=JotForm.pricingInformations.general.recurPaymentDiscount;} if($$('.form-submit-button')&&$$('.form-submit-button').length>0){var aSubmitIsVisible=false;$$('.form-submit-button').each(function(el){if(JotForm.isVisible(el.parentNode)){aSubmitIsVisible=true;return;}});if(!aSubmitIsVisible){JotForm.enableButtons();e.stop();} var invisibleCaptchaWrapper=$$('[data-invisible-captcha="true"]');var hasInvisibleCaptcha=!!invisibleCaptchaWrapper.length;if(hasInvisibleCaptcha){var recaptchasHiddenInput=invisibleCaptchaWrapper[0].select('[name="recaptcha_invisible"]')[0];var isCaptchaValidated=recaptchasHiddenInput&&recaptchasHiddenInput.getValue();if(!isCaptchaValidated){const isEmbed=window.parent&&window.parent!==window;if(isEmbed){attachScrollToCaptcha(form);} window.grecaptcha.execute().then(()=>{console.log('Captcha initialized') JotForm.enableButtons();}).catch(()=>{console.log('Captcha cannot be initialized') JotForm.enableButtons();}) e.stop();return;}}} if(JotForm.disableSubmitButton){JotForm.toggleDisableSubmitMessage();JotForm.enableButtons();e.stop();return;} if(!JotForm.validateAll(form)){JotForm.enableButtons();JotForm.showButtonMessage();JotForm.updateErrorNavigation(true);if(JotForm.submitError){if(JotForm.submitError=="jumpToSubmit"){var visSubmit=[];$$('.form-submit-button').each(function(but){if(JotForm.isVisible(but)){visSubmit.push(but);}});if(visSubmit.length>0){if(visSubmit[visSubmit.length-1].up('.form-line')){visSubmit[visSubmit.length-1].up('.form-line').scrollIntoView(false);}else{visSubmit[visSubmit.length-1].scrollIntoView(false);}}}else if(JotForm.submitError=="jumpToFirstError"){setTimeout(function(){JotForm.setPagePositionForError();},100);}} $$('.custom-hint-group').each(function(elem){elem.showCustomPlaceHolder();});e.stop();return;} trackExecution('submit-validation-passed');if(JotForm.validatedRequiredFieldIDs!=null&&typeof JotForm.validatedRequiredFieldIDs==='object'){if(Object.keys(JotForm.validatedRequiredFieldIDs).length){JotForm.errorCatcherLog({validatedRequiredFieldIDs:JotForm.validatedRequiredFieldIDs},'VALIDATED_REQUIRED_FIELD_IDS');} form.appendChild(createHiddenInputElement({name:'validatedNewRequiredFieldIDs',value:JSON.stringify((Object.keys(JotForm.validatedRequiredFieldIDs).length&&JotForm.validatedRequiredFieldIDs)||'No validated required fields')}));}else{form.appendChild(createHiddenInputElement({name:'validatedNewRequiredFieldIDs',value:'Invalid Value: '+typeof JotForm.validatedRequiredFieldIDs}));} if(Object.keys(JotForm.visitedPages).length){form.appendChild(createHiddenInputElement({name:'visitedPages',value:JSON.stringify(JotForm.visitedPages)}));} $$('.form-radio-other,.form-checkbox-other').each(function(el){if(!el.checked&&JotForm.getOptionOtherInput(el)){JotForm.getOptionOtherInput(el).disable();}});JotForm.runAllCalculations(true);if($$('input, select, textarea').length>900){$$('.form-matrix-table').each(function(matrixTable){var matrixObject={};var inputs=matrixTable.select("input, select");var isDynamic=matrixTable.dataset.dynamic;inputs.each(function(input){var ids=input.id.split("_");var x=ids[2];var y=ids[3];if(input.type=="radio"&&!isDynamic){if(input.checked){matrixObject[x]=input.value;}else if(!(x in matrixObject)){matrixObject[x]=false;}}else{if(!(x in matrixObject)){matrixObject[x]={};} if(input.type=="checkbox"||input.type=="radio"){matrixObject[x][y]=input.checked?input.value:false;}else{matrixObject[x][y]=input.value;}} input.writeAttribute("disabled","true");});try{var matrixArea=document.createElement('textarea');matrixArea.style.display='none';matrixArea.name=matrixTable.down('input, select').readAttribute("name").split("[")[0];matrixArea.value=JSON.stringify(matrixObject);matrixTable.insert({after:matrixArea});}catch(e){console.log(e);}});} var accessToLocalStorage=JotForm.hasAccessToLocalStorage();var currentForm=document.querySelector('form');var formId=currentForm&¤tForm.id?currentForm.id:'';var formName=currentForm&¤tForm.name?currentForm.name:'';if(JotForm.autoFillDeployed&&!JotForm.payment){var autofillFormInstance=AutoFill&&AutoFill.getInstance(formId+formName);autofillFormInstance&&autofillFormInstance.stopSavingData();accessToLocalStorage&&window.localStorage.clear();}else if(JotForm.isNewSaveAndContinueLaterActive&&accessToLocalStorage){var saclKey="JFU_SCL_details_"+formId;window.localStorage.removeItem(saclKey);}}catch(err){JotForm.error(err);e.stop();var logTitle=e.stopped?'FORM_VALIDATION_ERROR':'FORM_VALIDATION_EVENT_NOT_STOPPED';$this.errorCatcherLog(err,logTitle);return;} $$('.time-dropdown').each(function(el){el.enable();});$$('.form-checkbox, .form-radio').each(function(el){var stoppedGateways=['control_paypalcomplete','control_stripe','control_paypalSPB','control_square'];var gateway=el.up('.form-line')?el.up('.form-line').getAttribute('data-type'):null;var isNewStripe=JotForm.stripe&&typeof JotForm.stripe.validateStripe!=='undefined';if(gateway&&stoppedGateways.indexOf(gateway)>-1){if((gateway==='control_stripe'&&isNewStripe)||gateway==='control_square'){return false;}} if(el.up('.form-product-item')&&el.disabled&&el.checked){el.observe('click',function(e){e.preventDefault();setTimeout(JotForm.countTotal,20);});} el.enable();});$$('.conditionallyDisabled').each(function(el){el.enable();});if(JotForm.clearFieldOnHide!=="dontClear"){$$('.form-field-hidden input','.form-field-hidden select','.form-field-hidden textarea').each(function(input){if(input.name=="simple_fpc"){return;} if(input.tagName=='INPUT'&&['checkbox','radio'].include(input.type)){input.checked=false;}else{input.clear();}});} try{if(typeof PaymentUtils!=='undefined'){const paymentUtils=new PaymentUtils();paymentUtils.attachPaymentSummaryToForm();}}catch(error){console.log('paymentSummary error occured',error);} var numberOfInputs=form.querySelectorAll('.form-all input, select').length;var pciLimit=['bluesnap','cybersource'].includes(JotForm.payment)&&numberOfInputs>1000;if(numberOfInputs>3000||pciLimit){JotForm.removeNonselectedProducts(form);} if(JotForm.compact&&JotForm.imageSaved==false){e.stop();window.parent.saveAsImage();$(document).observe('image:loaded',function(){var block=document.createElement('div');Object.assign(block.style,{position:'fixed',top:'0',left:'0',right:'0',bottom:'0',background:'rgba(0,0,0,0.85)'});block.innerHTML='
Please Wait...
';document.body.appendChild(block);setTimeout(function(){JotForm.ignoreDirectValidation=true;form.submit();},1000);});return;} if(window.FORM_MODE=='cardform'&&Array.prototype.forEach&&CardForm&&CardForm.cards){if(window.toMarkdown){Array.prototype.forEach.call(CardForm.cards,function(card){if(card.markdownEditor&&card.markdownEditor.setMarkdownFromHtml){card.markdownEditor.setMarkdownFromHtml();}});}} var previouslyEncryptedWithV2=JotForm.isEditMode()&&!!JotForm.submissionDecryptionKey;var signatureInputValues=document.querySelectorAll('.signature-line input[type="hidden"]');var signatureValuesArray=Array.from(signatureInputValues).map(function(signInputItem){return{id:signInputItem.id,value:signInputItem.value};});history.pushState({signatureValues:signatureValuesArray},null,null);if(JotForm.isEncrypted||previouslyEncryptedWithV2){var redirectConditions={};$A(JotForm.conditions).each(function(condition){if(!condition.disabled&&condition.type==='url'){redirectConditions[condition.id]=JotForm.checkCondition(condition);}});JotForm.encryptAll(e,function(submitForm){if(submitForm){if(Object.keys(redirectConditions).length>0){appendHiddenInput('redirectConditions',JSON.stringify(redirectConditions));} if(!window.offlineForm){JotForm.ignoreDirectValidation=true;form.submit();}}});} JotForm.sendFormOpenId(form,'clientSubmitFinish_V5');history.replaceState(Object.assign({},history.state,{submitted:true}),null,null);};form.observe('submit',handleFormSubmit);var submitEventMounted=false;var registry=form.retrieve('prototype_event_registry')||{};var submitEventRegistry=registry.get&®istry.get('submit')||[];submitEventRegistry.forEach(function(event){if(event.handler.name==='handleFormSubmit')submitEventMounted=true;});trackExecution('validator-mounted-'+submitEventMounted);trackSubmitSource('mounted');$$('#'+form.id+' *[class*="validate"]').each(function(input){JotForm.setFieldValidation(input);});$$('#'+form.id+' *[class*="form-address-table"] input').each(function(input){var dataComponentName=input.getAttribute('data-component');if(dataComponentName==='address_line_1'||dataComponentName==='address_line_2'){input.setAttribute("maxLength",100);}else if(dataComponentName==='zip'){input.setAttribute("maxLength",20);}else{input.setAttribute("maxLength",60)}});$$('.form-upload').each(function(upload){try{var required=!!upload.validateInput;var exVal=upload.validateInput||Prototype.K;upload.validateInput=function(){upload.errored=false;if(exVal()!==false){if(!upload.files){return true;} var acceptString=upload.readAttribute('accept')||upload.readAttribute('data-file-accept')||upload.readAttribute('file-accept')||"";var maxsizeString=upload.readAttribute('maxsize')||upload.readAttribute('data-file-maxsize')||upload.readAttribute('file-maxsize')||"";var minsizeString=upload.readAttribute('minsize')||upload.readAttribute('data-file-minsize')||upload.readAttribute('file-minsize')||"";var accept=acceptString.strip().toLowerCase().split(/\s*\,\s*/gim);for(var key in accept){if(typeof accept[key]==='string'){accept[key]=accept[key].slice(0,1)==='.'?accept[key].slice(1):accept[key];}} var maxsize=parseInt(maxsizeString,10)*1024;var minsize=parseInt(minsizeString,10)*1024;var file=upload.files[0];if(!file){return true;} if(!file.fileName){file.fileName=file.name;} var ext="";if(JotForm.getFileExtension(file.fileName)){ext=JotForm.getFileExtension(file.fileName);} if(acceptString!="*"&&!accept.include(ext)&&!accept.include(ext.toLowerCase())){return JotForm.errored(upload,JotForm.texts.uploadExtensions+'
'+acceptString);} var validateImage=upload.readAttribute('data-imagevalidate')||false;var validatedImageExt="jpeg, jpg, png, gif, bmp";if((accept.include(ext)||accept.include(ext.toLowerCase()))&&validateImage&&(validateImage==='yes'||validateImage==='true')&&(validatedImageExt.include(ext)||validatedImageExt.include(ext.toLowerCase()))&&typeof window.FileReader!='undefined'){var binary_reader=new FileReader();binary_reader.onloadend=function(e){function ab2str(buf){var binaryString='',bytes=new Uint8Array(buf),length=bytes.length;for(var i=0;imaxsize&&maxsize!==0){return JotForm.errored(upload,JotForm.texts.uploadFilesize+' '+maxsizeString+'Kb');} if(file.fileSize-1||field.indexOf("+")>-1){offset=field.split(/[\+\-]/)[1];offset=field.indexOf("-")>-1?"-"+offset:""+offset;field=field.split(/[\+\-]/)[0];} field=field.replace(/[{}]/g,'');if(!$('year_'+field)||!$('year_'+field).value)return false;var year=$('year_'+field).value;;var month=$('month_'+field).value;var day=$('day_'+field).value;var date=new Date(year,month-1,day);if(offset.length){date.setDate(date.getDate()+parseInt(offset,10));} return date;},getInputValidations:function(input){if(input){return input.className.replace(/.*validate\[(.*)\].*/,'$1').split(/\s*,\s*/);} return[];},removeValidations:function(input,pattern){var validationPattern=new RegExp('(validate\\[(.*)?'+pattern+'(.*)?\\])');if(validationPattern.test(input.className)){var matches=validationPattern.exec(input.className);var validationClass=matches[0].replace(new RegExp(pattern+'(\\,\\s*)?','g'),'').replace(/\,\s(?!\w+)/g,'');input.className=input.className.replace(validationPattern,validationClass).replace(' validate[]','');return input;} return input;},getValidMessage:function(message,value){var validMessage=message.replace(/\s*$/,"");var notation=/{value}/ig;if(notation.test(message)){return validMessage.replace(notation,value)+".";} return validMessage+" "+value+".";},getProductSelectionStatuses:function(input){try{var cont=JotForm.getContainer(input);var newValidation=input.getAttribute('data-inputname')!==null;var inputName=newValidation?input.getAttribute('data-inputname'):input.name;if(inputName===''){var findInput=$$('.form-product-input').find(function(item){return item.name!==''});inputName=newValidation?findInput.getAttribute('data-inputname'):findInput.name;} var selector=newValidation?'[data-inputname="'+inputName+'"]':'[name="'+inputName+'"]';return $A(document.querySelectorAll(selector)).map(function(e){var _isVisible=JotForm.isVisible(e);if(JotForm.doubleValidationFlag()){_isVisible=!(JotForm.isInputAlwaysHidden(e));} if(_isVisible){if(e.name===''){var productID=e.value;var isConnectedProductChecked=false;if(JotForm.categoryConnectedProducts!==undefined&&JotForm.categoryConnectedProducts[productID]!==undefined){Array.from(JotForm.categoryConnectedProducts[productID]).forEach(function(pid){var productCheckbox=$$('.form-product-input[value="'+pid+'"]')[0]?$$('.form-product-input[value="'+pid+'"]')[0]:null;if(productCheckbox&&productCheckbox.checked){isConnectedProductChecked=true;}});} return isConnectedProductChecked;} if((e.readAttribute('type')==="checkbox"||e.readAttribute('type')==="radio")&&e.value.indexOf('_expanded')>-1){if(!e.checked){return false;}else{return $A($$('#'+e.id+'_subproducts .form-subproduct-quantity')).map(function(cb){return cb.getSelected().value>0||cb.value>0;}).any();}}else if($(e.id+'_custom_price')){return e.checked&&$(e.id+'_custom_price').getValue()>0;}else{var qty=e.up('.form-product-item')?e.up('.form-product-item').down('select[id*="quantity"], input[id*="quantity"]'):false;if(qty){return e.checked&&qty.getValue()>0;} return e.checked;}}else{if(JotForm.productPages&&JotForm.productPages.totalPage>1&&cont.select('.product--selected').length>0){JotForm.corrected(e);return true;}}})}catch(e){console.log('getProductSelectionStatuses :: ',e);return false;}},setFieldValidation:function(input){var $this=this;var reg=JotForm.validationRegexes;var validationWhiteList=[];if(JotForm.payment==='square'&&(input.classList.contains('cc_firstName')||input.classList.contains('cc_lastName'))&&window.FORM_MODE!=='cardform'){return;} input.validateInput=function(deep,dontShowMessage){if(document.get.ignoreValidation&&document.get.ignoreValidation==="true"){return true;} if(JotForm.doubleValidationFlag()){var alwaysHidden=JotForm.isInputAlwaysHidden(input);if(alwaysHidden&&!input.hasClassName('h-captcha-response')){return true;} if(alwaysHidden&&!input.hasClassName('g-recaptcha-response')){return true;}}else{if(!JotForm.isVisible(input)&&!input.hasClassName('h-captcha-response')){return true;} if(!JotForm.isVisible(input)&&!input.hasClassName('g-recaptcha-response')){return true;}} var container=JotForm.getContainer(input);if(container.getAttribute('data-type')==="control_appointment"){var inputID=input.getAttribute('id');if(!inputID||inputID.indexOf('_date')===-1){return true;} if((input.hasClassName('validate')&&!input.hasClassName('valid'))){JotForm.errored(input,JotForm.texts.required);return false;} JotForm.corrected(input);return true;} if(JotForm.getContainer(input).getAttribute('data-type')==="control_inline"&&!deep){var validatedFitbInputs=JotForm.getContainer(input).querySelectorAll('input[class*="validate"],select[class*="validate"]');if(Array.from(validatedFitbInputs).map(function(subInput){return subInput.validateInput?subInput.validateInput(true):input.validateInput(true);}).every(function(e){return e;})){return JotForm.corrected(input);} return false;} if(JotForm.getContainer(input).getAttribute('data-type')==="control_datetime"&&!JotForm.getContainer(input).down('input[id*="month_"]').dateTimeCheck(false)){return false;} var timeFieldContainer=container.getAttribute('data-type')==="control_time";var hourSelect=container.down('select[id*="hourSelect"]');var inputHourSelect=container.down('input[id*="hourSelect"]');var isHourSelectElement=timeFieldContainer&&(hourSelect||inputHourSelect);var timeCheck=timeFieldContainer&&((hourSelect&&!hourSelect.timeCheck())||(inputHourSelect&&!inputHourSelect.timeCheck()));if(timeFieldContainer&&isHourSelectElement&&timeCheck){return false;} if(!$(input.parentNode).hasClassName('form-matrix-values')&&!input.hasClassName('form-subproduct-option')&&!input.hasClassName('time-dropdown')&&!(input.id.match(/_quantity_/)||input.id.match(/_custom_/))&&!(JotForm.getContainer(input).getAttribute('data-type')==="control_inline")) {JotForm.corrected(input);} var vals=JotForm.getInputValidations(input);if(input.hinted===true){input.clearHint();setTimeout(function(){input.hintClear();},150);} if(typeof input.overridenValidateInput==='function'){return input.overridenValidateInput(input,deep,dontShowMessage);} if(input.readAttribute('data-type')==='input-spinner'&&input.value){return input.validateSpinnerInputs();} else if(input.readAttribute('data-type')==='input-grading'&&input.value){return input.validateGradingInputs();} else if(input.readAttribute('data-type')==='input-number'&&input.value){return input.validateNumberInputs();} else if(input.readAttribute('data-min-amount')){return input.validateMinimum();} if(input.limitValidation&&input.classList.contains('mdInput')){var errorText=input.limitValidation();if(errorText!==false){return JotForm.errored(input,errorText);}} if(input.up('.form-line')&&input.up('.form-line').down('.form-textarea-limit-indicator-error')){input.triggerEvent('change');return;} if(vals.include('minCharLimit')){var valid=input.validateTextboxMinsize();if(!valid)return valid;} if(vals.include('disallowFree')){for(var i=0;i-1){return JotForm.errored(input,JotForm.texts.freeEmailError,dontShowMessage);}}} if(vals.include('minSelection')||vals.include('minselection')){var minSelection=parseInt(input.readAttribute('data-minselection'));var numberChecked=0;input.up('.form-line').select('input[type=checkbox]').each(function(check){if(check.checked)numberChecked++;});if(numberChecked>0&&numberCheckedmaxSelection){return JotForm.errored(input,JotForm.getValidMessage(JotForm.texts.maxSelectionsError,maxSelection),dontShowMessage);}} if(vals.include('disallowPast')&&validationWhiteList.indexOf('disallowPast')===-1){var id=container.id.split('_').last();var inputtedDate=JotForm.getDateValue(id).split('T')[0];var dat=new Date();var month=(dat.getMonth()+1<10)?'0'+(dat.getMonth()+1):dat.getMonth()+1;var day=(dat.getDate()<10)?'0'+dat.getDate():dat.getDate();var currentDate=dat.getFullYear()+"-"+month+"-"+day;if(JotForm.checkValueByOperator('before',JotForm.strToDate(currentDate),JotForm.strToDate(inputtedDate))){return JotForm.errored(input,JotForm.texts.pastDatesDisallowed,dontShowMessage);}} if(JotForm.getContainer(input).getAttribute('data-type')==="control_datetime"&&input.readAttribute('data-age')&&input.value){var minAge=input.readAttribute('data-age');var today=new Date();var birthDate=new Date(input.value);var formLine=input.up('.form-line');var liteModeInput=formLine?formLine.down('input[id*="lite_mode_"]'):null;if(liteModeInput){var dateParts=liteModeInput.value.split(liteModeInput.readAttribute('data-seperator'));if(liteModeInput.readAttribute('data-format')==='ddmmyyyy'){birthDate=new Date(dateParts[2],parseInt(dateParts[1],10)-1,dateParts[0]);}else if(liteModeInput.readAttribute('data-format')==='mmddyyyy'){birthDate=new Date(dateParts[2],parseInt(dateParts[0],10)-1,dateParts[1]);}else if(liteModeInput.readAttribute('data-format')==='yyyymmdd'){birthDate=new Date(dateParts[0],parseInt(dateParts[1],10)-1,dateParts[2]);}}else{var parentContainer=input.up('.notLiteMode');if(!parentContainer){return false;} var yearElement=parentContainer.down('input[id*="year_"]');var year=yearElement?yearElement.value:'';var monthElement=parentContainer.down('input[id*="month_"]');var month=monthElement?monthElement.value:'';var dayElement=parentContainer.down('input[id*="day_"]');var day=dayElement?dayElement.value:'';if(year&&month&&day){birthDate=new Date(year,parseInt(month,10)-1,day);}} var age=today.getFullYear()-birthDate.getFullYear();var m=today.getMonth()-birthDate.getMonth();if(m<0||(m===0&&today.getDate()-1){var custom=JotForm.dateFromField(lim.custom[j]);custom=JotForm.addZeros(custom.getFullYear(),2)+"-"+JotForm.addZeros(custom.getMonth()+1,2)+"-"+JotForm.addZeros(custom.getDate(),2);if(custom===year+"-"+month+"-"+day)return invalidLimits();return;} if((lim.custom[j]===year+"-"+month+"-"+day)||(typeof lim.custom[j]=="string"&&lim.custom[j].length===5&&lim.custom[j]===(month+"-"+day))||(typeof lim.custom[j]=="string"&&lim.custom[j].length===2&&lim.custom[j]==day)){return invalidLimits();}}} var date=new Date($("year_"+id).value,($("month_"+id).value-1),$("day_"+id).value);if("ranges"in lim&&lim.ranges!==false&&Array.isArray(lim.ranges)){for(var j=0;j")===-1)continue;var range=lim.ranges[j].split(">");var startDate;if(range[0].indexOf("{")>-1){startDate=JotForm.dateFromField(range[0]);}else{JotForm.browserIs.safari()&&!JotForm.browserIs.chrome()?startDate=new Date(range[0]+'T00:00'):startDate=new Date(range[0].split('-'));} var endDate;if(range[1].indexOf("{")>-1){endDate=JotForm.dateFromField(range[1]);}else{JotForm.browserIs.safari()&&!JotForm.browserIs.chrome()?endDate=new Date(range[1]+'T00:00'):endDate=new Date(range[1].split('-'));} if(endDate){if(date.getTime()>=startDate.getTime()&&date.getTime()<=endDate.getTime()){return invalidLimits();}}}} var dayOfWeek=JotForm.getDayOfWeek(date);if("days"in lim,dayOfWeek in lim.days&&lim.days[dayOfWeek]==false){return invalidLimits();} if("future"in lim&&lim.future===false){var now=new Date();if(date>now){return invalidLimits();}} if("past"in lim&&lim.past===false){var now=new Date();var yesterday=new Date();yesterday.setDate(now.getDate()-1);if(date-1){var startDate=JotForm.dateFromField(lim.start);if(dateendDate){return invalidLimits();}}else if(lim.end.indexOf('{')>-1){var endDate=JotForm.dateFromField(lim.end);if(date>endDate){return invalidLimits();}}}}}catch(e){console.log(e);}} if(vals.include('validateLiteDate')){if(input.hasClassName("invalidDate")){var format=input.readAttribute("placeholder") return JotForm.errored(input,JotForm.texts.dateInvalid.replace("{format}",format),dontShowMessage);}} if(vals.include("Email_Confirm")){var idEmail=input.id.replace(/.*_(\d+)(?:_confirm)?/gim,'$1');if(($('input_'+idEmail).value!=$('input_'+idEmail+'_confirm').value)){return JotForm.errored(input,JotForm.texts.confirmEmail,dontShowMessage);}else if(($('input_'+idEmail+'_confirm').value)&&(!reg.email.test($('input_'+idEmail+'_confirm').value))){return JotForm.errored(input,JotForm.texts.email,dontShowMessage);}} if(vals.include("required")){if(JotForm.minTotalOrderAmount!=='0'&&!JotForm.isValidMinTotalOrderAmount()){input.addClassName('form-minTotalOrderAmount-error');}else{input.removeClassName('form-minTotalOrderAmount-error');} if(JotForm.getContainer(input).getAttribute('data-type')=='control_signature'){var pad=input if(jQuery(pad).attr("data-required")==="true"){var formLine=jQuery('#id_'+jQuery(pad).attr('data-id'));var _isVisible=formLine.is(':visible');if(JotForm.doubleValidationFlag()){_isVisible=!(JotForm.isInputAlwaysHidden(pad));} if(_isVisible){var canvasData=jQuery(pad).jSignature('getData','base30');if(!(canvasData&&canvasData[1].length)&&!jQuery(pad).hasClass('edit-signature')){return JotForm.errored(input,JotForm.texts.required,dontShowMessage);}else{return JotForm.corrected(input);}}}} if(input.tagName=='INPUT'&&input.readAttribute('type')=="file"){var formInput=input.up('.form-input')||input.up('.form-input-wide');var isMultiple=input.readAttribute('multiple')==='multiple'||input.hasAttribute('multiple');if(!isMultiple){if(input.value.empty()&&!(input.uploadMarked||(formInput&&formInput.uploadMarked))){return JotForm.errored(input,JotForm.texts.required,dontShowMessage);}else{return JotForm.corrected(input);}}else{if(JotForm.isFillingOffline()){if(input.value.empty()){return JotForm.errored(input,JotForm.texts.required,dontShowMessage);}else{return JotForm.corrected(input);}} return input.up('div[class*=validate[multipleUpload]]').validateInput();}}else if(input.tagName=="INPUT"&&!$(input.parentNode).hasClassName('form-matrix-values')&&(input.readAttribute('type')=="radio"||input.readAttribute('type')=="checkbox")&&JotForm.getContainer(input).getAttribute('data-type')!=='control_inline'){var otherInput=input.up(".form-"+input.type+"-item")?input.up(".form-"+input.type+"-item").down(".form-"+input.type+"-other-input"):null;if(otherInput){if(input.checked&&otherInput.value==""){return JotForm.errored(input,JotForm.texts.required);}} var baseInputName=input.name.substr(0,input.name.indexOf('['));var otherInputName=baseInputName+'[other]';var checkboxArray=[];if(document.getElementsByName(otherInputName)[0]){checkboxArray=$A(document.getElementsByName(baseInputName+'[]'));checkboxArray[checkboxArray.length]=document.getElementsByName(otherInputName)[0];if(!checkboxArray.map(function(e){return e.checked;}).any()){return JotForm.errored(input,JotForm.texts.required,dontShowMessage);}}else{var cont=JotForm.getContainer(input);if(JotForm.payment&&cont.getAttribute('data-type').match(JotForm.payment)){if(!JotForm.getProductSelectionStatuses(input).any()||(window.FORM_MODE==='cardform'&&cont.select('.product--selected').length===0)) {if(input.hasClassName('paymentTypeRadios')){return JotForm.errored(input,"Please select payment method.",dontShowMessage);} return JotForm.errored(input,JotForm.texts.required,dontShowMessage);}else{$A(cont.querySelectorAll('select[id*="quantity"], input[id*="quantity"]')).forEach(function(q){if(q.getValue()>0)JotForm.corrected(q);})}}else{if(cont.select("input:checked").length===0){return JotForm.errored(input,JotForm.texts.required,dontShowMessage);}}}}else if((input.tagName=="INPUT"||input.tagName=="SELECT")&&($(input).up().hasClassName('form-matrix-values')||$(input).up(1).hasClassName('form-matrix-values'))){function isInputTypeRadioOrCheckbox(inp){return['radio','checkbox'].indexOf(inp.type)!==-1;} function isFilled(el){return isInputTypeRadioOrCheckbox(el)?el.checked:(!!el.value&&!el.value.strip(" ").empty());} var matrixElement=input.up('table')?input.up('table'):input.up('.jfMatrix');var allCells=Array.from(matrixElement.querySelectorAll('input,select'));function getElementsInRow(row){return Array.from(row.querySelectorAll('input,select'));} function anyRowElementsFilled(rowElements){return rowElements.map(isFilled).any();} function allRowElementsFilled(rowElements){var singleChoiceFilled=rowElements.every(function(e){return e.type!=='radio'})||rowElements.filter(function isRadio(e){return e.type==='radio';}).map(isFilled).any(function(e){return e;});var othersFilled=rowElements.filter(function notRadio(e){return e.type!=='radio';}).map(isFilled).every(function(e){return e;});return singleChoiceFilled&&othersFilled;} var rows=window.FORM_MODE==='cardform'?matrixElement.querySelectorAll('.jfMatrixTable-row,.jfMatrixScale,.jfMatrixInputList-item,.jfMatrixChoice-table'):matrixElement.rows;var hasOneAnswerEveryRows=Array.from(rows).map(getElementsInRow).filter(function notEmpty(el){return el.length;}).map(anyRowElementsFilled).every(function(el){return el;});var hasAnswerEveryCell=Array.from(rows).map(getElementsInRow).filter(function notEmpty(el){return el.length;}).map(allRowElementsFilled).every(function(el){return el;});if(vals.include("requireEveryRow")&&!hasOneAnswerEveryRows){return JotForm.errored(input,JotForm.texts.requireEveryRow,dontShowMessage);}else if(vals.include("requireOneAnswer")&&!allCells.map(isFilled).any()){return JotForm.errored(input,JotForm.texts.requireOne,dontShowMessage);}else if(vals.include('requireEveryCell')&&!hasAnswerEveryCell){return JotForm.errored(input,JotForm.texts.requireEveryCell,dontShowMessage);}else{return JotForm.corrected(input);}}else if((input.tagName==="INPUT"||input.tagName==="SELECT")&&input.hasClassName('form-subproduct-option')){if(input.hasClassName('form-subproduct-quantity')){var qID=input.id.replace(/_[0-9]*_[0-9]*$/,'');if($(qID.replace(/_quantity/,'')).checked){if($A($$('[id*="'+qID+'"]')).map(function(vl){return(vl.getSelected().value>0||vl.value>0);}).any()){return JotForm.corrected(input);}else{return JotForm.errored(input,JotForm.texts.required,dontShowMessage);}}}}else if(input.name&&input.name.include("[")||$this.getContainer(input).getAttribute('data-type')==='control_inline'){try{var isDisabledMatrix=$(input).getAttribute('data-component')==='matrix'&&($(input).up().hasClassName('form-matrix-values-disabled')||$(input).up(1).hasClassName('form-matrix-values-disabled')) if(isDisabledMatrix){return true;} var cont=$this.getContainer(input);if((input.hasClassName('form-address-search')&&cont.select('.jfQuestion-clean').length>0)||input.hasClassName('js-forMixed')){inputs=[input];}else{inputs=Array.from(cont.querySelectorAll('input,select[name*="'+input.name.replace(/\[.*$/,"")+'"]'));} var checkValues=inputs.map(function(e){if(e.id.match(/_donation/)){return e.getValue()==0;} if(window.FORM_MODE!=='cardform'){if(e.name&&e.name.match(/cc_/)){return JotForm.paymentTotal==0;}} if(e.id.match(/input_[0-9]+_quantity_[0-9]+_[0-9]+/)){var cb=$(((e.id.replace('_quantity','')).match(/input_[0-9]+_[0-9]+/))[0]);var allProducts=$$('[id*="'+e.id.match(/input_[0-9]*/)[0]+'"][type="'+cb.getAttribute('type')+'"]');if(e.id.split("_").length===6){var subProductQty=$$('[id*="'+e.id.replace(/_[0-9]*_[0-9]*$/,"")+'"]');} if((cb.checked&&!subProductQty&&(isNaN(e.value)||e.value==0||e.value.empty()))||(!allProducts.map(function(c){return c.checked}).any())||(cb.checked&&subProductQty&&!subProductQty.map(function(q){return q.value>0}).any())){e.addClassName('form-validation-error');return true;}} var innerVals=e.className.replace(/.*validate\[(.*)\].*/,'$1').split(/\s*,\s*/);var _isVisible=JotForm.isVisible(e);if(JotForm.doubleValidationFlag()){_isVisible=!(JotForm.isInputAlwaysHidden(e));} if(innerVals.include('required')&&_isVisible){if(JotForm.getContainer(e).getAttribute('data-type')==='control_inline'&&['radio','checkbox'].indexOf(e.readAttribute('type'))>-1){var baseName=e.name;var inputType=e.readAttribute('type');if(inputType==='checkbox'){var fieldId=e.name.replace(/(^.*\[|\].*$)/g,'').split('-')[0];var TIMESTAMP_OF_2019=1546300000000;var isNewIDType=isNaN(fieldId)||Number(fieldId)=1){if(count>emptyOption){return false;}else{return true;}}} if(!dontShowMessage){e.addClassName('form-validation-error');} return true;}else{if(JotForm.getContainer(e).hasClassName("form-datetime-validation-error")){return JotForm.errored(input,'Enter a valid date',dontShowMessage);}}} if(!e.hasClassName('js-forMixed')){e.removeClassName('form-validation-error');} return false;});if(JotForm.payment&&JotForm.isEditMode()&&(cont.getAttribute('data-type').match(JotForm.payment)||(JotForm.payment==='paypalcomplete'&&cont.getAttribute('data-type')==='control_paymentmethods'))){return JotForm.corrected(input);} if(JotForm.paymentTotal===0&&JotForm.payment==='paypalcomplete'&&cont.getAttribute('data-type')==='control_paymentmethods'){var selectedProducts=[];var fullDiscountedProducts=[];var discountTypes=['100.00-percent','100-percent'];var productSelectClass=window.FORM_MODE==='cardform'?'product--selected':'p_selected';if(JotForm.couponApplied&&JotForm.discounts&&Object.keys(JotForm.discounts).length>0){Object.values(document.getElementsByClassName(productSelectClass)).forEach(function(value){if(typeof value==='object'&&value&&value.getAttribute('pid')){selectedProducts.push(value.getAttribute('pid'));}});if(selectedProducts&&selectedProducts.length>0){Object.values(selectedProducts).forEach(function(el){if(JotForm.discounts[el]&&discountTypes.includes(JotForm.discounts[el])){fullDiscountedProducts.push(el);}});if(fullDiscountedProducts.length===selectedProducts.length){fullDiscountedProducts.sort();selectedProducts.sort();var totalFullDiscount=true;for(let i=0;i-1){var seperator=input.readAttribute('seperator')||input.readAttribute('data-seperator');var format=(input.readAttribute('format')||input.readAttribute('data-format')).toLowerCase();if(input.value.length!==((seperator.length*2)+format.length)){return JotForm.errored(input,JotForm.texts.dateInvalid.replace("{format}",format),dontShowMessage);}} if(JotForm.getContainer(input).hasClassName("form-datetime-validation-error")){return JotForm.errored(input,'Enter a valid date',dontShowMessage);}}else if((!input.value||input.value.strip(" ").empty()||input.value.replace('
','').empty()||input.value=='Please Select'||(typeof textAreaEditorInput==='string'&&textAreaEditorInput.empty()))&&!(input.readAttribute('type')=="radio"||input.readAttribute('type')=="checkbox")&&!$(input.parentNode).hasClassName('form-matrix-values')&&JotForm.getContainer(input).getAttribute('data-type')!=="control_address"){if(window.FORM_MODE!="cardform"&&input.hasClassName("form-dropdown")&&input.hasAttribute("multiple")){var count=0,emptyOption=0;for(var i=1;i=1){if(count>emptyOption){return JotForm.corrected(input);}else{return JotForm.errored(input,JotForm.texts.required,dontShowMessage);}}} if(input.hasClassName('form-dropdown')&&$$('.jfDropdown-search:focus').length>0){return JotForm.corrected(input);} if(input.querySelector('[data-testid="mollie-container--cardHolder"]')&&JotForm.mollie.cardFormMollieValidate()){return JotForm.corrected(input)} if(input.getAttribute('name')==='cc_paypalSPB_orderID'||input.getAttribute('name')==='cc_paypalSPB_payerID'){return JotForm.corrected(input);} if(JotForm.newDefaultTheme&&input.hasClassName('form-star-rating-star')){input.up().descendants().each(function(e){e.setStyle({backgroundPosition:'-128px 0px'});});} return JotForm.errored(input,JotForm.texts.required,dontShowMessage);} vals=vals.without("required");}else if(!input.value){return true;} if(!vals[0]){return true;} switch(vals[0]){case"Email":input.value=input.value.replace(/^\s+|\s+$/g,'');var value=(typeof punycode!=="undefined")?punycode.toASCII(input.value):input.value;if(!reg.email.test(value)){return JotForm.errored(input,JotForm.texts.email,dontShowMessage);} break;case"Alphabetic":if(!reg.alphabetic.test(input.value)){return JotForm.errored(input,JotForm.texts.alphabetic,dontShowMessage);} break;case"Numeric":if(!reg.numeric.test(input.value)&&!reg.numericDotStart.test(input.value)){return JotForm.errored(input,JotForm.texts.numeric,dontShowMessage);} break;case"Alphanumeric":case"AlphaNumeric":if(!reg.alphanumeric.test(input.value)){return JotForm.errored(input,JotForm.texts.alphanumeric,dontShowMessage);} break;case"Cyrillic":if(!reg.cyrillic.test(input.value)){return JotForm.errored(input,JotForm.texts.cyrillic,dontShowMessage);} break;case"Url":case"URL":try{var checkUrlValue=input.value;if(input.value.startsWith('www.')){checkUrlValue='https://'+input.value;} new URL(checkUrlValue);}catch(error){return JotForm.errored(input,JotForm.texts.url,dontShowMessage);} break;case"Currency":if(input.up(".form-matrix-table")){if(input.up(".form-matrix-table").select("input").collect(function(inp){return!reg.currency.test(inp.value)}).any()){return JotForm.errored(input,JotForm.texts.currency,dontShowMessage);} else{return JotForm.corrected(input);}}else{if(!reg.currency.test(input.value)){return JotForm.errored(input,JotForm.texts.currency,dontShowMessage);}} break;case"Fill Mask":if(input.dataset.masked=="true"&&!(input&&input.inputmask&&input.inputmask.isComplete())){return JotForm.errored(input,JotForm.texts.fillMask,dontShowMessage);} break;default:} if(JotForm.getContainer(input).getAttribute('data-type')==="control_inline"&&!deep){return JotForm.corrected(input);} return true;};var validatorEvent=function(){setTimeout(function(){try{var inputContainer=$this.getContainer(input);var requiredFields=inputContainer.select('[class*=validate]');var lastRequiredField=requiredFields[requiredFields.length-1];var isLastRequiredField=($this.lastFocus?($this.getContainer($this.lastFocus)==$this.getContainer(input)&&lastRequiredField==input):false);var isPrefix=input&&input.getAttribute('data-component')==='prefix';if($this.lastFocus&&(($this.lastFocus==input||$this.getContainer($this.lastFocus)!=$this.getContainer(input))||isLastRequiredField)&&(!isPrefix)&&(!(window.FORM_MODE==='cardform'&&inputContainer.dataset.type==='control_fullname'))&&(!(window.FORM_MODE==='cardform'&&inputContainer.dataset.type==='control_yesno'))&&(!(window.FORM_MODE==='cardform'&&(inputContainer.dataset.type==='control_checkbox'||inputContainer.dataset.type==='control_radio')))){input.validateInput();var isInputErrored=input.hasClassName('form-validation-error');var isEmailConfirmInput=input.id&&input.id.indexOf("confirm")>-1;var emailConfirmationInput=inputContainer.select('#'+input.id+'_confirm');if(input.type=="email"&&!isInputErrored&&!isEmailConfirmInput&&emailConfirmationInput.length>0){emailConfirmationInput[0].validateInput();}}else if(input.type=="hidden"||input.type=='file'){input.validateInput();} else if(input.hasClassName("form-textarea")&&input.up('div').down('.nicEdit-main')){input.validateInput();}else if(input.hasClassName("pad")){input.validateInput();}}catch(e){console.log(e);}},10);};if(input.type==='email'){var emailCharLimit=Number(input.getAttribute('maxlength'));if(emailCharLimit){input.observe('keydown',function(e){var numOfCharacter=e.target.value.length;if(numOfCharacter===emailCharLimit&&e.key!='Backspace'){JotForm.errored(input,JotForm.getValidMessage(JotForm.texts.characterLimitError,emailCharLimit));}else if(input.hasClassName('form-validation-error')){JotForm.corrected(input);}}) input.observe('paste',function(e){var pastedText=(e.clipboardData||window.clipboardData).getData('text');if(pastedText.length+e.target.value.length>=emailCharLimit){JotForm.errored(input,JotForm.getValidMessage(JotForm.texts.characterLimitError,emailCharLimit));}else if(input.hasClassName('form-validation-error')){JotForm.corrected(input);}})}} if(input.type=='hidden'||input.type=='file'){input.observe('change',validatorEvent);}else if(!input.classList.contains('form-'+input.type+'-other')&&!(input.tagName==='SELECT'&&JotForm.browserIs.ios()&&input.classList.contains('form-address-state'))){input.observe('blur',validatorEvent);} if(input.type=='checkbox'||input.type=='radio'){if(input.parentNode.hasClassName('jfCheckbox')||input.parentNode.hasClassName('jfRadio')){input.observe('change',function(){input.validateInput();});} var vals=JotForm.getInputValidations(input);if(!vals.include('requireEveryRow')&&!vals.include('requireEveryCell')&&!input.classList.contains('form-'+input.type+'-other')){input.observe('change',function(){input.validateInput();});} if(!input.classList.contains('form-'+input.type+'-other')){input.observe('keyup',function(e){if(e.key!=='Tab'&&e.key!=='Shift'){input.validateInput();}})} var otherInput=JotForm.getOptionOtherInput(input);if(otherInput){otherInput.observe('blur',function(){input.validateInput();});otherInput.observe('keyup',function(e){if(e.key!=='Tab'&&e.key!=='ArrowDown'){input.validateInput();}});input.observe('change',function(e){if(!e.target.checked){input.validateInput()}})}} if(input.hasClassName("pad")){jQuery(input).on('change',validatorEvent);} if(input.hasClassName("form-textarea")&&input.up('div').down('.nicEdit-main')){input.up('div').down('.nicEdit-main').observe('blur',validatorEvent);} if(input.classList.contains('form-spinner-input')){var spinnerElement=$(input).up('.form-spinner');var spinnerEvent=function(){input.validateInput();};spinnerElement.down('.form-spinner-up').observe('click',spinnerEvent);spinnerElement.down('.form-spinner-down').observe('click',spinnerEvent);} if(JotForm.isEditMode()&&JotForm.getContainer(input).getAttribute('data-type')==="control_datetime"){validationWhiteList.push('disallowPast','limitDate');input.observe('change',function(){if(JotForm.isVisible(input)){validationWhiteList=validationWhiteList.filter(function(item){return['disallowPast','limitDate'].indexOf(item)===-1;});input.validateInput();}});}},isFillingOffline:function(){var offlineFormQS=getQuerystring('offline_forms');return!!(offlineFormQS==='true'||JotForm.switchedToOffline);},FBInit:function(){JotForm.FBNoSubmit=true;FB.getLoginStatus(function(response){if(response.authResponse){JotForm.FBCollectInformation(response.authResponse.userID);}else{FB.Event.subscribe('auth.login',function(response){JotForm.FBCollectInformation(response.authResponse.userID);});}});},FBCollectInformation:function(id){JotForm.FBNoSubmit=false;var fls=$$('.form-helper').collect(function(el){var f="";var d=el.readAttribute('data-info').replace("user_","");switch(d){case"can_be_anyvalue":f="place correct one here";break;case"sex":f="gender";break;case"about_me":f="bio";break;default:f=d;} return[f,el.id];});var fields={};var getPhoto=false;$A(fls).each(function(p){if(p[0]=="pic_with_logo"){getPhoto={fieldID:p[1]};} if(p[0]!=="username"){fields[p[0]]=p[1];}});var params=$H(fields).keys().without("pic_with_logo");var callback=function(input){JotForm.bringOldFBSubmissionBack(id);JotForm.getForm(input).insert({top:createHiddenInputElement({name:'fb_user_id',id:'fb_user_id',value:id})});};try{FB.api('/'+id,{fields:params},function(res){var input;$H(res).each(function(pair){if($(fields[pair.key])){input=$(fields[pair.key]);switch(pair.key){case"location":input.value=pair.value.name;break;case"website":input.value=pair.value.split(/\s+/).join(", ");break;default:input.value=pair.value;}}});if(getPhoto){FB.api('/'+id+'/picture',function(res){if(res.data.url&&$(getPhoto.fieldID)){$(getPhoto.fieldID).value=res.data.url;} callback(input,id);});}else{callback(input,id);}});}catch(e){console.error(e);} $$('.fb-login-buttons').invoke('show');$$('.fb-login-label').invoke('hide');},bringOldFBSubmissionBack:function(id){var formIDField=$$('input[name="formID"]')[0];if(formIDField&&formIDField.value){new Ajax.Jsonp(JotForm.url+'server/bring-old-fbsubmission-back',{parameters:{formID:formIDField.value,fbid:id},evalJSON:'force',onComplete:function(t){var res=t.responseJSON;if(res.success){JotForm.editMode(res,true,['control_helper','control_fileupload']);}}});}},setCustomHint:function(elem,value){var element=document.getElementById(elem)||document.querySelector(elem)||null,new_value=value.replace(/
/gim,"\n")||"";element.classList.add('custom-hint-group');element.setAttribute('data-customhint',value);element.setAttribute('customhinted',"true");element.hasContent=(element.value&&element.value.replace(/\n/gim,"
")!=value)?true:false;element.showCustomPlaceHolder=function(){if(!this.hasContent){this.placeholder=new_value;this.setAttribute("spellcheck","false");this.classList.add('form-custom-hint');}};element.hideCustomPlaceHolder=function(){if(!this.hasContent){this.placeholder="";this.classList.remove('form-custom-hint');this.removeAttribute('spellcheck');}};element.addEventListener('focus',function(){if(!this.hasContent){this.classList.remove('form-custom-hint');this.removeAttribute('spellcheck');}});element.addEventListener('blur',function(){this.showCustomPlaceHolder();});element.addEventListener('keyup',function(){this.hasContent=(this.value.length>0&&this.value!==new_value)?true:false;if(this.hasContent&&this.classList.contains('form-custom-hint')){this.classList.remove('form-custom-hint');this.removeAttribute('spellcheck');}});element.addEventListener('paste',function(){var self=this;setTimeout(function(){self.hasContent=(self.value.length>0&&self.value!==new_value)?true:false;},2);});if(element&&element.type==="textarea"&&element.hasAttribute('data-richtext')){setTimeout(function(){var editor=document.querySelector('#id_'+element.id.replace('input_','')+' .nicEdit-main')||null;var editorInstance=nicEditors.findEditor(element.id);if(editor){if(!editorInstance.getContent()){editor.style.color='#babbc0';if(JotForm.newDefaultTheme){editorInstance.setContent(new_value);}} editor.addEventListener('blur',function(){if(!editorInstance.getContent()||editorInstance.getContent()==="
"){editor.style.color='#babbc0';editorInstance.setContent(new_value);element.setAttribute("spellcheck","false");element.classList.add('form-custom-hint');}});editor.addEventListener('focus',function(){editor.style.color='';element.classList.remove('form-custom-hint');element.removeAttribute('spellcheck');if(editorInstance.getContent()===new_value){editorInstance.setContent('');};});}},1000);} var form=element.closest('form.jotform-form');if(form) {form.addEventListener('submit',function(){this.querySelectorAll('.custom-hint-group').forEach(function(elem){if(elem.type==='textarea'&&elem.hasAttribute('data-richtext')){var editorInstance=nicEditors.findEditor(elem.id);if(elem.classList.contains('form-custom-hint')){editorInstance.setContent('');}} elem.hideCustomPlaceHolder();});});} element.showCustomPlaceHolder();},fieldHasContent:function(id){const field=document.querySelector(`#id_${id}`);if(field.classList.contains('form-line-error'))return false;if(field.querySelectorAll('.form-custom-hint').length>0)return false;const type=JotForm.getInputType(id);const inputElement=document.querySelector(`#input_${id}`);const inputElements=document.querySelectorAll('#id_'+id+' input');switch(type){case"address":case"combined":return Array.from(inputElements).map(function(e){return e.value;}).some();case"number":return Array.from(inputElements).map(function(e){return e.value.length>0;}).some();case"birthdate":return JotForm.getBirthDate(id);case"datetime":const date=JotForm.getDateValue(id);return!(date=="T00:00"||date=='');case"appointment":return document.querySelector(`#input_${id}_date`)&&document.querySelector(`#input_${id}_date`).value;case"time":return JotForm.get24HourTime(id);case"checkbox":case"radio":return Array.from(inputElements).map(function(e){return e.checked;}).some();case"select":return Array.from(document.querySelectorAll('#id_'+id+' select')).map(function(e){return e.value;}).some();case"grading":return Array.from(document.querySelectorAll(`input[id^=input_${id}_]`)).map(function(e){return e.value;}).some();case"signature":return jQuery("#id_"+id).find(".pad").jSignature('getData','base30')[1].length>0;case"slider":return inputElement.value>0;case"file":if(inputElement.readAttribute('multiple')==='multiple'||inputElement.readAttribute('multiple')===''){const fileList=field.querySelectorAll('.qq-upload-list li');if(fileList.length>0){let status=true;fileList.forEach(function(elem){if(elem.getAttribute('class')&&elem.getAttribute('class').indexOf('fail')>0){status=false;}});return status;} return true;}else{return inputElement.value;} default:if(inputElement&&inputElement.value){return inputElement.value;}else{return false;}}},setupProgressBar:function(){JotForm.progressBar=new ProgressBar("progressBar",{'height':'20px','width':'95%'});var countFields=['select','radio','checkbox','file','combined','email','address','combined','datetime','time','birthdate','number','radio','number','radio','autocomplete','radio','text','textarea','signature','div','slider'];var totalFields=0;var completedFields=0;var updateProgress=function(){completedFields=0;$$('.form-line').each(function(el){var id=el.id.split("_")[1];var type=JotForm.getInputType(id);if($A(countFields).include(type)){if(JotForm.fieldHasContent(id)){completedFields++;}}});var percentage=parseInt(100/totalFields*completedFields);if(isNaN(percentage))percentage=0;JotForm.progressBar.setPercent(percentage);$('progressPercentage').update(percentage+'% ');$('progressCompleted').update(completedFields);if(percentage==100){$('progressSubmissionReminder').show();}else{$('progressSubmissionReminder').hide();}};var setListener=function(el,ev){$(el).observe(ev,function(){updateProgress();});};$$('.form-line').each(function(el){var id=el.id.split("_")[1];var type=JotForm.getInputType(id);if(!countFields.include(type)){return;} totalFields++;switch(type){case'radio':case'checkbox':setListener($('id_'+id),'click');break;case'select':case'file':setListener($('id_'+id),'change');break;case'datetime':setListener($('id_'+id),'date:changed');$$("#id_"+id+' select').each(function(el){setListener($(el),'change');});break;case'time':case'birthdate':$$("#id_"+id+' select').each(function(el){setListener($(el),'change');});break;case'address':setListener($('id_'+id),'keyup');break;case'number':setListener($('id_'+id),'keyup');setListener($('id_'+id),'click');break;case'signature':setListener($('id_'+id),'click');break;default:setListener($('id_'+id),'keyup');break;}});$('progressTotal').update(totalFields);updateProgress();},setupRichArea:function(qid){if(!(!Prototype.Browser.IE9&&!Prototype.Browser.IE10&&Prototype.Browser.IE)){var field='id_'+qid;var isFieldHidden=$(field).hasClassName('always-hidden')||$(field).style.display==='none'||$(field).style.display==='hidden';if(!JotForm.isVisible(field)){$(field).up('.form-section')&&$(field).up('.form-section').show();JotForm.showField(qid);} new nicEditor({iconsPath:location.protocol+'//www.jotform.com/images/nicEditorIcons.gif?v2'}).panelInstance('input_'+qid);JotForm.updateAreaFromRich(field);if(isFieldHidden){this.hideField(qid);}}},updateAreaFromRich:function(field){try{const fieldElement=document.querySelector('#'+field);var rich=fieldElement.querySelector('.nicEdit-main');var txtarea=fieldElement.querySelector('textarea');if(rich&&txtarea){rich.addEventListener('keyup',function(){txtarea.value=rich.innerHTML;if(txtarea.triggerEvent)txtarea.triggerEvent('keyup');});}}catch(e){console.error(e);}},validateSessionID:function(session){if(!session)return false;var isValidSession=false;var sessionIDList=['StripeCheckout-','Payfast-','Square-','Sensepass-','JF-S4L'];for(var i=0;i"):false;if(field.hasAttribute('data-customhint')||field.hasAttribute('customhinted')){var hint=field.readAttribute('data-customhint');if(hint&&value&&hint!=value){field.removeClassName('form-custom-hint');field.hasContent=true;}} else if(field.hasAttribute('hinted')||field.hinted) {var hint=(fieldata.oldinputvalue)?fieldata.oldinputvalue.replace(/\n/gim,"
"):false;if(hint&&value&&hint!=value){field.setStyle({color:"#000"});}} inc++;});},_handleRichText:function(){$$('.nicEdit-main').each(function(richArea){var txtarea=richArea.up('.form-line').down('textarea');if(txtarea){richArea.innerHTML=txtarea.value;}});},_handleStarRating:function(){$$(".form-star-rating").each(function(rating){if(rating.setRating==='function')rating.setRating(rating.down("input").value);});},_handlePaymentTotal:function(){if($('payment_total')){JotForm.totalCounter(JotForm.prices);}}};if(JotForm.payment&&$$('.form-product-item > input.form-product-has-subproducts').length>0){$$('.form-line[data-type="control_authnet"] select, .form-line[data-type="control_authnet"] input').each(function(input){if(input.id){excludeFields.push(input.id);}});} var timeout=Number(params.timeout)>0?params.timeout:4;var fieldAmount=$$('input, select, textarea').length;if(fieldAmount>200){timeout=Math.floor(fieldAmount/10);} var autoFillParams={timeout:timeout,sessionID:JotForm.sessionID,excludeFields:excludeFields,ttl:params.ttl,allowBindOnChange:(params.bindChange&¶ms.bindChange=='on')?true:false,onBeforeSave:function(){},onSave:function(){},onRelease:function(){},onBeforeRestore:function(){},onRestore:function(){var restoredDatas=this.restoredData[0];if(restoredDatas){_conflicts._handleCustomHint(restoredDatas);_conflicts._handleRichText(restoredDatas);_conflicts._handleStarRating(restoredDatas);_conflicts._handlePaymentTotal(restoredDatas);}}};if(window.autoFill){autoFill([form],autoFillParams);} else{jQuery(_form).autoFill(autoFillParams);} this.runAllConditions();this.autoFillDeployed=true;},runReplaceTag:function(calc,combinedObject,output,result,resultFieldType){try{if(!calc.replaceText)calc.replaceText="";if(calc.replaceText.indexOf(":")>-1){var subfield=calc.replaceText.substr(calc.replaceText.indexOf(":")+1);if(calc.equation.indexOf('|')>-1){var splitResult=calc.operands.split('|');var qid=splitResult[0];subfield=qid+'_'+subfield.split('-')[0];} if(subfield in combinedObject){output=combinedObject[subfield];}} if(output.empty()&&calc.defaultValue){output=calc.defaultValue;} var className=result+"_"+calc.replaceText.replace(/\[/g,"_field_").replace(/\:/g,"_");;className=className.replace(']','');var spans=Array.from(document.getElementsByClassName(className));var subLabel=[];if(window.FORM_MODE=='cardform'){subLabel=$$('.'+'jfField-sublabel').filter(function(el){return el.htmlFor=='input_'+result;});} else{subLabel=$$('.'+'form-sub-label').filter(function(el){return el.htmlFor=='input_'+result;});} var replaceRegex=calc.replaceText.replace('[','\\[');var re=new RegExp("\{"+replaceRegex+"\}","g");var def=calc.defaultValue||"";var links=$$('a[href="{'+replaceRegex+'}"]');var replaceLinks=$$('a[replace-link="'+className+'"]');var linkRegex=new RegExp(/([--:\w?@%&+~#=]*\.[a-z]{2,4}\/{0,2})((?:[?&](?:\w+)=(?:\w+))+|[--:\w?@%&+~#=\s]+)?/);var matchLink=output.match(linkRegex);links.each(function(link){link.setAttribute('replace-link',className);link.setAttribute('href','');if(matchLink){var url=matchLink[0].indexOf('//')===-1?'//'+matchLink[0]:matchLink[0];link.setAttribute('href',url);}});replaceLinks.each(function(link){if(matchLink){var url=matchLink[0].indexOf('//')===-1?'//'+matchLink[0]:matchLink[0] link.setAttribute('href',url);}}) if(spans.length==0){if(resultFieldType==='inline'){var fitbFormFields=$$('#FITB_'+result+' .fitb-replace-tag');var fieldRegex=new RegExp("([^<>]*)\{"+replaceRegex+"\}([^<>]*)","g");fitbFormFields.forEach(function(el){if(el.innerHTML){el.innerHTML=el.innerHTML.replace(fieldRegex,'$1'+output+'$2');}});}else{var contents=calc.isLabel?$('label_'+result).innerHTML:$('text_'+result).innerHTML;if(calc.isLabel){contents=contents.replace(re,''+output+'');}else{var localRe=new RegExp("(>[^<>]*)\{"+replaceRegex+"\}([^<>]*<)","g");while(contents.match(localRe)&&output.indexOf('{'+replaceRegex+'}')===-1){contents=contents.replace(localRe,'$1'+output+'$2');}} calc.isLabel?$('label_'+result).update(contents):$('text_'+result).update(contents);}}else{spans.each(function(span){if(output!=null){if(window.DomPurify){span.update(window.DomPurify.sanitize(output,{ADD_ATTR:['target']}));}else{span.update(output.stripScripts().stripEvents());}}});} subLabel.each(function(subl){var content=subl.innerHTML.replace(re,''+output+'');subl.update(content);});var description=$('id_'+result+'_description');if(description){var descriptionContent=description.innerHTML;if(descriptionContent.indexOf(calc.replaceText)>-1){descriptionContent=descriptionContent.replace(re,''+output+'');description.update(descriptionContent);}}}catch(e){console.log(e);}},runAllConditions:function(){const firstPerformancePoint=performance.now();Object.entries(JotForm.fieldConditions).forEach(function(pair){const[field,value]=pair;let event=value.event;const fieldElement=document.querySelector(`#${field}`) if(!fieldElement){return;} if(["autofill","number","autocomplete"].includes(event))event="keyup";fieldElement.dispatchEvent(new Event(event));});if(typeof __conditionDebugger_logPerformance==='function'){__conditionDebugger_logPerformance([{title:'Run All Conditions',value:(performance.now()-firstPerformancePoint).toFixed(2)}]);}},hasQuestion:function(questions,questionType){var field=false;if(questions.length>0){questions.some(function(question){if(question){if(question.type===questionType){return field=question;}}});} return field;},handleSSOPrefill:function(){if(this.isEditMode()||getQuerystring('jf_createPrefill')=='1'){return;} if(JotForm.SSOPrefillData){JotForm.SSOPrefillData.each(function(question){if(question&&question.value){var qid=question.qid;var value=question.value;switch(question.type){case"control_fullname":var names=question.value;Object.keys(names).forEach(function(input){if($(input+"_"+qid)){$(input+"_"+qid).value=names[input];}});break;case"control_phone":var full=$("input_"+qid+"_full");if(full){full.value=value;}else{var fields=$A($$('input[id^=input_'+qid+'_]'));var fieldL=fields.length-1;var parts=value.replace(/\D+/g,' ').trim().split(' ');if(parts.length===1){var pattern=/(\d{3})(\d{3})(\d{4})/;var replacement='$1 $2 $3';var phone=parts[0];if(phone.length>10){pattern=new RegExp('(\\d{'+(phone.length-10)+'})(\\d{3})(\\d{3})(\\d{4})');replacement='$1 $2 $3 $4';} parts=phone.replace(pattern,replacement).split(' ');} var remaining=parts.slice(fieldL).join(' ');var phoneNumberParts=parts.slice(0,fieldL);phoneNumberParts.push(remaining);phoneNumberParts=phoneNumberParts.filter(function(item){return item!=='';});if(phoneNumberParts.length0){questions.each(function(question){if(question){switch(question.type){case'control_chargify':var email=$this.hasQuestion(questions,'control_email');if(email!==false){var emails=$$('input[type="email"]');emails[0].observe('blur',function(e){if(e.target.value){$$('.cc_email')[0].value=e.target.value;};});} break;case'control_stripe':var stripeFormID=$$('input[name="formID"]')[0].value;if(typeof JotForm.tempStripeCEForms!=='undefined'&&JotForm.tempStripeCEForms.includes(stripeFormID)){break;} var email=$this.hasQuestion(questions,'control_email');if(email!==false){var emails=$$('input[type="email"]');if(emails.length<=0){break;} emails[0].observe('blur',function(e){if(e.target.value){if(JotForm.stripe&&typeof JotForm.stripe!=='undefined'){JotForm.stripe.updateElementEmail(e.target.value);}};});} break;case'control_mollie':var isEmailFieldExist=$this.hasQuestion(questions,'control_email');var isAddressFieldExist=$this.hasQuestion(questions,'control_address');var mollieField=$$('.form-line[data-type="control_mollie"]')[0];if(isEmailFieldExist!==false){var emailFields=$$('input[type="email"]');var latestEmailValues={};emailFields[0].observe('blur',function(e){if(!mollieField){mollieField=$$('.form-line[data-type="control_mollie"]')[0];} if(!mollieField){return;} if(typeof e.target.value==='string'){var mollieEmailFields=mollieField.select('.cc_email');if(mollieEmailFields.length>0){mollieEmailFields.each(function(item){if(latestEmailValues[e.target.id]===item.value||item.value.length===0){item.value=e.target.value;}});} latestEmailValues[e.target.id]=e.target.value;};});} if(isAddressFieldExist!==false){var addressFields=$$('.form-line[data-type="control_address"]');var inputs=$(addressFields[0]).select('input, select');var latestAddressValues={};inputs.each(function(inp){var eventName=inp.nodeName==='INPUT'?'blur':'change';inp.observe(eventName,function(e){if(typeof e.target.value!=='string'){return;} var component=e.target.getAttribute('data-component');var mollieComponent='';if(component==='address_line_1'){mollieComponent='addr_line1';}else if(component==='address_line_2'){mollieComponent='addr_line2';}else if(component==='zip'){mollieComponent='postal';}else{mollieComponent=component;} if(mollieComponent){if(!mollieField){mollieField=$$('.form-line[data-type="control_mollie"]')[0];} if(!mollieField){return;} var addrFields=mollieField.select('[data-component="'+mollieComponent+'"]');if(addrFields.length>0){addrFields.each(function(item){if(latestAddressValues[e.target.id]===item.value||item.value.length===0){item.value=e.target.value;}});}} latestAddressValues[e.target.id]=e.target.value;});});} break;default:}}});}},setQuestionMasking:function(toSelector,type,maskValue,unmask){if(!maskValue&&(maskValue===null||typeof maskValue==='undefined')&&(!unmask||typeof unmask==='undefined'))return;maskValue=maskValue.replace(/'/g,"'");var unmask=(unmask)?unmask:false;maskValue=maskValue.replace(/\\/g,'');maskValue=maskValue.replace(/9/g,'\\9').replace(/a/g,'\\a').replace(/A/g,'\\A');var definitions={"#":{validator:"[0-9]"}} if(type==="textMasking"){Object.extend(definitions,{"@":{validator:"[A-Za-z\u0410-\u044F\u0401\u0451\u4E00-\u9FFF]",},"*":{validator:"[0-9A-Za-z\u0410-\u044F\u0401\u0451\u4E00-\u9FFF]"}});} try{if(window.buildermode&&buildermode==='card'){return;} if(toSelector.hasOwnProperty('indexOf')&&toSelector.indexOf('|')>-1){toSelector=toSelector.split('|')[0]+' [id*='+toSelector.split('|')[1]+']';if(toSelector.indexOf('#input_')>-1){toSelector=toSelector.replace('input_','id_');}} var maskedInput=document.querySelector(toSelector);if(!maskedInput){return;} if(unmask){Inputmask.remove(maskedInput);maskedInput.removeAttribute('maskValue');maskedInput.placeholder='';return;} setTimeout(()=>{Inputmask.remove(maskedInput);Inputmask({placeholder:'_',autoclear:false,definitions,mask:maskValue,inputEventOnly:true,postValidation:function(characters,t,a,isValid){if(characters.length){var caretPos=characters.indexOf('_');if(isValid){return{caret:(isValid||(isValid&&isValid.c))&&isValid.pos+1}} if(!isValid&&t>0){return{caret:caretPos}}}}}).mask(maskedInput);maskedInput.setAttribute('maskValue',maskValue);maskedInput.addEventListener('input',e=>e.target.dispatchEvent(new Event('change')));},0);}catch(error){console.log(error);}},setInputTextMasking:function(elem,maskValue,unmask){setTimeout(function(){JotForm.setQuestionMasking("#"+elem,'textMasking',maskValue,unmask);},10);},setPhoneMaskingValidator:function(elem,maskValue,unmask){setTimeout(function(){JotForm.setQuestionMasking("#"+elem,'phoneMasking',maskValue,unmask);},10);},loadScript:function(){var toLoad=arguments.length;var callback;var hasCallback=arguments[toLoad-1]instanceof Function;var script;if(hasCallback){toLoad--;callback=arguments[arguments.length-1];}else{callback=function(){};} for(var i=0;i0){return;} const _form=document.querySelector('.jotform-form');const _formID=_form.getAttribute('id');let _referer;let _location;try{_referer=encodeURIComponent(document.referrer);}catch(e){_referer='undefined'} try{const queryParameters=new URLSearchParams(window.location.search);const parentURL=queryParameters.get('parentURL');_location=parentURL||encodeURIComponent(window.top.location.href);}catch(e){_location='undefined'} const _screenHeight=window.screen.height;const _screenWidth=window.screen.width;if(!_formID){return false;} if(_form){if(location&&location.href&&location.href.indexOf('&nofs')==-1&&location.href.indexOf('&sid')==-1){insertAfter(createImageEl(uuid),_form);}} function insertAfter(newNode,referenceNode){referenceNode.parentNode.insertBefore(newNode,referenceNode.nextSibling);} function createImageEl(uuid){let base='https://events.jotform.com/';if(typeof JotForm.enterprise!=="undefined"&&JotForm.enterprise){base='https://'+JotForm.enterprise+'/events/';} if(self.jsForm){base=base+'jsform/';}else{base=base+'form/';} let src=base+_formID+'/';let resolutionStr;if(_screenHeight&&_screenWidth){resolutionStr=_screenWidth+'x'+_screenHeight;} src=src+'?ref='+encodeURIComponent(_referer);if(resolutionStr){src=src+'&res='+encodeURIComponent(resolutionStr);} if(uuid){src=src+'&eventID='+encodeURIComponent(uuid);} src=src+'&loc='+encodeURIComponent(_location);const viewBrandingFooter=JotForm&&JotForm.showJotFormPowered&&JotForm.showJotFormPowered==='new_footer';if(viewBrandingFooter){src+='&seenBrandingFooter=1';} const img=new Image();img.id="event_tracking_image";img.ariaHidden="true";img.src=src;img.alt="jftr";img.style.display='none';img.width=1;img.height=1;return img;}},additionalActionsFormEmbedded:function(){var self=this;var integration=getQuerystring('embeddedvia');if(integration){if(integration==='weebly'&&!(window.FORM_MODE&&window.FORM_MODE=='cardform')){if(!self.isStyleSheetLoaded('mobile.responsive.min.css')){var styleSheetUrl='https://widgets.jotform.io/mobileResponsive/mobile.responsive.min.css';self.loadStyleSheet(styleSheetUrl,function(){self.handleIFrameHeight();});}}}},changeSubmitURL:function(submitURL){if(submitURL.length>0){for(var i=this.forms.length-1;i>=0;i--){var form=this.forms[i];form.action=form.action.replace(/\/\/submit\..*?\//,'//'+submitURL+'/');};}},handlePreview:function(filled){$$('body')[0].setStyle({overflowX:'hidden'});$A(JotForm.forms).each(function(form){var previewInput=document.createElement('input');previewInput.setAttribute('type','hidden');previewInput.setAttribute('name','preview');previewInput.value='true';form.appendChild(previewInput);if(filled===true){var script=document.createElement('script');script.setAttribute('type','text/javascript');script.setAttribute('src','//cdn.jotfor.ms/js/form-tester.js?rev='+new Date().getTime());form.appendChild(script);}});},getClientCountry:function(callback){new Ajax.Request('//china.jotfor.ms/opt/geo.ip.php',{evalJSON:'force',onComplete:function(res){if(res.status===200){callback(res.responseJSON);}else{callback({country:''});}}});},updateMatrixInputs:function(id,target){const matrix=document.getElementById("matrix_"+id);const desktopWrapper=matrix.querySelector('.forDesktop');const mobileWrapper=matrix.querySelector('.forMobile');if(target==='mobile'){var hiddenMatrix=mobileWrapper;var visibleMatrix=desktopWrapper;}else{var hiddenMatrix=desktopWrapper;var visibleMatrix=mobileWrapper} const hiddenWrappers=hiddenMatrix.querySelectorAll('.form-matrix-values');hiddenWrappers.forEach(function(i){i.classList.remove('form-matrix-values');i.classList.add('form-matrix-values-disabled');});const hiddenInputs=hiddenMatrix.querySelectorAll('input, select');hiddenInputs.forEach(function(i){const idAttr=i.id;if(idAttr.indexOf('disabled')<0){i.id+='_disabled';i.setAttribute('data-name',i.getAttribute('name'));i.removeAttribute('name');}});const mobileInputs=mobileWrapper.querySelectorAll('input, select, label');mobileInputs.forEach(function(i){const idAttr=i.id;if(idAttr&&idAttr.indexOf('cancelled')!==-1){i.id=i.id.replace('_cancelled','');} const forAttr=i.getAttribute('for');if(forAttr&&forAttr.indexOf('cancelled')!==-1){i.setAttribute('for',forAttr.replace('_cancelled',''));}});const visibleWrapper=visibleMatrix.querySelectorAll('.form-matrix-values-disabled');visibleWrapper.forEach(function(i){i.classList.remove('form-matrix-values-disabled');i.classList.add('form-matrix-values');});const visibleInputs=visibleMatrix.querySelectorAll('input');visibleInputs.forEach(function(i){i.id=i.id.replace('_disabled','');if(i.getAttribute('data-name')){i.setAttribute('name',i.getAttribute('data-name'));i.removeAttribute('data-name');}});hiddenMatrix.classList.add('hidden-matrix');visibleMatrix.classList.remove('hidden-matrix');},setMatrixLayout:function(id,passive,mobileActiveQuestionOrder){if(!passive&&!JotForm.isVisible('id_'+id)){return;} var matrix=document.getElementById("matrix_"+id);if(!$(matrix))return;var desktopVersion=$(matrix).select('.forDesktop')[0];var mobileVersion=$(matrix).select('.forMobile')[0];var dataType=matrix.getAttribute('data-type');if(!passive){if((desktopVersion&&desktopVersion.getStyle('display')!=='none')&&mobileVersion){this.updateMatrixInputs(id,'mobile');}else if((mobileVersion&&mobileVersion.getStyle('display')!=='none')&&desktopVersion){this.updateMatrixInputs(id,'desktop');}} if(['Slider','Emoji Slider','Yes No'].indexOf(dataType)>-1){if(desktopVersion){var matrixLabelListItems=desktopVersion.getElementsByClassName('jfMatrixLabelList-item');var matrixInputListItems=desktopVersion.getElementsByClassName('jfMatrixInputList-item');if(Array.prototype.forEach){Array.prototype.forEach.call(matrixLabelListItems,function(matrixLabel,index){var matrixInput=matrixInputListItems[index];if(matrixInput&&matrixLabel){if(dataType==='Yes No'){matrixLabel.style.width='calc(100% - '+matrixInput.offsetWidth+'px)';matrixInput.style.width='';} matrixInput.style.height=matrixLabel.offsetHeight+'px';}});}}} var hasMobile=$(matrix).select('.forMobile').length>0;var isSlider=['Slider','Emoji Slider'].indexOf(dataType)>-1;if(isSlider&&hasMobile){var mobileSlider=$(matrix).select('.slider')[0];var mobileNext=$(matrix).select('.jfMobileMatrix-nextRow')[0];var mobilePrev=$(matrix).select('.jfMobileMatrix-prevRow')[0];var rowList=$(matrix).select('.jfMobileMatrix-row');var bulletList=$(matrix).select('.jfMobileMatrix-columnDot');var rowLength=rowList.length;var currentRow=$(matrix).select('.jfMobileMatrix-row.isSelected')[0];var currIndex=parseInt(currentRow.readAttribute('data-order'),10);var newIndex=false;var newEl=false;if(bulletList[currIndex]){bulletList[currIndex].addClassName('isActive');} var mobileItems=mobileSlider.querySelectorAll('.jfMatrixInputList-item');var setActiveSlider=function(){mobileItems[newIndex].removeClassName('isHidden');mobileItems[currIndex].addClassName('isHidden');bulletList[currIndex].removeClassName('isActive');bulletList[newIndex].addClassName('isActive');currentRow=newEl;currIndex=newIndex;};var handleMobileNextClick=function(){newIndex=currIndex+1;if(newIndex!==rowLength){newEl=rowList[newIndex];newEl.addClassName('isSelected');currentRow.removeClassName('isSelected');if(newIndex>0){mobilePrev.disabled=false;} if(newIndex+1===rowLength){mobileNext.disabled=true;} setActiveSlider();}};var handleMobilePrevClick=function(){if(currIndex!==0){newIndex=currIndex-1;newEl=rowList[newIndex];newEl.addClassName('isSelected');currentRow.removeClassName('isSelected');if(newIndex===0){mobilePrev.disabled=true;} if(newIndex>=rowLength){mobileNext.disabled=true;} if(newIndex0){var headerItems=matrix.getElementsByClassName('jfMatrixHeader-item');var tableCells=matrix.getElementsByClassName('jfMatrixTable-cell');for(var i=1;i0){$(matrix).select('.forMatrixPrev')[0].disabled=!isBackEnabled;$(matrix).select('.forMatrixPrev')[0].setAttribute('aria-hidden',!isBackEnabled);} if($(matrix).select('.forMatrixNext').length>0){$(matrix).select('.forMatrixNext')[0].disabled=!isNextEnabled;$(matrix).select('.forMatrixNext')[0].setAttribute('aria-hidden',!isNextEnabled);} $(matrix).select('.jfMatrixProgress-text span')[0].innerHTML=activeQuestionOrder+1;} if(mobileActiveQuestionOrder){setActiveQuestion(mobileActiveQuestionOrder);} var handleNextButtonClick=function(){$(this).stopObserving('click');$(matrix).select('.jfMatrix-question');var activeQuestionOrder=parseInt($(matrix).select('.jfMatrix-question.isActive')[0].readAttribute('data-order'));activeQuestionOrder=parseInt(activeQuestionOrder,10)+1;setActiveQuestion(activeQuestionOrder);$(this).observe('click',handleNextButtonClick);};var handlePrevButtonClick=function(){$(this).stopObserving('click');$(matrix).select('.jfMatrix-question');var activeQuestionOrder=parseInt($(matrix).select('.jfMatrix-question.isActive')[0].readAttribute('data-order'));activeQuestionOrder=parseInt(activeQuestionOrder,10)-1;setActiveQuestion(activeQuestionOrder);$(this).observe('click',handlePrevButtonClick);};$(matrix).select('.forMatrixNext').length>0&&$(matrix).select('.forMatrixNext')[0].observe("click",handleNextButtonClick);$(matrix).select('.forMatrixPrev').length>0&&$(matrix).select('.forMatrixPrev')[0].observe("click",handlePrevButtonClick);var findAncestor=function(el,cls){while((el=el.parentElement)&&!el.classList.contains(cls));return el;} if(!passive&&!mobileVersion.hasClassName('hidden-matrix')){$(matrix).select('input').each(function(input){if(input.type=='radio'&&dataType!=='Yes No'){var showNextQuestion=function(){$(this).stopObserving('click');if(mobileVersion.hasClassName('hidden-matrix')){return;} var activeTable=findAncestor(this,'jfMatrixChoice-table');if($(activeTable)&&$(activeTable).select('.jfMatrixChoice-row.isSelected')&&$(activeTable).select('.jfMatrixChoice-row.isSelected').length>0){var selectedRow=$(activeTable).select('.jfMatrixChoice-row.isSelected')[0];selectedRow.removeClassName('isSelected');} var activeRow=findAncestor(this,'jfMatrixChoice-row');if(activeRow){activeRow.addClassName('isSelected');} setTimeout(function(){var nextButton=$(matrix).select('.jfMatrixProgress-button.forMatrixNext')[0];if($(nextButton)&&$(nextButton).readAttribute('disabled')==null){$(nextButton).triggerEvent('click');}},500);$(this).observe('click',showNextQuestion);};input.observe('click',showNextQuestion);}});}}}},setRatingLayout:function(id){if(document.getElementById('stage')){return null;} if(typeof CardForm==="object"&&CardForm.layoutParams&&CardForm.layoutParams.hasTouch===false){if(!JotForm.accessible){JotForm.setRatingClickTransfer(id);}} const rating=document.getElementById('rating_'+id);if(!rating)return;const ratingHiddenInput=rating.querySelector('.jfRating-shortcut-input');const ratingItems=rating.querySelector('.jfRating-items');const ratingInputs=rating.querySelectorAll('.jfRating-input');if(!JotForm['ratingFnQueues']){JotForm['ratingFnQueues']=[];} if(!JotForm['ratingFnQueues']['fnQueue_'+id]){JotForm['ratingFnQueues']['fnQueue_'+id]=[];} ratingItems.addEventListener('click',function(){if(typeof CardForm==="object"&&CardForm.layoutParams&&CardForm.layoutParams.hasTouch===false){if(!JotForm.accessible){ratingHiddenInput&&ratingHiddenInput.focus();}}});ratingHiddenInput.addEventListener('keyup',function(){let value=this.value;if(value){if(rating.querySelectorAll('.jfRating-input:checked').length){var ratingBefore=rating.querySelector('.jfRating-input:checked').value;} if(value==="-"){value=parseInt(ratingBefore)-1;} if(value==="+"){value=parseInt(ratingBefore)+1;} value=value.toString();var ratingTargetInput=rating.querySelector('.jfRating-input[value='+value+']');if(ratingTargetInput){ratingTargetInput.checked='checked';JotForm.setRatingItemsChecked(id,value,ratingBefore);}} this.value='';});ratingInputs.forEach(function(ratingInput){ratingInput.addEventListener('mouseenter',function(event){this.closest('.jfRating-item').classList.add('indicate');const ratingItemEach=rating.querySelectorAll('.jfRating-items .jfRating-item.jfRating-selection');ratingItemEach.forEach(function(ratingItem){if(parseInt(event.target.value,10)parseInt(this.value)){return false;} queueProcessor.enqueue(function(){ratingItem.classList.add('checked');});}}},{value:value});} if(ratingBefore&&ratingBefore>selectedValue){ratingSelection=Array.from(ratingSelection).reverse();ratingSelection.forEach(function(ratingItem){if(ratingItem.dataset){const itemValue=ratingItem.dataset.value;if(itemValue){if(itemValue<=this.value){return false;} queueProcessor.enqueue(function(){ratingItem.classList.remove('checked');});}}},{value:value});} document.querySelector('#input_'+id).value=value;const hiddenInput=rating.querySelector('.form-textbox');hiddenInput.value=parseInt(value,10);JotForm.runConditionForId(id.toString());},setRatingClickTransfer:function(){},getScrollbarWidth:function(matrix){var outer=document.createElement("div");outer.style.visibility="hidden";outer.style.width="100px";outer.style.msOverflowStyle="scrollbar";matrix.appendChild(outer);var widthNoScroll=outer.offsetWidth;outer.style.overflow="scroll";var inner=document.createElement("div");inner.style.width="100%";outer.appendChild(inner);var widthWithScroll=inner.offsetWidth;outer.parentNode.removeChild(outer);return widthNoScroll-widthWithScroll;},getOptionOtherInput:function(option){if(!option||!option.classList.contains('form-'+option.type+'-other')){return null;} const otherInputSelector='.form-'+option.type+'-item';const parentWrapper=option.closest(otherInputSelector);if(parentWrapper){const otherSelector='.form-'+option.type+'-other-input';return parentWrapper.querySelector(otherSelector);}},setFullNameAutoFocus:function(id){const prefixDropdown=document.querySelector(`#prefix_${id}`) prefixDropdown.addEventListener('change',()=>{setTimeout(function(){const firstNameInput=document.querySelector(`#first_${id}`) firstNameInput.focus();},500);})},initShoppingBag:function(){},initProductPages:function(){},initDonation:function(){},customToQueryParams:function(text,separator){var match=text.strip().match(/[^#&?]*?=[^#&?]*/g);if(!match||!match[1])return{};return match[1].split(separator||'&').inject({},function(hash,pair){if((pair=pair.split('='))[0]){var key=decodeURIComponent(pair.shift()),value=pair.length>1?pair.join('='):pair[0];if(value!=undefined)try{value=decodeURIComponent(value)}catch(e){value=unescape(value)} if(key in hash){if(!Object.isArray(hash[key]))hash[key]=[hash[key]];hash[key].push(value);} else hash[key]=value;} return hash;});},loadEmbedStyle:function(formID,styles){try{styles=JSON.parse(styles);}catch(e){styles={};} var isEmbed=window.parent!==window;if(!isEmbed){return;} if(window.location.href.indexOf('disableSmartEmbed')>-1){return;} var formCSS=document.getElementById('form-css');if(!formCSS){return;} var parser=document.createElement('a');parser.href=formCSS.href;var params=parser.search.toQueryParams();var embedUrl=params.embedUrl||document.URL;var referrerHash=getMD5(embedUrl);['resetSmartStyle','clearSmartStyle','clearInlineStyle'].each(function(key){var regexPattern=new RegExp('&?'+key+'(?:=[0-9]*)?');var matches=regexPattern.exec(embedUrl);if(matches&&matches[0]){embedUrl=embedUrl.replace(matches[0],'');var keyValue=matches[0].replace('&','').split('=');params[keyValue[0]]=keyValue[1]!==undefined?keyValue[1]:'1';}});if(params.embedUrl){delete(params.embedUrl);} params=Object.toQueryString(params);params+=(params!==''?'&':'')+'embedUrl='+embedUrl;pathname=parser.pathname.split('.css')[0]+'/'+referrerHash+'.css';pathname=pathname.charAt(0)==='/'?pathname.slice(1):pathname;var nextHref=parser.protocol+'//'+parser.hostname+'/'+pathname+'?'+params;this.loadStyleSheet(nextHref,function(){var inlineStyle=((styles[referrerHash]||{})['inlineStyle']||{});if(typeof inlineStyle['embedHeight']!=='undefined'){window.parent.postMessage('setHeight:'+inlineStyle['embedHeight']+':'+formID,'*');} formCSS.remove();});},initOwnerView:function(formID){if(!this.jsForm){return;} var url=this.url;if(!this.url.include('.jotform.pro')){url='https://www.jotform.com'} var src=url+'/ownerView.php?id='+formID;window.parent.postMessage(['loadScript',src,formID].join(':'),'*');},_xdr:function(url,method,data,callback,errback,disableCache){var req;if(XMLHttpRequest){JotForm.createXHRRequest(url,method,data,callback,errback,undefined,disableCache);}else if(XDomainRequest){req=new XDomainRequest();req.open(method,url);req.onerror=errback;req.onload=function(){callback(req.responseText);};req.send(data);}else{errback(new Error('CORS not supported'));}},createXHRRequest:function(url,method,data,callback,errback,forceWithCredentials,disableCache){var req=new XMLHttpRequest();if(forceWithCredentials){req.withCredentials=true;} if('withCredentials'in req){req.open(method,url,true);req.setRequestHeader("Content-type","application/x-www-form-urlencoded");if(disableCache){req.setRequestHeader("Cache-Control","no-cache, no-store, max-age=0");} req.onerror=errback;req.onreadystatechange=function(){if(req.readyState===4){if(req.status>=200&&req.status<400){try{var resp=JSON.parse(req.responseText);var responseErrorCodes=[400,404,401,503,301];if(responseErrorCodes.indexOf(resp.responseCode)>-1){if(resp.responseCode===301){url=url.replace('api.','eu-api.');JotForm.createXHRRequest(url,method,data,callback,errback,forceWithCredentials);return;} errback(resp.message,resp.responseCode);return;} callback(resp);}catch(err){errback(new Error('Error: '+err));}}else{errback(new Error('Response returned with non-OK status'));}}};req.send(data);}},serialize:function(data){var str=[];for(var p in data) str.push(encodeURIComponent(p)+"="+encodeURIComponent(data[p]));return str.join("&");},preparePOST:function(obj,label){postData=new Object();for(var key in obj){value=obj[key];if(label){if(key.indexOf('_')!==-1){keys=key.split('_');key=keys[0]+"]["+keys[1];} key="["+key+"]";} postData[label+key]=value;} return postData;},getPrefillToken:function(){if(typeof document.get.prefillToken!=='undefined')return document.get.prefillToken;var path=window.location.pathname.split('/').splice(2);if(path[0]==='prefill')return path[1].split('?')[0];return false;},livePrefillTokenSuffixes:['6c70','6c71'],isLivePrefillToken:function(token){if(!token)return false;return window.JotForm.livePrefillEnabled&&token.length===36&&JotForm.livePrefillTokenSuffixes.includes(token.slice(-4));},initPrefills:function(){var prefillToken=JotForm.getPrefillToken();var isManualPrefill=getQuerystring('jf_createPrefill')=='1';if(!prefillToken)return;if(JotForm.isLivePrefillToken(prefillToken))return;var _form=document.querySelector('form');var monthNames=["January","February","March","April","May","June","July","August","September","October","November","December"];var isCardForm=window.FORM_MODE==='cardform';var url=JotForm.server+'?action=getPrefillData&formID='+_form.id+'&key='+prefillToken;var data={};JotForm.createXHRRequest(url,'get',null,function(res){$H(res.data).each(function(pair){var isArrayValue=Array.isArray(pair.value);var isValueTypeValid=typeof pair.value==='string'||isArrayValue;if(!isValueTypeValid)return;var isEmptyValue=isArrayValue?pair.value.length===0:pair.value.trim()==='';if(isEmptyValue)return;var useQuestionID=getQuerystring('useQuestionID')=='1'||(res.settings&&res.settings.useQuestionID);var field=$(pair.key);var line;if(useQuestionID){var keys=pair.key.split('-');line=document.querySelector('#id_'+keys[0]);field=line!==null?line.querySelector(keys[1]?'[id*="'+keys[1]+'"]':'input, select, textarea'):null;} if(field===null){var idStringSections=pair.key.split("_");var zeroIndexValue=parseInt(idStringSections.pop())-1;idStringSections.push(zeroIndexValue) var possibleZeroIndexElement=idStringSections.join("_");field=$(possibleZeroIndexElement);if(field===null){var qid='';if(pair.key.indexOf('hour_')>-1){qid=pair.key.replace('hour_','');field=$('input_'+qid+'_hourSelect');}else if(pair.key.indexOf('min_')>-1){qid=pair.key.replace('min_','');field=$('input_'+qid+'_minuteSelect');}else if(pair.key.indexOf('_ampm')>-1){qid=pair.key.substring(pair.key.indexOf("input_")+6,pair.key.lastIndexOf("_ampm"));field=$('ampm_'+qid);}}} if(field===null)return;if(!line)line=field.up('li.form-line');var _name=field.name;_name=_name.slice(_name.indexOf('_')+1);if(typeof document.get[_name]!=='undefined')return;if(field.type==='checkbox'){_name=_name.replace('[]','');} var isLiteMode=keys&&keys[1]==='lite_mode';var questionType=line.getAttribute('data-type');var inputValue=pair.value;if(pair.key.includes('month')&&monthNames.indexOf(pair.value)>-1){inputValue=monthNames.indexOf(pair.value)+1;} if(['control_radio','control_checkbox'].indexOf(questionType)===-1&&isArrayValue){inputValue=inputValue.join(',');} if(questionType==='control_radio'&&!isArrayValue)inputValue=[inputValue];if(['control_time','control_datetime'].indexOf(questionType)>-1&&(!isCardForm||isLiteMode)){field.value=inputValue;if(useQuestionID){field.triggerEvent('blur');field.triggerEvent('complete');}} if(['control_datetime','control_time'].indexOf(questionType)>-1){if(pair.key.indexOf('hour')>-1&&inputValue.charAt(0)==='0'){inputValue=inputValue.substring(1) field.value=inputValue;} var timeInput=line.down('input[id*="_timeInput"]');if(timeInput){var hour=line.down('input[id*="_hourSelect"]').value;var min=line.down('input[id*="_minuteSelect"]').value;if(hour&&min){var calculatedHour=hour.toString().length===1?'0'+hour:hour;timeInput.value=calculatedHour+':'+min;timeInput.triggerEvent('change');}}} if(questionType==='control_inline'&&field.up('.FITB-inptCont[data-type="datebox"]')){var datebox=field.up('.FITB-inptCont[data-type="datebox"]');var dateboxID=datebox.id;if(pair.key.indexOf('lite_mode_')>-1&&dateboxID){var day=res.data[dateboxID.replace('id_','day_')];var month=res.data[dateboxID.replace('id_','month_')];var year=res.data[dateboxID.replace('id_','year_')];if(day&&month&&year){JotForm.formatDate({date:new Date(year,month-1,day),dateField:datebox});}}}else if(['control_radio','control_checkbox'].indexOf(questionType)>-1&&Array.isArray(inputValue)){JotForm.onTranslationsFetch(function(){var foundValues=[];line.querySelectorAll('input.form-checkbox:not(.form-checkbox-other), input.form-radio:not(.form-radio-other)').forEach(function(input){var translatedValues=[input.value];if(typeof FormTranslation!=='undefined'&&Object.values(FormTranslation.dictionary).length>1){Object.values(FormTranslation.dictionary).forEach(function(dictionary){if(dictionary[input.value])translatedValues.push(dictionary[input.value]);});} var foundValue=inputValue.find(function(val){return translatedValues.indexOf(val)>-1;});if(foundValue!==undefined){foundValues.push(foundValue);if(input.checked)return;var isDisabled=input.disabled?!!(input.enable()):false;input.click();if(isDisabled)input.disable();}});var otherOption=line.querySelector('.form-checkbox-other, .form-radio-other');var otherOptionInput=line.querySelector('.form-checkbox-other-input, .form-radio-other-input');if(otherOption&&otherOptionInput){var unusedValues=inputValue.reduce(function(acc,val){if(foundValues.indexOf(val)===-1){acc.push(val);} return acc;},[]);if(unusedValues.length===0)return;var isOtherOptionDisabled=otherOption.disabled?!!(otherOption.enable()):false;otherOption.click();if(isOtherOptionDisabled)otherOption.disable();otherOptionInput.value=unusedValues.join(',');}});}else{if(['control_dropdown'].indexOf(questionType)>-1){data[_name]=inputValue.replace(/\+/g,'{+}');}else{data[_name]=inputValue;}} if(res.settings&&res.settings.fieldBehaviour==='readonly'&&!isManualPrefill){if(['radio','checkbox'].indexOf(field.type)>-1){var qid=line.getAttribute('id').split('_')[1];JotForm.enableDisableField(qid,false);}else{if(field.getAttribute('data-richtext')==='Yes'){var nicContentEditable=field.previousElementSibling.firstChild;if(nicContentEditable){nicContentEditable.setAttribute('contenteditable','false');setTimeout(function waitForTransition(){nicContentEditable.innerHTML=pair.value;},1000)}} field.disable();field.setAttribute('autocomplete',_name);if(!field.hasClassName('conditionallyDisabled')){field.addClassName('conditionallyDisabled');}}}});JotForm.prePopulations(data,true);JotForm.onTranslationsFetch(dispatchCompletedEvent);},function(err){console.log(err);dispatchCompletedEvent();});function dispatchCompletedEvent(){if(document.createEvent){var event=document.createEvent('CustomEvent');event.initEvent('PrefillCompleted',false,false);document.dispatchEvent(event);}} var prefillTokenInputEl=document.createElement('input');prefillTokenInputEl.setAttribute('type','hidden');prefillTokenInputEl.setAttribute('name','prefill_token');prefillTokenInputEl.value=prefillToken;_form.appendChild(prefillTokenInputEl);},createManualPrefill:function(){var isManualPrefill=getQuerystring('jf_createPrefill')=='1';if(!isManualPrefill)return;var errorNavigation=setInterval(function disableScroll(){if(window.ErrorNavigation){clearInterval(errorNavigation);window.ErrorNavigation.disableScrollToBottom();}},300);var manualPrefillStyles='';$$('head')[0].insert(manualPrefillStyles);JotForm.conditions=[];JotForm.fieldConditions={};$$('.always-hidden, .form-field-hidden').each(function(el){var id=el.getAttribute('id').split('_')[1];JotForm.showField(id);});var allowedQuestions=['control_fullname','control_email','control_address','control_phone','control_email','control_datetime','control_inline','control_textbox','control_textarea','control_dropdown','control_radio','control_checkbox','control_number','control_time','control_spinner','control_scale','control_button','control_pagebreak'];$$('.form-line').each(function(line){var type=line.getAttribute('data-type');var id=line.getAttribute('id').split('_')[1];JotForm.requireField(id,false);if(allowedQuestions.indexOf(type)>-1){line.select("input, textarea, select").each(function(elem){if(elem.hasAttribute('readonly')){elem.removeAttribute('readonly');} if(elem.hasAttribute('disabled')){elem.removeAttribute('disabled');}});return;};var notSupportedText="Prefill isn't available for this field.";if(window.FORM_MODE==='cardform'){var questionContent=line.querySelector('.jfCard-question')||line;questionContent.setStyle({'pointer-events':'none','opacity':'0.3'});var notificationContainer=line.querySelector('.jfCard-actionsNotification');var messageContainer=notificationContainer.querySelector('.form-error-message');if(messageContainer){messageContainer.innerHTML=notSupportedText;messageContainer.setStyle({'display':'block'});}else{messageContainer=document.createElement('div');messageContainer.className='form-error-message';messageContainer.setStyle({'display':'block'});messageContainer.innerHTML=notSupportedText;notificationContainer.appendChild(messageContainer);}}else{var inputContainer=line.querySelector('div[class^="form-input"]');var labelContainer=line.querySelector('.form-label');if(inputContainer){inputContainer.setStyle({'pointer-events':'none','opacity':'0.3'});} if(labelContainer){labelContainer.setStyle({'pointer-events':'none','opacity':'0.3'});} var descriptionContent=line.querySelector('.form-description-content');if(descriptionContent){descriptionContent.innerHTML=notSupportedText;}else{JotForm.description(id,notSupportedText);} if(JotForm.newDefaultTheme||JotForm.extendsNewTheme){line.querySelector('.form-description').setStyle({bottom:'auto',top:'0',maxWidth:'220px'});}}});$$('.form-submit-button').each(function(btn){btn.setStyle({'pointer-events':'none','opacity':'0.3'});});window.addEventListener('message',function(event){if(event.data.source!=='jfManual_prefill')return;if(event.data.action==='getFieldsData'||event.data.action==='getFieldsDataForSharing'){var fieldMapping={};var isFirstFullnameMatched=false;var tempKey='';var tempValue=[];var fields=document.querySelectorAll('.form-line');var fullname='';var email='';var hasErrors=false;fields.forEach(function(field){var fieldType=field.getAttribute('data-type');if(allowedQuestions.indexOf(fieldType)===-1)return;if(!hasErrors){hasErrors=field.hasClassName('form-line-error');} var inputs=field.querySelectorAll('input, select, textarea');inputs.forEach(function(input){var inputValue=input.value.trim();if(inputValue==''||(['control_scale','control_radio','control_checkbox'].indexOf(fieldType)>-1&&!input.checked))return;if(fieldType==='control_inline'&&input.getAttribute('type')==='radio'&&!input.checked)return;if(fieldType==='control_checkbox'){tempKey=tempKey||input.id;tempValue.push(inputValue);return;} if(input.id.includes('ampm')){var isRangeInput=input.id.includes('Range');var timeInputs=field.querySelectorAll('input[id*="_timeInput"], select[id*="hour"], select[id*="min"]').filter(function(timeInput){return(timeInput.id.includes('Range')&&isRangeInput)||(!timeInput.id.includes('Range')&&!isRangeInput);});if(!timeInputs.every(function(input){return input.value;})){return;}} fieldMapping[input.id]=input.value;if(fieldType==='control_fullname'&&!isFirstFullnameMatched)fullname=!fullname?inputValue:fullname+' '+inputValue;if(fieldType==='control_email'&&!email)email=inputValue;});if(!isFirstFullnameMatched&&fieldType==='control_fullname')isFirstFullnameMatched=true;if(tempKey&&tempValue)fieldMapping[tempKey]=tempValue;tempKey='';tempValue=[];});var finalSource=event.data.action==='getFieldsDataForSharing'?'jfManual_prefill_forShare':'jfManual_prefill';event.source.postMessage({source:finalSource,formData:{hasErrors:hasErrors},prefillData:{fieldMapping:fieldMapping,fullname:fullname,email:email}},event.origin);}},false)},adjustWorkflowFeatures:function(params){try{if(params||typeof document.get==='object'){if(!params){params={};} var wfTaskType=false;var wfTaskID=params.taskID||document.get.taskID;var targetForm=JotForm&&JotForm.forms&&JotForm.forms[0]?JotForm.forms[0]:false;if(!wfTaskID||!targetForm){return;} var isRequestMoreInfo=(params.requestMoreInfo||document.get.requestMoreInfo)=='1';var isWorkflowAssignFormFilling=(params.workflowAssignFormTask||document.get.workflowAssignFormTask)=='1';switch(true){case isWorkflowAssignFormFilling:wfTaskType='assign-form';break;case isRequestMoreInfo:wfTaskType='request-more-info';break;} if(!wfTaskType){return;} targetForm.appendChild(createHiddenInputElement({name:'wfTaskID',value:wfTaskID}));targetForm.appendChild(createHiddenInputElement({name:'wfTaskType',value:wfTaskType}));}}catch(e){console.log('Error adjusting wf variables',e);}},onTranslationsFetch:function(callback){if(typeof FormTranslation!=='undefined'&&FormTranslation.version!==1&&!FormTranslation.to){setTimeout(function(){JotForm.onTranslationsFetch(callback)},100);}else{callback();}},onLanguageChange:function(callback){var langButton=document.querySelector('#langDd');if(langButton){langButton.addEventListener("click",function(){callback();});}},removeFileForMobile:function(options){if(!options.qid)return;var isDeleted=false;var fileArray=window.filesForMobile['q'+options.qid];fileArray.forEach(function(f,index){if(f&&f.fileName===options.fileNameToDelete&&!isDeleted){fileArray.splice(index,1);isDeleted=true;}})},removeFile:function(options){if(!options.fileElement||!options.fileName)return;const qid=options.fileElement.closest('.form-line').id.split('_')[1];window.sendMessageToJFMobile&&JotForm.removeFileForMobile({qid:qid,fileName:options.fileName}) options.fileElement.parentNode.removeChild(options.fileElement);JotForm.corrected(options.fileElement);JotForm.runConditionForId(qid);},sendFormOpenId:function(form,type){try{var formId=form.id;if(parseInt(formId,10)%10!==4||JotForm.isEditMode())return;var openFormIdInput=form.querySelector('[name="formOpenId_V5"]');if(!openFormIdInput)return;navigator.sendBeacon(JotForm.getAPIEndpoint()+'/form/'+form.id+'/event/'+openFormIdInput.value+'/'+type,{});}catch(error){console.log('unexpected behaviour',error);}}};function getMD5(s){function L(k,d){return(k<>>(32-d))}function K(G,k){var I,d,F,H,x;F=(G&2147483648);H=(k&2147483648);I=(G&1073741824);d=(k&1073741824);x=(G&1073741823)+(k&1073741823);if(I&d){return(x^2147483648^F^H)}if(I|d){if(x&1073741824){return(x^3221225472^F^H)}else{return(x^1073741824^F^H)}}else{return(x^F^H)}}function r(d,F,k){return(d&F)|((~d)&k)}function q(d,F,k){return(d&k)|(F&(~k))}function p(d,F,k){return(d^F^k)}function n(d,F,k){return(F^(d|(~k)))}function u(G,F,aa,Z,k,H,I){G=K(G,K(K(r(F,aa,Z),k),I));return K(L(G,H),F)}function f(G,F,aa,Z,k,H,I){G=K(G,K(K(q(F,aa,Z),k),I));return K(L(G,H),F)}function D(G,F,aa,Z,k,H,I){G=K(G,K(K(p(F,aa,Z),k),I));return K(L(G,H),F)}function t(G,F,aa,Z,k,H,I){G=K(G,K(K(n(F,aa,Z),k),I));return K(L(G,H),F)}function e(G){var Z;var F=G.length;var x=F+8;var k=(x-(x%64))/64;var I=(k+1)*16;var aa=Array(I-1);var d=0;var H=0;while(H>>29;return aa}function B(x){var k="",F="",G,d;for(d=0;d<=3;d++){G=(x>>>(d*8))&255;F="0"+G.toString(16);k=k+F.substr(F.length-2,2)}return k}function J(k){k=k.replace(/rn/g,"n");var d="";for(var F=0;F127)&&(x<2048)){d+=String.fromCharCode((x>>6)|192);d+=String.fromCharCode((x&63)|128)}else{d+=String.fromCharCode((x>>12)|224);d+=String.fromCharCode(((x>>6)&63)|128);d+=String.fromCharCode((x&63)|128)}}}return d}var C=Array();var P,h,E,v,g,Y,X,W,V;var S=7,Q=12,N=17,M=22;var A=5,z=9,y=14,w=20;var o=4,m=11,l=16,j=23;var U=6,T=10,R=15,O=21;s=J(s);C=e(s);Y=1732584193;X=4023233417;W=2562383102;V=271733878;for(P=0;P-1){return true;} return false;});var index;for(var i=0;iwindow.innerHeight){modalTopDistance=productItemHeightRelativeToViewPort-modalHeight+92;} modal.style.top=(modalTopDistance).toString()+'px';},0);}catch(e){console.log('Ground');}} if(isNewUi&&imageUrls.length===0){imageUrls.push(document.querySelectorAll('.form-overlay-item img')[index].src);} if(!imageUrls||!imageUrls.length)return;var divOverlay=document.createElement('div');var divOverlayContent=document.createElement('div');var divImgWrapper=document.createElement('div');var divSliderNavigation=document.createElement('div');var divThumbnail=document.createElement('ul');divOverlay.id='productImageOverlay';divOverlay.className=isNewUi?'overlay new_ui':'overlay old_ui';divOverlay.tabIndex=-1;divOverlayContent.className='overlay-content';divImgWrapper.className='img-wrapper';divSliderNavigation.className='slider-navigation';divOverlay.appendChild(divOverlayContent);divOverlayContent.appendChild(divImgWrapper);divOverlayContent.appendChild(divSliderNavigation);if(isNewUi){divSliderNavigation.appendChild(divThumbnail);} var prevButton=document.createElement('small');var nextButton=document.createElement('small');var closeButton=document.createElement('button');closeButton.innerText='X';prevButton.className='lb-prev-button';nextButton.className='lb-next-button';closeButton.className='lb-close-button';closeButton.setAttribute('tabindex',0);divImgWrapper.appendChild(prevButton);divImgWrapper.appendChild(nextButton);divOverlayContent.appendChild(closeButton);var images=imageUrls.map(function(url){var span=document.createElement('span');span.setAttribute('style','background-image: url("'+encodeURI(url)+'"); display: none');span.setAttribute('url',encodeURI(url));return span;});images[0].style.display='block';var visibleIndex=0;var imgLength=images.length;var sliderListItemClickHandler=function(index){images[visibleIndex].style.display='none';divThumbnail.childElements()[visibleIndex].classList.remove('selected');visibleIndex=index;images[visibleIndex].style.display='block';divThumbnail.childElements()[index].classList.add('selected');} images.each(function(p,index){divImgWrapper.appendChild(p);if(images.length>1){if(!divOverlayContent.hasClassName('has_thumbnail')){divOverlayContent.addClassName('has_thumbnail');} var listItem=document.createElement('li');listItem.onclick=sliderListItemClickHandler.bind(this,index);listItem.setAttribute('style','background-image: url("'+p.getAttribute('url')+'")');if(index===0){listItem.className="selected";} divThumbnail.appendChild(listItem);}});var displayPrevious=function(){images[visibleIndex].style.display='none';visibleIndex-=1;if(visibleIndex==-1)visibleIndex=imgLength-1;images[visibleIndex].style.display='block';divThumbnail.childElements().each(function(element,index){if(visibleIndex===index){element.className="selected";}else{element.className="";}});} prevButton.onclick=displayPrevious;var displayNext=function(){images[visibleIndex].style.display='none';visibleIndex+=1;if(visibleIndex==imgLength)visibleIndex=0;images[visibleIndex].style.display='block';divThumbnail.childElements().each(function(element,index){if(visibleIndex===index){element.className="selected";}else{element.className="";}});} nextButton.onclick=displayNext;divOverlayContent.onclick=function(e){e.stopPropagation();} var close=function(){window.onresize=null;divOverlay.remove();} closeButton.onclick=close;divOverlay.onclick=close;divOverlay.onkeydown=function(e){e.stopPropagation();e.preventDefault();if(e.keyCode==37||e.keyCode==38){displayPrevious();}else if(e.keyCode==39||e.keyCode==40){displayNext();}else if(e.keyCode==27){divOverlay.remove();}} document.body.appendChild(divOverlay);divOverlay.focus();} function isIframeEmbedForm(){try{return((window.self!==window.top)&&(window.location.href.indexOf("isIframeEmbed")>-1));}catch(e){return false;}} function isIframeEmbedFormPure(){try{return(window.self!==window.top);}catch(e){return false;}} function callIframeHeightCaller(){if(!JotForm.iframeHeightCaller){return;} JotForm.iframeHeightCaller();};if(isIframeEmbedForm()){document.querySelector('html').addClassName('isIframeEmbed');window.addEventListener('resize',callIframeHeightCaller);window.addEventListener('DOMContentLoaded',callIframeHeightCaller);} if(isIframeEmbedFormPure()){document.querySelector('html').addClassName('isEmbeded');document.addEventListener('DOMContentLoaded',function(){document.querySelectorAll('img[loading=lazy]').forEach(function(image){image.addEventListener('load',callIframeHeightCaller);});});} function setEncryptedValue(a){var field=a.field;var encryptedValue=a.encryptedValue;var sendAsHiddenField=["control_number","control_spinner","control_email","control_dropdown","control_datetime","control_matrix","control_birthdate","control_time","control_scale","control_rating",];var fieldLine=field.closest('li.form-line');if(!fieldLine){return;} var questionType=fieldLine.readAttribute('data-type');var isAlreadyEncrypted=field.hasAttribute('data-encrypted-answer')&&field.getAttribute('data-encrypted-answer')=="true";if(isAlreadyEncrypted){return;}else{field.dataset.encryptedAnswer='true'} if(questionType=="control_textarea"){document.querySelectorAll('[name="'+field.name+'"]').forEach(function(f){f.value=encryptedValue;});return;} var isMixedEmailType=questionType==='control_mixed'&&field.type==='email';if(sendAsHiddenField.indexOf(questionType)!==-1||field.tagName=="SELECT"||isMixedEmailType){if(questionType=="control_scale"&&!field.checked){return;} appendHiddenInput(field.name,encryptedValue);if(questionType==='control_matrix'){field.name="";} return;} if(field.getAttribute('data-masked')){var maskValue=field.getAttribute('maskvalue');JotForm.setQuestionMasking(`#${field.id}`,'',maskValue,true);} var dataFormatArr=["month","day","year"];var exists=dataFormatArr.some(function(fieldTxt){if(field&&field.id){return(field.id.indexOf(fieldTxt)>=0);}});if(field.getAttribute('data-format')||exists===true){if(field.inputmask&&field.inputmask.remove){field.inputmask.remove();} field.setAttribute('placeholder','');} if(field.type==='number'){field.type='text';} if(questionType==='control_textbox'){field=JotForm.removeValidations(field,"(Alphabetic|AlphaNumeric|Currency|Cyrillic|Email|Numeric|Url)");} field.value=encryptedValue;} function IsValidJsonString(str){try{JSON.parse(str);}catch(e){return false;} return true;} function hasExludedEncryptWidgets(formData){return formData.match(/^data:image/ig)||!!~formData.indexOf('widget_metadata')||IsValidJsonString(formData);};function getFieldsToEncrypt(){var ignoredFields=['control_captcha','control_paypal','control_stripe','control_stripeCheckout','control_stripeACH','control_stripeACHManual','control_2co','control_paypalexpress','control_authnet','control_paypalpro','control_braintree','control_dwolla','control_payment','control_paymentwall','control_square','control_boxpayment','control_eway','control_bluepay','control_worldpay','control_firstdata','control_paypalInvoicing','control_payjunction','control_worldpayus','control_chargify','control_cardconnect','control_echeck','control_bluesnap','control_payu','control_pagseguro','control_moneris','control_sofort','control_skrill','control_sensepass','control_paysafe','control_iyzico','control_gocardless','control_mollie','control_paypalSPB','control_cybersource','control_paypalcomplete','control_payfast'];var fields=[];document.querySelectorAll('.form-textbox, .form-textarea, .form-radio, .form-checkbox, .form-dropdown, .form-number-input, .form-hidden.form-widget').forEach(function(field){var fieldLine=field.closest('li.form-line');if(!fieldLine){return;} var questionType=fieldLine.readAttribute('data-type');if(ignoredFields.indexOf(questionType)!==-1){return;} var isMultipleSelectionInput=['checkbox','radio'].include(field.type);if(isMultipleSelectionInput&&!field.checked){return;} if(questionType==='control_matrix'&&isMultipleSelectionInput){return;} if((!field.value&&questionType!=='control_matrix')||(field.value.length>300&&field.value.indexOf('==')==field.value.length-2)){return;} if(questionType==="control_textarea"&&field.disabled){return;} if(questionType==="control_widget"&&hasExludedEncryptWidgets(field.value)){return;} fields.push(field);});return fields;} function setUnencryptedValueToForm(field){var isUniqueField=JotForm.uniqueField&&JotForm.uniqueField==field.id.replace(/\w+_(\d+)(.+)?/,'$1');if(typeof window.unencryptPaymentField!=='undefined'){unencryptPaymentField();} var fieldId=field.id.replace(/[^_]+_(\d+)(.+)?/,'$1');if(JotForm.fieldsToPreserve.indexOf(fieldId)>-1||isUniqueField){var name=field.name.replace(/(\w+)(\[\w+\])?/,"$1_unencrypted$2");appendHiddenInput(name,field.value);}} function createHiddenInputElement(attributes){var input=document.createElement('input');input.type='hidden';Object.keys(attributes||{}).forEach(function(key){input[key]=attributes[key];});return input;} function appendHiddenInput(name,value,attributes){var form=document.querySelector('.jotform-form');if(form){return form.appendChild(createHiddenInputElement(Object.assign({name:name,value:value},attributes||{},)));}} function trackExecution(value){var form=document.querySelector('.jotform-form');if(form){var jsExecutionTrackerElement=form.querySelector('[name="jsExecutionTracker"]');if(jsExecutionTrackerElement){jsExecutionTrackerElement.value+='=>'+(value+':'+(new Date()).getTime());}else{appendHiddenInput('jsExecutionTracker','restarted:'+(new Date()).getTime());trackExecution(value);}}} function trackSubmitSource(value){$A(document.forms).each(function(form){if(form.name==="form_"+form.id){var submitSourceTrackerElement=form.querySelector('[name="submitSource"]');if(submitSourceTrackerElement){submitSourceTrackerElement.value=value;}else{appendHiddenInput('submitSource',value);}}});} calculateTimeToSubmit=function(){var form=document.querySelector('.jotform-form');if(form){var startTime=new Date().getTime();var timeToSubmitElement=form.querySelector('[name="timeToSubmit"]');if(!timeToSubmitElement){appendHiddenInput('timeToSubmit',0);timeToSubmitElement=form.querySelector('[name="timeToSubmit"]');}else{trackExecution('interval-existed');appendHiddenInput('timeToSubmitExisted',timeToSubmitElement.value+'-bfcache-'+!!JotForm.fromBFCache);timeToSubmitElement.value=0;} if(timeToSubmitElement){var timeToSubmitInterval=setInterval(function(){var seconds=Math.round(((new Date()).getTime()-startTime)/1000);if(Number(timeToSubmitElement.value)>=20){trackExecution('interval-complete');clearInterval(timeToSubmitInterval);}else{timeToSubmitElement.value=seconds;}},1000);}}} testSubmitFunction=function(){trackExecution('onsubmit-fired');trackSubmitSource('onsubmit');} function unencryptPaymentField(){var gateways=["paypalcomplete","square"];var getPaymentFields=$$('input[name="simple_fpc"]').length>0&&gateways.indexOf($$('input[name="simple_fpc"]')[0].getAttribute('data-payment_type'))>-1;var paymentExtras=[{type:"phone",pattern:/Phone|Contact/i},{type:"email",pattern:/email|mail|e-mail/i},{type:"company",pattern:/company|organization/i}];var eligibleFields=$$('.form-line[data-type*="email"],'+'.form-line[data-type*="textbox"],'+'.form-line[data-type*="phone"],'+'.form-line[data-type*="dropdown"],'+'.form-line[data-type*="radio"]');const sortedFields=eligibleFields.sort(function(a,b){return Number(a.id.replace("id_",""))-Number(b.id.replace("id_",""));});if(getPaymentFields){var paymentId=$$('input[name="simple_fpc"]')[0].value;var paymentFieldsToPreserve={};sortedFields.each(function(field){var fieldId=field.id.replace('id_','');var fieldType=field.getAttribute('data-type').replace('control_','');paymentExtras.each(function(extra){if(fieldType===extra.type&&Object.keys(paymentFieldsToPreserve).length<3){var label=field.down('label').innerHTML.strip();if(extra.pattern.exec(label)&&!paymentFieldsToPreserve[extra.type]){paymentFieldsToPreserve[extra.type]=fieldId;if(JotForm.fieldsToPreserve.indexOf(fieldId)===-1){JotForm.fieldsToPreserve.push(fieldId);}}}});});JotForm.fieldsToPreserve.push(paymentId+'_cc_firstName');JotForm.fieldsToPreserve.push(paymentId+'_cc_lastName');}} function shouldSubmitFormAfterEncrypt(){var selfSubmitFields=["control_stripe","control_braintree","control_square","control_eway","control_bluepay","control_mollie","control_stripeACHManual","control_pagseguro","control_moneris","control_paypalcomplete"];if(JotForm.payment==='sensepass'&&JotForm.isDirectFlow==='Yes'){selfSubmitFields.push('control_sensepass');} var hasSelfSubmitField=false;document.querySelectorAll('.form-textbox, .form-textarea, .form-radio, .form-checkbox, .form-dropdown, .form-number-input').forEach(function(field){var fieldLine=field.closest('li.form-line');if(!fieldLine){return;} var questionType=fieldLine.readAttribute('data-type');if(!hasSelfSubmitField){hasSelfSubmitField=selfSubmitFields.indexOf(questionType)>-1;}});var submitFormAfterEncrypt=true;if(hasSelfSubmitField&&JotForm.paymentTotal>0&&JotForm.isPaymentSelected()){submitFormAfterEncrypt=false;} return submitFormAfterEncrypt;} function addEncryptionKeyToForm(encryptionKey){var encryptionKeyInput=document.querySelector('input[name="submissionEncryptionKey"]');if(!encryptionKeyInput){appendHiddenInput('submissionEncryptionKey',encryptionKey);}} function attachScrollToCaptcha(form){let target;const targetParent=document.querySelector('div:not(.grecaptcha-logo) > iframe[src*="google.com/recaptcha"]');if(targetParent!==null&&targetParent!==undefined){const parentElement=targetParent.parentElement;if(parentElement!==null&&parentElement!==undefined){target=parentElement.parentElement;}} if(!target){console.log("couldn't find recaptcha element");return;} if(!form.invisibleCaptchaStyleObserverAttached){const observer=new MutationObserver(()=>{if(target.style.visibility==='visible'){target.scrollIntoView();}});observer.observe(target,{attributes:true,attributeFilter:['style']});form.invisibleCaptchaStyleObserverAttached=true;}} function generateUUID(formID){var len=7;var charSet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';var randomString='';for(var i=0;imax){date.setDate(max);} date.setMonth(m);} switch(el.navAction){case Calendar.NAV_PREVIOUS_YEAR:if(year>calendar.minYear){date.setFullYear(year-1);} break;case Calendar.NAV_PREVIOUS_MONTH:if(mon>0){setMonth(mon-1);} else if(year-->calendar.minYear){date.setFullYear(year);setMonth(11);} break;case Calendar.NAV_TODAY:break;case Calendar.NAV_NEXT_MONTH:if(mon<11){setMonth(mon+1);} else if(year0){for(var index=0;index'+month+'
'+year+'
';title.parentNode.insertAdjacentElement('beforebegin',newHeader);var newMonthNode=newHeader.querySelector('.calendar-new-month');var newYearNode=newHeader.querySelector('.calendar-new-year');newMonthNode.appendChild(prevMonth);newMonthNode.appendChild(nextMonth);newYearNode.appendChild(prevYear);newYearNode.appendChild(nextYear);title.style.display='none';}} Calendar.setup=function(params) {Calendar.params=params;function param_default(name,def){if(!params[name]){params[name]=def;}} param_default('dateField',null);param_default('triggerElement',null);param_default('parentElement',null);param_default('selectHandler',null);param_default('closeHandler',null);var triggerElement=$(params.triggerElement||params.dateField);var isNewTheme=triggerElement.getAttribute('data-version')==='v2';var isLiteMode=triggerElement.className.indexOf('icon-liteMode')>-1;var isAllowTime=triggerElement.getAttribute('data-allow-time')==='Yes';var questionType=triggerElement.getAttribute('data-qtype')||null;var autoCalendar=triggerElement.className.indexOf('showAutoCalendar')>-1;var targetElem=triggerElement.parentElement;var isLiteModeCalendar=triggerElement.className.indexOf('icon-liteMode')>-1;if(!isLiteMode||isAllowTime){targetElem=targetElem.parentElement;} if(params.parentElement) {var calendar=new Calendar(params.parentElement,params.id);calendar.setTranslatedMonths(params.id);calendar.setSelectHandler(params.selectHandler||Calendar.defaultSelectHandler);if(params.dateFormat){calendar.setDateFormat(params.dateFormat);} if(params.dateField){calendar.setDateField(params.dateField);calendar.parseDate(calendar.dateField.innerHTML||calendar.dateField.value);} if(params.startOnMonday){calendar.startOnMonday=true;calendar.create($(params.parentElement));} calendar.limits=params.limits;if(calendar.limits){calendar.fixCustomLimits();calendar.setDynamicLimits();calendar.update(calendar.date);calendar.checkPastAndFuture();} calendar.show();} else {var calendar=new Calendar(undefined,params.id);calendar.setTranslatedMonths(params.id);var triggerInputElement=triggerElement.previousElementSibling;if(isNewTheme){calendar.isNewTheme=isNewTheme;calendar.triggerElement=triggerElement;calendar.triggerInputElement=triggerInputElement;} calendar.limits=params.limits;if(calendar.limits){calendar.fixCustomLimits();calendar.setDynamicLimits();} calendar.setSelectHandler(params.selectHandler||Calendar.defaultSelectHandler);calendar.setCloseHandler(params.closeHandler||Calendar.defaultCloseHandler);calendar.startOnMonday=params.startOnMonday;if(params.dateFormat){calendar.setDateFormat(params.dateFormat);} if(params.dateField){calendar.setDateField(params.dateField);calendar.parseDate(calendar.dateField.innerHTML||calendar.dateField.value);} if(params.dateField){Date.parseDate(calendar.dateField.value||calendar.dateField.innerHTML,calendar.dateFormat);} if(questionType){calendar.container.setAttribute('data-qtype',questionType);} if(isNewTheme){if(!isLiteMode||isAllowTime){calendar.container.className+=' extended';} calendar.container.setAttribute('data-version','v2');handlePopupUI(calendar,{width:targetElem.offsetWidth});} function isCalendarOpen(){if(calendar.container.style.display==='none'){calendar.callCloseHandler();return;} calendar.callCloseHandler();setTimeout(function(){if(isAllowTime){if(isLiteModeCalendar){calendar.showAtElement(targetElem.querySelector('input[id*="lite_mode_"]'));}else{calendar.showAtElement(targetElem.querySelector('input[id*="month_"]'));}}else{calendar.showAtElement(targetElem.querySelector('span input'));}},0);} triggerElement.onclick=triggerCalender;var isLiteMode=triggerElement.className.indexOf('seperatedMode')>-1;if(isNewTheme&&!isLiteMode&&autoCalendar){triggerInputElement.onclick=triggerCalender;} function triggerCalender(event){if(calendar.dateField&&(calendar.dateField.disabled||calendar.dateField.hasClassName('conditionallyDisabled'))){return false;} if(isNewTheme){if(calendar.container.style.display!=='none'){calendar.callCloseHandler();return;} handlePopupUI(calendar,{width:targetElem.offsetWidth});if(isAllowTime){if(isLiteModeCalendar){calendar.showAtElement(targetElem.querySelector('input[id*="lite_mode_"]'));}else{calendar.showAtElement(targetElem.querySelector('input[id*="month_"]'));}}else{if(isLiteModeCalendar){targetElem.querySelector('span input').addClassName('calendar-opened');} calendar.showAtElement(targetElem.querySelector('span input'));}}else{calendar.showAtElement(triggerElement);} if(isNewTheme){window.onorientationchange=isCalendarOpen;} return calendar;};if(calendar.limits){calendar.update(calendar.date);calendar.checkPastAndFuture();} if(calendar.startOnMonday){calendar.update(calendar.date);calendar.create(undefined,params.id);}} try{var getDateFromField=function(){if(calendar.dateField.id){var id=calendar.dateField.id.replace("year_","");if(!$('month_'+id))return new Date();if(id){calendar.id=id;} var month=$('month_'+id)?parseInt($('month_'+id).value)-1:-1;var day=$('day_'+id).value;var year=$('year_'+id).value;if(month>-1&&day&&day!==""&&year&&year!==""){var dat=new Date(year,month,day,0,0,0);if(!calendar.date.equalsTo(dat)){calendar.date=dat;calendar.update(calendar.date);}}}};getDateFromField();calendar.dateField.up("li").observe("date:changed",function(){getDateFromField();if(isNewTheme){handlePopupUI(calendar);}});}catch(e){console.log(e);} return calendar;};Calendar.prototype={container:null,selectHandler:null,closeHandler:null,id:null,minYear:1900,maxYear:2100,dateFormat:'%Y-%m-%d',date:new Date(),currentDateElement:null,shouldClose:false,isPopup:true,dateField:null,startOnMonday:false,initialize:function(parent,id) {if(parent){this.create($(parent),id);} else{this.create(undefined,id);}},fixCustomLimits:function(){var fixDate=function(date){if(date.indexOf('today')>-1){return date;} var arr=date.toString().split("-");date="";if(arr.length>2){date+=(arr[0].length===2?"20"+arr[0]:arr[0])+"-";} if(arr.length>1){date+=JotForm.addZeros(arr[arr.length-2],2)+"-";} date+=JotForm.addZeros(arr[arr.length-1],2);return date;} var lim=this.limits;if("custom"in lim&&lim.custom!==false&&lim.custom instanceof Array){for(var i=0;i")===-1)continue;var range=lim.ranges[i].split(">");var start=fixDate(range[0]);var end=fixDate(range[1]);lim.ranges[i]=start+">"+end;}}},setDynamicLimits:function(){var getComparativeDate=function(dat){var todayKey=dat.indexOf('today')>-1?/today/:new RegExp(Calendar.TODAY.trim(),'i');if(todayKey.test(dat)){var comp=new Date();var offset=parseInt(dat.replace(/\s/g,"").split(todayKey)[1])||0;comp.setDate(comp.getDate()+offset);var getUnselectedDaysCount=function(){var curDate=new Date();var unselectedDaysCount=0;while(curDate<=comp){var dayName=curDate.toLocaleDateString('en-US',{weekday:'long'}).toLowerCase();if(lim.days[dayName]!==undefined&&lim.days[dayName]===false){unselectedDaysCount++;} curDate.setDate(curDate.getDate()+1);} return unselectedDaysCount;} if(lim.countSelectedDaysOnly){comp.setDate(comp.getDate()+getUnselectedDaysCount());} return comp.getFullYear()+"-"+JotForm.addZeros(comp.getMonth()+1,2)+"-"+JotForm.addZeros(comp.getDate(),2);}else{return dat;}} var lim=this.limits lim.start=getComparativeDate(lim.start);lim.end=getComparativeDate(lim.end);if("custom"in lim&&lim.custom!==false&&lim.custom instanceof Array){for(var i=0;i")===-1)continue;var range=lim.ranges[i].split(">");start=getComparativeDate(range[0]);end=getComparativeDate(range[1]);lim.ranges[i]=start+">"+end;}}},update:function(date) {var calendar=this;var today=new Date();var thisYear=today.getFullYear();var thisMonth=today.getMonth();var thisDay=today.getDate();var month=date.getMonth();var dayOfMonth=date.getDate();this.date=new Date(date);date.setDate(1);if(calendar.startOnMonday){date.setDate(-(date.getDay())-5);}else{date.setDate(-(date.getDay())+1);} setTimeout((function(){if(this.id){this.container.setAttribute('id','calendar_'+this.id);}}).bind(this),0);Element.getElementsBySelector(this.container,'tbody tr').each(function(row,i){var rowHasDays=false;row.immediateDescendants().each(function(cell,j){var day=date.getDate();var dayOfWeek=date.getDay();var isCurrentMonth=(date.getMonth()==month);cell.className='';cell.date=new Date(date);cell.update(day);if(!isCurrentMonth){cell.addClassName('otherDay');} else{rowHasDays=true;} if(isCurrentMonth&&day==dayOfMonth){cell.addClassName('selected');calendar.currentDateElement=cell;} var allDays=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"];var makeUnselectable=function(){if(date.getFullYear()==thisYear&&date.getMonth()==thisMonth&&day==thisDay&&$$('.todayButton').length>0){$$('.todayButton').first().setStyle({color:"white"});$$('.todayButton').first().addClassName("unselectable");} cell.setOpacity(0.5);cell.addClassName("unselectable");};var makeSelectable=function(){cell.setOpacity(1);cell.removeClassName("unselectable");};if(calendar.limits){var lim=calendar.limits;makeSelectable();if(allDays[i]in lim.days&&lim.days[allDays[dayOfWeek]]==false){makeUnselectable();} if("future"in lim&&lim.future===false){var now=new Date();if(date>now){makeUnselectable();}} if("past"in lim&&lim.past===false){var now=new Date();var yesterday=new Date();yesterday.setDate(now.getDate()-1);if(date-1){startDate=JotForm.dateFromField(lim.start);}else{var start=lim.start.split("-");if(start.length==3){startDate=new Date(start[0],start[1]-1,start[2]);}} if(date-1){endDate=JotForm.dateFromField(lim.end);}else{var end=lim.end.split("-");if(end.length==3){var endDate=new Date(end[0],end[1]-1,end[2]);}} if(endDate){var nextDay=new Date(endDate);nextDay.setDate(endDate.getDate()+1);if(date>=nextDay){makeUnselectable();}}} if("custom"in lim&&lim.custom!==false&&lim.custom instanceof Array){for(var j=0;j-1){var custom=JotForm.dateFromField(lim.custom[j]);custom=JotForm.addZeros(custom.getFullYear(),2)+"-"+JotForm.addZeros(custom.getMonth()+1,2)+"-"+JotForm.addZeros(custom.getDate(),2);if(custom===date.getFullYear()+"-"+m+"-"+d)makeUnselectable();} if((lim.custom[j]===date.getFullYear()+"-"+m+"-"+d)||(typeof lim.custom[j]=="string"&&lim.custom[j].length===5&&lim.custom[j]===(m+"-"+d))||(typeof lim.custom[j]=="string"&&lim.custom[j].length===2&&lim.custom[j]==d)){makeUnselectable();}}} if("ranges"in lim&&lim.ranges!==false&&lim.ranges instanceof Array){for(var j=0;j")===-1)continue;var range=lim.ranges[j].split(">");var start=range[0];var end=range[1];var startDate;if(start.indexOf("{")>-1){startDate=JotForm.dateFromField(start);}else{startDate=start.split("-");startDate=new Date(startDate[0],startDate[1]-1,startDate[2],0,0,0);} var endDate;if(end.indexOf("{")>-1){endDate=JotForm.dateFromField(end);}else{endDate=end.split("-");endDate=new Date(endDate[0],endDate[1]-1,endDate[2],0,0,0);} if(endDate){endDate.setDate(endDate.getDate()+1);if(date>=startDate&&date=thisYear){unselectable(this.container.down(".nextYear"));}else{selectable(this.container.down(".nextYear"));} if(selectedYear>=thisYear&&selectedMonth>=thisMonth){unselectable(this.container.down(".nextMonth"));}else{selectable(this.container.down(".nextMonth"));}} if("past"in this.limits&&this.limits.past===false){if(selectedYear<=thisYear){unselectable(this.container.down(".previousYear"));}else{selectable(this.container.down(".previousYear"));} if(selectedYear<=thisYear&&selectedMonth<=thisMonth){unselectable(this.container.down(".previousMonth"));}else{selectable(this.container.down(".previousMonth"));}}}},setNames:function(id){Calendar.DAY_NAMES=JotForm.calendarViewDaysTranslated&&JotForm.calendarViewDaysTranslated[id]||JotForm.calenderViewDays&&JotForm.calenderViewDays[id]||JotForm.calendarDays||Calendar.DAY_NAMES;for(var i=0;i<=7;i++){Calendar.SHORT_DAY_NAMES[i]=Calendar.DAY_NAMES[i%Calendar.DAY_NAMES.length].substring(0,1).toUpperCase();} if(JotForm.calendarTodayTranslated){Calendar.TODAY=JotForm.calendarTodayTranslated;}else if(JotForm.calendarOther&&JotForm.calendarOther.today){Calendar.TODAY=JotForm.calendarOther.today;}},setTranslatedMonths:function(id){Calendar.MONTH_NAMES=JotForm.calendarViewMonthsTranslated&&JotForm.calendarViewMonthsTranslated[id]||JotForm.calenderViewMonths&&JotForm.calenderViewMonths[id]||JotForm.calendarMonths||Calendar.MONTH_NAMES;},create:function(parent,id) {this.setNames(id);if(!parent){parent=document.getElementsByTagName('body')[0];this.isPopup=true;}else{this.isPopup=false;} var table=this.table?this.table.update(""):new Element('table');table.setAttribute('summary','Datepicker Popup');this.table=table;var thead=new Element('thead');table.appendChild(thead);if(!JotForm.isSourceTeam&&!JotForm.isMarvelTeam){var row=new Element('tr');var cell=new Element('td',{colSpan:7});cell.addClassName('title');row.appendChild(cell);thead.appendChild(row);} row=new Element('tr');if(JotForm.isSourceTeam){this._drawButtonCell(row,'‹',1,Calendar.NAV_PREVIOUS_MONTH,'previousMonth');var titleMonthTd=new Element('td');titleMonthTd.setAttribute('colspan',2);var titleMonth=new Element('div');titleMonth.addClassName('titleMonth');titleMonthTd.appendChild(titleMonth);row.appendChild(titleMonthTd);this._drawButtonCell(row,'›',1,Calendar.NAV_NEXT_MONTH,'nextMonth');this._drawButtonCell(row,'‹',1,Calendar.NAV_PREVIOUS_YEAR,'previousYear');var titleYearTd=new Element('td');var titleYear=new Element('div');titleYear.addClassName('titleYear');titleYearTd.appendChild(titleYear);row.appendChild(titleYearTd);this._drawButtonCell(row,'›',1,Calendar.NAV_NEXT_YEAR,'nextYear');}else if(JotForm.isMarvelTeam){var calendarTd=new Element('td');calendarTd.setAttribute('colspan',7);var calendarDiv=new Element('div');calendarDiv.addClassName('calendarWrapper');var monthDiv=new Element('div');monthDiv.addClassName('monthWrapper');var titleMonth=new Element('div');titleMonth.addClassName('titleMonth');monthDiv.appendChild(titleMonth);calendarDiv.appendChild(monthDiv);var monthDirectionDiv=new Element('div');monthDirectionDiv.addClassName('controlWrapper-month') this._drawButtonCellasDiv(monthDirectionDiv,'︿',1,Calendar.NAV_PREVIOUS_MONTH,'previousMonth');this._drawButtonCellasDiv(monthDirectionDiv,'﹀',1,Calendar.NAV_NEXT_MONTH,'nextMonth');monthDiv.appendChild(monthDirectionDiv);var yearDiv=new Element('div');yearDiv.addClassName('yearWrapper');var titleYear=new Element('div');titleYear.addClassName('titleYear');yearDiv.appendChild(titleYear);calendarDiv.appendChild(yearDiv);var yearDirectionDiv=new Element('div');yearDirectionDiv.addClassName('controlWrapper-year') this._drawButtonCellasDiv(yearDirectionDiv,'︿',1,Calendar.NAV_PREVIOUS_YEAR,'previousYear');this._drawButtonCellasDiv(yearDirectionDiv,'﹀',1,Calendar.NAV_NEXT_YEAR,'nextYear');yearDiv.appendChild(yearDirectionDiv);row.appendChild(calendarTd);calendarTd.appendChild(calendarDiv);}else{var checkLegacyForm=document.querySelectorAll('.calendar.popup[data-version="v2"]');if(checkLegacyForm&&checkLegacyForm.length>0){this._drawButtonCell(row,'«',1,Calendar.NAV_PREVIOUS_YEAR,"previousYear");this._drawButtonCell(row,'‹',1,Calendar.NAV_PREVIOUS_MONTH,"previousMonth");this._drawButtonCell(row,Calendar.TODAY,3,Calendar.NAV_TODAY,"todayButton");this._drawButtonCell(row,'›',1,Calendar.NAV_NEXT_MONTH,"nextMonth");this._drawButtonCell(row,'»',1,Calendar.NAV_NEXT_YEAR,"nextYear");table&&table.addClassName('calendar-new-header-withSVG');}else{this._drawButtonCell(row,'«',1,Calendar.NAV_PREVIOUS_YEAR,"previousYear");this._drawButtonCell(row,'‹',1,Calendar.NAV_PREVIOUS_MONTH,"previousMonth");this._drawButtonCell(row,Calendar.TODAY,3,Calendar.NAV_TODAY,"todayButton");this._drawButtonCell(row,'›',1,Calendar.NAV_NEXT_MONTH,"nextMonth");this._drawButtonCell(row,'»',1,Calendar.NAV_NEXT_YEAR,"nextYear");}} thead.appendChild(row);row=new Element('tr');var startDay=(this.startOnMonday)?1:0;var endDay=(this.startOnMonday)?7:6;for(var i=startDay;i<=endDay;++i){if(JotForm.isMarvelTeam){cell=new Element('th').update(Calendar.MID_DAY_NAMES[i]);}else{cell=new Element('th').update(Calendar.SHORT_DAY_NAMES[i]);} if(i===startDay||i==endDay){cell.addClassName('weekend');} row.appendChild(cell);} thead.appendChild(row);var tbody=table.appendChild(new Element('tbody'));for(i=7;i>0;--i){row=tbody.appendChild(new Element('tr'));row.addClassName('days');for(var j=7;j>0;--j){cell=row.appendChild(new Element('td'));cell.calendar=this;}} var isExtended=this.container&&this.container.hasClassName('extended');this.container=new Element('div');this.container.setAttribute('aria-hidden',true);this.container.addClassName('calendar');if(this.isPopup){this.container.setStyle({position:'absolute',display:'none'});this.container.addClassName('popup');} if(isExtended){this.container.addClassName('extended');} this.container.appendChild(table);this.update(this.date);Event.observe(this.container,'mousedown',Calendar.handleMouseDownEvent);parent.appendChild(this.container);},_drawButtonCell:function(parent,text,colSpan,navAction,extraClass) {var cell=new Element('td');if(colSpan>1){cell.colSpan=colSpan;} cell.className='button'+(extraClass?" "+extraClass:"");cell.calendar=this;cell.navAction=navAction;cell.innerHTML=text;cell.unselectable='on';parent.appendChild(cell);return cell;},_drawButtonCellasDiv:function(parent,text,colSpan,navAction,extraClass) {var cell=new Element('div');if(colSpan>1){cell.colSpan=colSpan;} cell.className='button'+(extraClass?" "+extraClass:"");cell.calendar=this;cell.navAction=navAction;cell.innerHTML=text;cell.unselectable='on';parent.appendChild(cell);return cell;},callSelectHandler:function() {if(this.selectHandler){this.selectHandler(this,this.date.print(this.dateFormat));var isNewTheme=this.container.getAttribute('data-version')==='v2';if(isNewTheme){handlePopupUI(this);}}},callCloseHandler:function() {if(this.closeHandler){this.closeHandler(this);}},show:function() {this.container.show();if(this.isPopup){window._popupCalendar=this;Event.observe(document,'mousedown',Calendar._checkCalendar);Event.observe(document,'touchstart',Calendar._checkCalendar);}},showAt:function(x,y) {this.show();this.container.setStyle({left:x+'px',top:y+'px'});},showAtElement:function(element) {var firstElement=element.up('span').down('input')||element.up('div').down('input');if(firstElement.up('div').visible()===false){firstElement=element;} var firstPos=Position.cumulativeOffset(firstElement);var x=firstPos[0]+40;var y=firstPos[1]+100+firstElement.getHeight();if(element.id.match(/_pick$/)){var elPos=Position.cumulativeOffset(element);var elX=elPos[0]-140;if(elX>x)x=elX;y=elPos[1]+100+element.getHeight();} this.showAt(x,y);},hide:function() {if(this.isPopup){Event.stopObserving(document,'mousedown',Calendar._checkCalendar);Event.stopObserving(document,'touchstart',Calendar._checkCalendar);} this.container.hide();},parseDate:function(str,format) {if(!format){format=this.dateFormat;} this.setDate(Date.parseDate(str,format));},setSelectHandler:function(selectHandler) {this.selectHandler=selectHandler;},setCloseHandler:function(closeHandler) {this.closeHandler=closeHandler;},setDate:function(date) {if(!date.equalsTo(this.date)){this.update(date);var isNewTheme=this.container.getAttribute('data-version')==='v2';if(isNewTheme){handlePopupUI(this);}}},setDateFormat:function(format) {this.dateFormat=format;},setDateField:function(field) {this.dateField=$(field);},setRange:function(minYear,maxYear) {this.minYear=minYear;this.maxYear=maxYear;}};window._popupCalendar=null;Date.DAYS_IN_MONTH=[31,28,31,30,31,30,31,31,30,31,30,31];Date.SECOND=1000;Date.MINUTE=60*Date.SECOND;Date.HOUR=60*Date.MINUTE;Date.DAY=24*Date.HOUR;Date.WEEK=7*Date.DAY;Date.parseDate=function(str,fmt){var today=new Date();var y=0;var m=-1;var d=0;var a=str.split(/\W+/);var b=fmt.match(/%./g);var i=0,j=0;var hr=0;var min=0;for(i=0;i29)?1900:2000);break;case"%b":case"%B":for(j=0;j<12;++j){if(Calendar.MONTH_NAMES[j].substr(0,a[i].length).toLowerCase()==a[i].toLowerCase()){m=j;break;}} break;case"%H":case"%I":case"%k":case"%l":hr=parseInt(a[i],10);break;case"%P":case"%p":if(/pm/i.test(a[i])&&hr<12){hr+=12;} else if(/am/i.test(a[i])&&hr>=12){hr-=12;} break;case"%M":min=parseInt(a[i],10);break;}} if(isNaN(y)){y=today.getFullYear();} if(isNaN(m)){m=today.getMonth();} if(isNaN(d)){d=today.getDate();} if(isNaN(hr)){hr=today.getHours();} if(isNaN(min)){min=today.getMinutes();} if(y!=0&&m!=-1&&d!=0){return new Date(y,m,d,hr,min,0);} y=0;m=-1;d=0;for(i=0;i31&&y==0){y=parseInt(a[i],10);(y<100)&&(y+=(y>29)?1900:2000);}else if(d==0){d=a[i];}} if(y==0){y=today.getFullYear();} if(m!=-1&&d!=0){return new Date(y,m,d,hr,min,0);} return today;};Date.prototype.getMonthDays=function(month){var year=this.getFullYear();if(typeof month=="undefined"){month=this.getMonth();} if(((0==(year%4))&&((0!=(year%100))||(0==(year%400))))&&month==1){return 29;} else{return Date.DAYS_IN_MONTH[month];}};Date.prototype.getDayOfYear=function(){var now=new Date(this.getFullYear(),this.getMonth(),this.getDate(),0,0,0);var then=new Date(this.getFullYear(),0,0,0,0,0);var time=now-then;return Math.floor(time/Date.DAY);};Date.prototype.getWeekNumber=function(){var d=new Date(this.getFullYear(),this.getMonth(),this.getDate(),0,0,0);var DoW=d.getDay();d.setDate(d.getDate()-(DoW+6)%7+3);var ms=d.valueOf();d.setMonth(0);d.setDate(4);return Math.round((ms-d.valueOf())/(7*864e5))+1;};Date.prototype.equalsTo=function(date){return((this.getFullYear()==date.getFullYear())&&(this.getMonth()==date.getMonth())&&(this.getDate()==date.getDate())&&(this.getHours()==date.getHours())&&(this.getMinutes()==date.getMinutes()));};Date.prototype.setDateOnly=function(date){var tmp=new Date(date);this.setDate(1);this.setFullYear(tmp.getFullYear());this.setMonth(tmp.getMonth());this.setDate(tmp.getDate());};Date.prototype.print=function(str){var m=this.getMonth();var d=this.getDate();var y=this.getFullYear();var wn=this.getWeekNumber();var w=this.getDay();var s={};var hr=this.getHours();var pm=(hr>=12);var ir=(pm)?(hr-12):hr;var dy=this.getDayOfYear();if(ir==0){ir=12;} var min=this.getMinutes();var sec=this.getSeconds();s["%a"]=Calendar.SHORT_DAY_NAMES[w];s["%A"]=Calendar.DAY_NAMES[w];s["%b"]=Calendar.SHORT_MONTH_NAMES[m];s["%B"]=Calendar.MONTH_NAMES[m];s["%C"]=1+Math.floor(y/100);s["%d"]=(d<10)?("0"+d):d;s["%e"]=d;s["%H"]=(hr<10)?("0"+hr):hr;s["%I"]=(ir<10)?("0"+ir):ir;s["%j"]=(dy<100)?((dy<10)?("00"+dy):("0"+dy)):dy;s["%k"]=hr;s["%l"]=ir;s["%m"]=(m<9)?("0"+(1+m)):(1+m);s["%M"]=(min<10)?("0"+min):min;s["%n"]="\n";s["%p"]=pm?"PM":"AM";s["%P"]=pm?"pm":"am";s["%s"]=Math.floor(this.getTime()/1000);s["%S"]=(sec<10)?("0"+sec):sec;s["%t"]="\t";s["%U"]=s["%W"]=s["%V"]=(wn<10)?("0"+wn):wn;s["%u"]=w+1;s["%w"]=w;s["%y"]=(''+y).substr(2,2);s["%Y"]=y;s["%%"]="%";return str.gsub(/%./,function(match){return s[match]||match;});};Date.prototype.__msh_oldSetFullYear=Date.prototype.setFullYear;Date.prototype.setFullYear=function(y){var d=new Date(this);d.__msh_oldSetFullYear(y);if(d.getMonth()!=this.getMonth()){this.setDate(28);} this.__msh_oldSetFullYear(y);};