HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<html class="supernova"><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="alternate" type="application/json+oembed" href="https://www.jotform.com/oembed/?format=json&url=http%3A%2F%2Fwww.jotform.com%2Fform%2F60830194953156" title="oEmbed Form"><link rel="alternate" type="text/xml+oembed" href="https://www.jotform.com/oembed/?format=xml&url=http%3A%2F%2Fwww.jotform.com%2Fform%2F60830194953156" title="oEmbed Form">
<meta property="og:title" content="Test Embed Form" >
<meta property="og:url" content="http://www.jotform.us/form/60830194953156" >
<meta property="og:description" content="Please click the link to complete this form.">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<meta name="HandheldFriendly" content="true" />
<title>Test Embed Form</title>
<link href="https://cdn.jotfor.ms/static/formCss.css?3.3.12261" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="https://cdn.jotfor.ms/css/styles/nova.css?3.3.12261" />
<link type="text/css" media="print" rel="stylesheet" href="https://cdn.jotfor.ms/css/printForm.css?3.3.12261" />
<link type="text/css" rel="stylesheet" href="https://secure.jotform.us/themes/CSS/566a91c2977cdfcd478b4567.css?session=48144504970353"/>
<style type="text/css">
.form-label-left{
width:150px !important;
}
.form-line{
padding-top:12px;
padding-bottom:12px;
}
.form-label-right{
width:150px !important;
}
body, html{
margin:0;
padding:0;
background:false;
}
.form-all{
margin:0px auto;
padding-top:0px;
width:690px;
color:#555 !important;
font-family:"Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Verdana, sans-serif;
font-size:14px;
}
.form-radio-item label, .form-checkbox-item label, .form-grading-label, .form-header{
color: #555;
}
</style>
<script src="https://cdn.jotfor.ms/static/prototype.forms.js" type="text/javascript"></script>
<script src="https://cdn.jotfor.ms/static/jotform.forms.js?3.3.12261" type="text/javascript"></script>
<script type="text/javascript">
JotForm.init(function(){
JotForm.clearFieldOnHide="disable";
JotForm.onSubmissionError="jumpToFirstError";
});
</script>
</head>
<body>
<form class="jotform-form" action="https://submit.jotform.us/submit/60830194953156/" method="post" name="form_60830194953156" id="60830194953156" accept-charset="utf-8">
<input type="hidden" name="formID" value="60830194953156" />
<div class="form-all">
<ul class="form-section page-section">
<li id="cid_1" class="form-input-wide" data-type="control_head">
<div class="form-header-group">
<div class="header-text httal htvam">
<h2 id="header_1" class="form-header">
Test Embed Form
</h2>
</div>
</div>
</li>
<li class="form-line" data-type="control_textbox" id="id_3">
<label class="form-label form-label-left form-label-auto" id="label_3" for="input_3"> only one element </label>
<div id="cid_3" class="form-input jf-required">
<input type="text" class=" form-textbox" data-type="input-textbox" id="input_3" name="q3_onlyOne" size="20" value="" />
</div>
</li>
<li class="form-line" data-type="control_button" id="id_2">
<div id="cid_2" class="form-input-wide">
<div style="margin-left:156px" class="form-buttons-wrapper">
<button id="input_2" type="submit" class="form-submit-button">
Submit
</button>
</div>
</div>
</li>
<li style="display:none">
Should be Empty:
<input type="text" name="website" value="" />
</li>
</ul>
</div>
<input type="hidden" id="simple_spc" name="simple_spc" value="60830194953156" />
<script type="text/javascript">
document.getElementById("si" + "mple" + "_spc").value = "60830194953156-60830194953156";
</script>
</form></body>
</html>
<script type="text/javascript">JotForm.ownerView=true;</script>
/*
*Form CSS
*/
.form-all {
list-style: none;
list-style-position: outside;
margin: 0px;
font-family: Verdana;
font-size: 12px;
}
.form-captcha {
border: 1px solid #ccc;
background: #f5f5f5;
padding: 6px;
width: 152px;
-moz-border-radius: 4px 4px 4px 4px;
-webkit-border-radius: 4px;
border-radius: 4px 4px 4px 4px;
}
.underlined {
text-decoration: underline;
}
#payment_total{
display:inline-block;
}
.form-payment-label {
color:#999999;
display:block;
font-size:9px;
}
.form-payment-subtotal, .form-payment-shipping, .form-payment-tax{
font-size: 0.9em;
max-width: 200px;
overflow: visible;
}
.form-payment-divider {
display: block;
border-bottom: 1px solid lightgrey;
max-width: 200px;
}
.form-payment-total {
max-width: 200px;
display: block;
overflow: visible;
margin: 10px 0;
}
.form-payment-price {
float: right;
}
.form-product-custom_quantity {
width: 30px;
padding-left: 4px;
}
#coupon-message {
font-size: 10px;
font-weight: normal;
white-space: normal;
}
.form-captcha:hover {
border: 1px solid #aaa;
}
.form-captcha-image {
border: 1px solid #aaa;
-moz-border-radius: 4px 4px 4px 4px;
-webkit-border-radius: 4px;
border-radius: 4px 4px 4px 4px;
}
.form-collapse-table{
height:58px;
border:1px solid #ccc;
background:#f5f5f5 url(../../images/soft-grad.png) repeat-x;
position:relative;
}
.form-list{
padding:3px;
border:1px solid #CCC;
-moz-box-shadow:0 1px 1px rgba(0, 0, 0, 0.2) inset;
-webkit-box-shadow:0 1px 1px rgba(0, 0, 0, 0.2) inset;
box-shadow:0 1px 1px rgba(0, 0, 0, 0.2) inset;
}
.form-list option{
padding:2px;
}
.form-list option:nth-child(2n+1){
background:#f5f5f5;
}
.form-textarea {
font-family: "Lucida Grande", Verdana;
white-space: pre-wrap;
}
.form-textarea-limit{
}
.form-textarea-limit > span{
display:inline-block;
}
.form-textarea-limit textarea{
/*border:1px solid #aaa;*/
overflow:auto;
}
.form-textarea-limit textarea:focus{
outline:none !important;
}
.form-textarea-limit-indicator{
/*background: none repeat scroll 0 0 #F5F5F5;
border-color: -moz-use-text-color #AAAAAA #AAAAAA;
border-right: 1px solid #AAAAAA;
border-style: none solid solid;
border-width: medium 1px 1px;*/
color: #666666;
font-size: 9px;
margin-top: -1px;
padding: 2px;
text-align: right;
}
.form-textarea-limit-indicator-error{
color:red;
}
.nicEdit-main {
background-color: white;
}
/* #587647: shrunk lines word wrap problem fix, omer */
.form-line-column .nicEdit-main {
white-space: normal;
}
/*
By: Ibrahim
Ticket: http://www.jotform.com/answers/770434
Asana: https://app.asana.com/0/79151859578366/90318654662926
*/
.form-line-column .form-sub-label {
white-space: normal;
}
.form-datetime-validation-error {
background:#FFAAAA;
color:#fff;
}
.form-collapse-left{
}
.form-collapse-mid{
text-shadow:0px 2px 0px #fff;
float:left;
font-size:18px;
margin:16px 45px 16px 20px;
}
.form-product-item{
display:inline-block;
padding:5px 5px 5px 10px;
position:relative;
overflow: hidden;
}
.form-product-item img {
display:block;
position: static;
margin: 0 12px 0 0;
float:left;
-moz-border-radius: 3px 3px;
-webkit-border-radius: 3px 3px;
border-radius: 3px 3px;
}
.form-product-custom_price {
text-align: right;
width: 30px;
border: 1px solid gray;
margin: 0 2px;
padding: 2px 4px
}
.hover-product-item:hover{
background:#f5f5f5;
color:#000;
}
.form-product-item label, .form-product-item .form-radio, .form-product-item .form-checkbox {
cursor: pointer;
}
.form-special-subtotal {
display: block;
font-size: 10px;
margin-left: 10px;
margin-top: 6px;
}
.form-product-image, .form-product-image-with-options{
margin:5px;
margin-left:10px;
}
.form-product-image-with-options{
position:absolute;
top:15px;
-moz-border-radius:5px 5px;
-webkit-border-radius:5px 5px;
border-radius:5px 5px;
}
.form-radio, .form-checkbox{
vertical-align:middle;
margin:0px;
padding:0px;
}
.form-radio-item, .form-checkbox-item{
margin-top:5px;
float:left;
}
.form-multiple-column, .form-single-column{
display:inline-block;
/*display: inline;
zoom: 1;
*display: inline;*/
}
.form-multiple-column .form-radio-item, .form-multiple-column .form-checkbox-item{
width:150px;
}
.form-radio-item label, .form-checkbox-item label{
margin-left:5px;
}
.form-radio-item br, .form-checkbox-item br{
clear:left;
}
.form-submit-button, .form-submit-reset, .form-submit-print, .form-screen-button{
margin:0px;
overflow:visible;
padding:1px 6px;
width:auto;
}
.form-submit-button::-moz-focus-inner, .form-submit-reset::-moz-focus-inner{
border: 0px;
padding:1px 6px;
}
.form-submit-button.conditionallyDisabled {
opacity: 0.4;
cursor: default;
pointer-events: none;
}
.form-button-red{
border: 1px solid red;
}
.form-button-magenta{
border: 1px solid magenta;
}
.form-screen-message{
/*float:left;*/
width: 260px;
height: 100px;
}
.form-screen-button div{
background-image: url("/images/photo.png");
background-position:center;
background-repeat:no-repeat;
height: 50px;
width: 50px;
}
.form-screen-button {
/*float:left;*/
position:absolute;
top:1px;
margin:0px;
margin-left:10px;
padding:0px;
background: #fdc000; /* Old browsers */
background: -moz-linear-gradient(top, #fdc000 0%, #fe8900 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#fdc000), color-stop(100%,#fe8900)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #fdc000 0%,#fe8900 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #fdc000 0%,#fe8900 100%); /* Opera11.10+ */
background: -ms-linear-gradient(top, #fdc000 0%,#fe8900 100%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fdc000', endColorstr='#fe8900',GradientType=0 ); /* IE6-9 */
background: linear-gradient(top, #fdc000 0%,#fe8900 100%); /* W3C */
-moz-box-shadow:0 1px 0 rgba(255, 255, 255, .6), 0 1px 0 rgba(255,255,255,.6) inset;
-webkit-box-shadow:0 1px 0 rgba(255, 255, 255, .6), 0 1px 0 rgba(255,255,255,.6) inset;
box-shadow:0 1px 0 rgba(255, 255, 255, .6), 0 1px 0 rgba(255,255,255,.6) inset;
border:1px solid #ae5d00;
border-radius: 5px;
}
.form-screen-button:hover {
background: #fcc932; /* Old browsers */
background: -moz-linear-gradient(top, #fcc932 0%, #fc9e32 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#fcc932), color-stop(100%,#fc9e32)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #fcc932 0%,#fc9e32 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #fcc932 0%,#fc9e32 100%); /* Opera11.10+ */
background: -ms-linear-gradient(top, #fcc932 0%,#fc9e32 100%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcc932', endColorstr='#fc9e32',GradientType=0 ); /* IE6-9 */
background: linear-gradient(top, #fcc932 0%,#fc9e32 100%); /* W3C */
border:1px solid #ae5d00;
}
.form-screen-button:active {
background: #fe8900; /* Old browsers */
background: -moz-linear-gradient(top, #fe8900 0%, #fdc000 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#fe8900), color-stop(100%,#fdc000)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #fe8900 0%,#fdc000 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #fe8900 0%,#fdc000 100%); /* Opera11.10+ */
background: -ms-linear-gradient(top, #fe8900 0%,#fdc000 100%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fe8900', endColorstr='#fdc000',GradientType=0 ); /* IE6-9 */
background: linear-gradient(top, #fe8900 0%,#fdc000 100%); /* W3C */
border:1px solid #C56600;
-moz-box-shadow:0 1px 0 rgba(255, 255, 255, .6), 0 -1px 0 rgba(255,255,255,.6) inset;
-webkit-box-shadow:0 1px 0 rgba(255, 255, 255, .6), 0 -1px 0 rgba(255,255,255,.6) inset;
box-shadow:0 1px 0 rgba(255, 255, 255, .6), 0 -1px 0 rgba(255,255,255,.6) inset;
}
.form-screenshot-plate{
background: url("../../images/noises/defaultdesktop.png") repeat scroll 0 0 transparent;
border: 2px solid #545454;
border-radius: 3px 3px 3px 3px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.7) inset;
margin: 10px 0;
text-align: center;
}
.form-screenshot-img{
box-shadow: 0 0 5px rgba(0, 0, 0, 0.7);
margin: 14px 0;
display:inline-block;
}
.form-screenshot-img img{
}
.form-submit-print::-moz-focus-inner{
padding:0px 6px;
}
.form-submit-print{
padding:1px 6px;
}
.form-submit-print img{
margin-left: -14px;
margin-right: 3px;
margin-top: -3px;
}
.form-submit-print{
margin-bottom: -4px;
margin-top: -6px;
margin-left: -6px;
margin-right: 5px;
}
.form-submit-button-img{
border:none !important;
margin:0 !important;
padding:0 !important;
background: none !important;
cursor: pointer !important;
}
.form-collapse-right{
position:absolute;
right:0px;
height:58px;
width:40px;
}
.form-collapse-right-show{
background: url(../../images/arrow-open.png) no-repeat center;
}
.form-collapse-right-hide{
background: url(../../images/arrow-closed.png) no-repeat center;
}
.form-collapse-hidden {
display: none;
}
.form-grading-item {
margin-bottom: 3px;
}
.form-header {
margin:0px;
}
.form-footer {
margin: 0px;
text-align:center;
font-size: 9px;
color: #999;
font-weight: 300;
}
.form-subHeader {
border-top: 1px solid #ccc;
font-style: italic;
}
.form-header-group{
background:#f5f5f5;
border-bottom:1px solid #ccc;
padding:12px;
clear:both;
}
/* ömer 18/08 */
/* Form Header helper sub-classes */
/*.form-header-group.hasImage { display: table-row; }*/
.form-header-group.hasImage > .header-logo { display: table-cell; }
.form-header-group.hasImage > .header-text { display: table-cell; width: 100%; }
/* Header title text alignment */
.httal { text-align: left; } /*this is not added if user didnt select any alignment*/
.httac { text-align: center; }
.httar { text-align: right; }
/* Header title vertical alignment */
.htvat { vertical-align: top; }
.htvam { vertical-align: middle; }
.htvab { vertical-align: bottom; }
/* ömer 18/08 */
/* hasan 19/08 */
/* Form header image margins */
.header-logo-left { margin-right: 1em; }
.header-logo-right { margin-left: 1em; }
/* hasan 19/08 */
.form-footer-group{
/* background:#f5f5f5;*/
/* border-bottom:1px solid #ccc;*/
padding:12px;
clear:both;
}
/*.form-label {
width: 150px;
margin-bottom: 6px;
display:inline-block;
white-space:normal;
}*/
.form-label-top {
margin-bottom:6px;
display:block;
white-space:normal;
}
.form-label-left {
float:left;
display:inline-block;
text-align:left;
padding:3px;
white-space:normal;
}
.form-label-right {
float:left;
display:inline-block;
text-align:right;
margin-bottom:6px;
padding:3px;
white-space:normal;
}
.form-input-wide {
}
.form-section, .form-section-closed {
list-style:none;
list-style-position:outside;
margin:0px;
padding:0px;
position:relative;
zoom:1;
clear:both;
}
.form-section-closed {
overflow: hidden;
height: 60px;
}
.form-input {
display:inline-block;
}
.form-line {
clear:both;
padding:10px;
margin:0px;
/* Changed display to block to prevent a bug in Chrome */
display:block;
width:97%;
width:-moz-available;
/* Removed this because it was changing the size of the migrated forms */
/* border:1px solid transparent ; */
position:relative;
}
.form-line-column{
float:left;
clear:none;
width:auto;
white-space:nowrap;
}
/* Added css rule below to retain display:inline-block for shrunken fields */
.form-line.form-line-column {
display:inline-block;
}
.form-line-column-clear{
clear:left;
width:auto;
}
.form-line-active {
background-color: #FFFFE0;
/*outline: 1px solid #EEEED0;*/
color:#333;
}
.form-matrix-table {
border-collapse: collapse;
font-size: 10px;
margin-bottom: 5px;
}
.form-matrix-column-headers {
border: 1px solid #ccc;
background: #ddd;
color:inherit;
text-align:center;
}
.form-matrix-row-headers {
border: 1px solid #ccc;
background: #ddd;
}
.form-matrix-values {
border: 1px solid #ccc;
background: #f5f5f5;
}
.form-pagebreak{
border-top:1px solid #ccc;
background:#f5f5f5;
height:60px;
clear:left;
}
.form-pagebreak-back-container,
.form-pagebreak-next-container{
float:left;
padding:10px;
padding-top:14px;
}
.form-pagebreak-next-container{
padding-left:0px;
}
.form-pagebreak-back,
.form-pagebreak-next{
-webkit-border-radius:5px 5px;
-webkit-box-shadow:0px 1px 2px #aaa;
-moz-border-radius:5px 5px;
-moz-box-shadow:0px 1px 2px #aaa;
border-radius:5px 5px;
box-shadow:0px 1px 2px #aaa;
border:1px solid #999;
background:#ddd;
padding:5px;
margin:0px;
font-size:14px;
}
.form-pagebreak-next{
margin:0 0 0 20px;
}
.button-hidden {
display:none;
}
.form-required {
margin-left: 5px;
color: red;
}
.form-scale-table {
font-size: 12px;
}
.form-scale-table th {
border-bottom: 1px solid #ccc;
color: #999;
}
.form-product-details {
font-size: 0.8em;
color: inherit;
font-style: normal;
}
.form-product-options-text, .form-product-child-label {
font-weight: normal;
word-wrap: break-word;
}
.form-product-child-table {
margin-top: 4px;
}
.form-product-child-table td, .form-product-child-table th {
padding: 2px 6px;
}
.form-product-child-price {
font-size: 0.786em;
font-weight: bold;
font-style: italic;
color: #999;
min-width: 80px ! important;
}
.form-address-table{
width:330px;
}
.form-address-line{
width:310px;
}
.form-address-city, .form-address-state{
width:144px;
}
.form-address-table td, .form-address-table th{
padding-bottom:10px;
}
.form-address-table select{
width:150px;
}
.form-button-error{
color:red;
display:inline;
text-align: center;
}
.form-pagebreak>.form-button-error {
padding:14px 10px 10px;
display:block;
}
.form-line-error{
background:#FFAAAA;
/*border:1px solid #FFAAAA;*/
color:#333;
}
.form-line-error input:not(#coupon-input), .form-line-error select, .form-line-error textarea, .form-validation-error {
border:1px solid red !important;
-moz-box-shadow:0 0 2px red;
-webkit-box-shadow:0 0 2px red;
box-shadow:0 0 2px red;
}
.form-validation-error.form-input{
border:none;
}
.form-line-active .form-error-message {
display: none;
}
.form-error-message{
/*
right:7px;
top:6px;
*/
z-index:900;
position:absolute;
max-width:130px;
right:0px;
top:0px;
color:#333;
padding:3px;
font-size:10px;
border:4px solid #dd8888;
-webkit-box-shadow:0px 2px 4px rgba(102, 102, 102, 0.5);
-webkit-border-radius:6px 6px;
-moz-box-shadow:0px 2px 4px rgba(102, 102, 102, 0.5);
-moz-border-radius:6px 6px;
box-shadow:0px 2px 4px rgba(102, 102, 102, 0.5);
border-radius:6px 6px;
background:#FFCCCC;
}
.form-error-arrow{
position:absolute;
top:-20px;
left:10px;
height:0px;
width:0px;
border:10px solid transparent;
border-bottom-color:#666;
border-bottom:10px solid rgba(102, 102, 102, 0.3);
}
.form-error-arrow-inner{
position:absolute;
top:1px;
height:0px;
width:0px;
border:10px solid transparent;
border-bottom-color:#FFCCCC;
border-bottom-width:11px;
left:-10px;
top:-10px;
}
.form-input .form-error-message, .form-input-wide .form-error-message{
bottom:-5px;
font-size:11px;
position:relative;
z-index:900;
right:auto;
top:auto;
color:#333;
padding:3px;
max-width:100%;
padding-bottom:3px;
font-size:12px;
border:none;
-moz-box-shadow:0px 2px 4px rgba(102, 102, 102, 0.5);
-webkit-box-shadow:0px 2px 4px rgba(102, 102, 102, 0.5);
-moz-border-radius:6px 6px;
-webkit-border-radius:6px 6px;
box-shadow:0px 2px 4px rgba(102, 102, 102, 0.5);
border-radius:6px 6px;
background:#FFCCCC;
}
/*
.form-input .form-error-message:before,
.form-input-wide .form-error-message:before,
.form-multiple-column:before, .form-single-column:before,
.form-input .form-error-message:after,
.form-input-wide .form-error-message:after,
.form-multiple-column:after, .form-single-column:after {
content: " "; display: table;
}
.form-input .form-error-message:after,
.form-input-wide .form-error-message:after,
.form-multiple-column:after, .form-single-column:after {
clear: both;
}
*/
.form-description{
z-index:1000;
position:absolute;
right:7px;
max-width:150px;
top:6px;
border:4px solid #ccc;
-webkit-border-radius:6px 6px;
-webkit-box-shadow:0px 2px 4px #666;
-moz-border-radius:6px 6px;
-moz-box-shadow:0px 2px 4px #666;
border-radius:6px 6px;
box-shadow:0px 2px 4px #666;
background:#f5f5f5;
white-space:normal;
}
.form-description-content{
padding:10px;
font-size:10px;
color:#333;
}
.form-description-arrow {
border-color:transparent #CCCCCC transparent transparent;
border-style:solid;
border-width:10px;
height:0;
width:0;
left:-24px;
top:7px;
position:absolute;
}
.form-description-arrow-small {
border-color:transparent #F5F5F5 transparent transparent;
border-style:solid;
border-width:7px;
height:0;
width:0;
left:-14px;
top:10px;
position:absolute;
}
.right{
right:33px !important;
float: none !important;
}
.form-line:hover .form-description-indicator, .form-line-active .form-description-indicator{
display:block;
}
.form-description-indicator{
display:none;
height: 100%;
position: absolute;
right: 0;
top: 0;
width: 25px;
background:url(../../images/s-info.png) no-repeat center;
/*border-left:1px solid #ccc;
background-color:#f5f5f5;*/
}
.right .form-description-arrow {
border-color:transparent transparent transparent #CCCCCC;
left:auto;
right:-24px;
}
.right .form-description-arrow-small {
border-color:transparent transparent transparent #F5F5F5;
left:auto;
right:-14px;
}
.form-autocomplete-list{
font-family:Verdana, Geneva, Arial, Helvetica, sans-serif;
font-size:12px;
background:#333;
background:rgba(26,58,81,0.8);
border:1px solid #eee;
border-top:none;
padding:5px 0;
-moz-border-radius-bottomright:10px 10px;
-moz-border-radius-bottomleft:10px 10px;
-moz-box-shadow:0px 5px 10px rgba(0,0,0,0.6);
-webkit-border-bottom-right-radius:10px 10px;
-webkit-border-bottom-left-radius:10px 10px;
-webkit-box-shadow:0px 5px 10px rgba(0,0,0,0.6);
border-radius-bottom-right:10px 10px;
border-radius-bottom-left:10px 10px;
box-shadow:0px 5px 10px rgba(0,0,0,0.6);
}
.form-autocomplete-list-item{
margin:0 5px;
border:1px solid transparent;
color:#fff;
padding:3px;
-moz-border-radius:5px 5px;
-webkit-border-radius:5px;
border-radius:5px 5px;
text-shadow:1px 1px 3px #000;
cursor:pointer;
}
.form-autocomplete-list-item-selected, .form-autocomplete-list-item:hover{
-moz-box-shadow:0 0 4px #333;
-webkit-box-shadow:0 0 4px #333;
box-shadow:0 0 4px #333;
border:1px solid #1a3a51;
background:#4295D1;
}
.form-autocomplete-list-item:hover{
border:1px solid #ccc;
}
.form-sub-label-container{
display:inline-block;
margin-right:5px;
}
.form-sub-label{
color:#999999;
display:block;
font-size:9px;
}
.form-html{
padding:3px;
/*Emre: to prevent HTML textbox to expand more instead of getting shorter after shrinking (50747) */
white-space: normal;
}
.form-radio-other-input, .form.checkbox-other-input {
margin-left:5px;
}
.form-spinner-input-td{
white-space:normal;
}
/**
* Hides the browser default spinner buttons in protoplus based spinner field
*/
.form-spinner-input-td input[type="number"]::-webkit-inner-spin-button,
.form-spinner-input-td input[type="number"]::-webkit-outer-spin-button {
display:none;
}
.edit-hover{ display:none; }
/**
* For custom hint style, to achieve placeholder like color
*/
.form-custom-hint{
color: #aaa !important;
overflow: hidden !important;
}
/**
* FilePicker.io upload styling
*/
.filePicker-button{
border-style: solid;
border-width: 1px;
border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
cursor: pointer;
display: inline-block;
vertical-align: middle;
padding: 9px 24px;
margin-bottom: 0;
font-size: 13px;
line-height: 18px;
text-align: center;
color: #FFFFFF;
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
background: #0074CC; /* Old browsers */
background: -moz-linear-gradient(top, #0088cc 0%, #0055cc 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#0088cc), color-stop(100%,#0055cc)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #0088cc 0%,#0055cc 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #0088cc 0%,#0055cc 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, #0088cc 0%,#0055cc 100%); /* IE10+ */
background: linear-gradient(to bottom, #0088cc 0%,#0055cc 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#0088cc', endColorstr='#0055cc',GradientType=0 ); /* IE6-9 */
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
-moz-box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset, 0 1px 2px rgba(0, 0, 0, 0.05);
-webkit-box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset, 0 1px 2px rgba(0, 0, 0, 0.05);
box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset, 0 1px 2px rgba(0, 0, 0, 0.05);
}
.filePicker-button:hover {
background: #00a0f0; /* Old browsers */
background: -moz-linear-gradient(top, #00a0f0 0%, #0064f0 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#00a0f0), color-stop(100%,#0064f0)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #00a0f0 0%,#0064f0 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #00a0f0 0%,#0064f0 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, #00a0f0 0%,#0064f0 100%); /* IE10+ */
background: linear-gradient(to bottom, #00a0f0 0%,#0064f0 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00a0f0', endColorstr='#0064f0',GradientType=0 ); /* IE6-9 */
}
.filePicker-button:active {
background: #0064f0; /* Old browsers */
background: -moz-linear-gradient(top, #0064f0 0%, #00a0f0 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#0064f0), color-stop(100%,#00a0f0)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #0064f0 0%,#00a0f0 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #0064f0 0%,#00a0f0 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, #0064f0 0%,#00a0f0 100%); /* IE10+ */
background: linear-gradient(to bottom, #0064f0 0%,#00a0f0 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#0064f0', endColorstr='#00a0f0',GradientType=0 ); /* IE6-9 */
}
/**
* Multiple file upload styling
*/
.qq-uploader { position:relative; width:224px;}
.qq-upload-button {
/*background: none repeat scroll 0 0 #B5B5B5;*/
background: #ffa84c; /* old browsers */
background: -moz-linear-gradient(top, #FBCB5D 0%, #EFA003 100%); /* firefox */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#FBCB5D), color-stop(100%,#EFA003)); /* webkit */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#FBCB5D', endColorstr='#EFA003',GradientType=0 ); /* ie */
color: #FFFFFF;
display: block;
font-size:16px;
padding: 8px 0;
text-align: center;
text-shadow: 0 -1px #C64F00;
border: 1px solid #C64F00;
-moz-border-radius:5px 5px;
-webkit-border-radius:5px 5px;
border-radius:5px 5px;
}
.qq-upload-button-hover {
background: #ff7b0d; /* old browsers */
background: -moz-linear-gradient(top, #ff7b0d 0%, #ffa84c 100%); /* firefox */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ff7b0d), color-stop(100%,#ffa84c)); /* webkit */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ff7b0d', endColorstr='#ffa84c',GradientType=0 ); /* ie */
}
.qq-upload-button-focus {outline:1px dotted black;}
.qq-upload-delete{
display:none;
top:0px;
position:absolute;
background: #f85032; /* old browsers */
background: -moz-linear-gradient(top, #f85032 0%, #f16f5c 50%, #f6290c 51%, #f02f17 71%, #e73827 100%); /* firefox */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f85032), color-stop(50%,#f16f5c), color-stop(51%,#f6290c), color-stop(71%,#f02f17), color-stop(100%,#e73827)); /* webkit */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f85032', endColorstr='#e73827',GradientType=0 ); /* ie */
width:20px;
height:100%;
right:0px;
color:#fff;
line-height:20px;
text-align:center;
text-shadow:0 -1px 0px #000;
-moz-border-radius:0px 5px 5px 0px;
-webkit-border-radius:0px 5px 5px 0px;
border-radius:0px 5px 5px 0px;
border-left:1px solid #aaa;
cursor:pointer;
box-sizing: border-box;
}
.qq-upload-delete:hover{
background: #ffb76b; /* old browsers */
background: -moz-linear-gradient(top, #ffb76b 0%, #ffa73d 50%, #ff7c00 51%, #ff7f04 100%); /* firefox */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffb76b), color-stop(50%,#ffa73d), color-stop(51%,#ff7c00), color-stop(100%,#ff7f04)); /* webkit */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffb76b', endColorstr='#ff7f04',GradientType=0 ); /* ie */
}
.qq-upload-list li:hover{
border:1px solid #aaa;
}
.qq-upload-success:hover .qq-upload-delete{
display:block;
}
.qq-upload-drop-area {
position:absolute; top:0; left:0; width:100%; height:100%; min-height: 54px; z-index:2;
background:#F5F5F5;
background:rgba(240, 240, 240, 0.9);
text-align:center;
color:#B1B1B1;
border:2px dashed #c5c5c5;
-moz-border-radius:5px 5px;
-webkit-border-radius:5px 5px;
border-radius:5px 5px;
}
.qq-upload-drop-area span {
display:block; position:absolute; top: 50%; width:100%; margin-top:-10px; font-size:16px;
}
.qq-upload-drop-area-active {
background:lightyellow;
background:rgba(222, 255, 210, 0.9);
}
.qq-upload-list { margin:10px 0; padding:0; list-style:none; }
.qq-upload-list li {
position:relative;
font-size: 11px;
margin: 8px 0;
color: #5E5B5B;
padding: 2px 4px;
background: #EEEEEE;
-moz-border-radius: 5px 5px;
-webkit-border-radius: 5px 5px;
border-radius: 5px 5px;
white-space: normal;
border:1px solid transparent;
}
.qq-upload-file,.qq-upload-spinner, .qq-upload-size, .qq-upload-cancel, .qq-upload-failed-text {
font-size:0.8em;
line-height:16px;
}
.qq-file-uploading{
display: inline-block;
overflow: hidden;
white-space: nowrap;
width: 80px;
}
.qq-upload-failed-text{float:right;}
.qq-upload-fail{
background:#FF927D !important;
color:#fff !important;
}
.qq-upload-fail .qq-upload-size{display:none !important;}
.qq-upload-file {}
.qq-upload-spinner {display:inline-block; background: url("../../images/loading.gif"); width:15px; height:15px; vertical-align:text-bottom;margin-bottom: 3px;margin-left: 2px;}
.qq-upload-size,.qq-upload-cancel {float:right;margin-left: 4px;}
.qq-upload-failed-text {display:none;}
.qq-upload-fail .qq-upload-failed-text {display:inline;}
/**
* FB Login button styles and alignments
*/
.fb-login-wrapper{
}
.fb-align-auto, .fb-align-center{
}
.fb-align-left{
}
.fb-align-right{
}
.fb-login-label{
color: #888888;
font-size: 11px;
line-height: 23px;
}
.fb-login-button{
}
/**
* FB Login End
*/
/**
* Braintree credit card fields styling
*/
.braintree-hosted-fields {
background: rgb(255, 255, 255) none repeat scroll 0% 0% / auto padding-box border-box;
display: inline-block;
width: 147px;
height: 17px;
border: 1px solid lightgrey;
padding: 3px;
}
/* firefox focused field border*/
.braintree-hosted-fields-focused {
border: 1px solid #FFD300 !important;
box-shadow: 0px 0px 3px #FFF0AA;
}
/* webkit focused field border */
@media screen and (-webkit-min-device-pixel-ratio:0) {
.braintree-hosted-fields-focused {
outline: rgb(59, 153, 252) auto 5px;
border: 1px solid lightgrey !important;
}
}
/* braintree add ons */
.braintree-addons-box {
border-radius: 5px;
background-color: #efefef;
padding: 5px;
margin: 6px 0 0 18px;
font-size: 12px;
line-height: 16px;
}
/**
* Braintree End
*/
/* paypal pro */
.paypalpro_img {
width: 40px;
height: 26px;
padding-right: 7px;
}
.paypalpro_visa { background: url('../../images/credit-card-logo.png') no-repeat 0 0; }
.paypalpro_mc { background: url('../../images/credit-card-logo.png') no-repeat -47px 0; }
.paypalpro_amex { background: url('../../images/credit-card-logo.png') no-repeat -94px 0; }
.paypalpro_dc { background: url('../../images/credit-card-logo.png') no-repeat -141px 0; }
/**
* reCaptcha styling
*/
#recaptcha_logo{ display:none;}
#recaptcha_tagline{display:none;}
#recaptcha_table{border:none !important;}
.recaptchatable .recaptcha_image_cell, #recaptcha_table{ background-color:transparent !important; }
#recaptcha_table td { padding-left:0px !important; }
.always-hidden {
display:none !important;
}
.dropdown-match-height {
min-height: 24px;
}
/**
* E-Signature
*/
.signature-pad-passive,
.signature-pad-wrapper {
border: 1px solid #9D9D9D;
color: #444;
}
.signature-pad-passive .signature-line {
border: 1px solid #444;
width: 80%;
position: absolute;
bottom: 50px;
left: 10%;
right: 10%;
}
.signature-pad-wrapper .clear-pad-btn {
cursor:pointer;
text-decoration:underline;
float:right;
font-weight:bold;
font-size:12px;
}
/*
* TODO: This a fix for column view in IE6 and IE7
* only in single column. After relaxing we have
* to change the HTML code directly to fix column
* problems in IE6 and IE7.
*/
.form-single-column .clearfix { display: inline-block; }
.form-single-column .clearfix { display: block; }
/*
* New Feature for fixes for mobile devices.
* We should improve this for each and every kind of question.
* then test it on various mobile devices
*/
@media only screen and (max-device-width: 550px){
body{
/* background:#EAEAEA url(/images/bg.png) repeat-x 0 -55px !important; */
font-size: 18px;
}
.form-all{
width:auto !important;
}
.form-label-left{
float:none;
display:block;
}
.form-buttons-wrapper{
margin:5px !important;
text-align:center;
}
.form-textarea{
/* Emre: to prevent the textareas to overflow when iPhone is used (47600) */
width:94% !important;
white-space: pre-wrap;
}
.form-textbox, .form-textarea, .form-dropdown, .form-list{
border:1px solid #555;
padding:4px;
-webkit-border-radius:5px 5px;
-webkit-box-shadow:0 2px 4px rgba(0,0,0, 0.4) inset;
-moz-border-radius:5px 5px;
-moz-box-shadow:0 2px 4px rgba(0,0,0, 0.4) inset;
border-radius:5px 5px;
box-shadow:0 2px 4px rgba(0,0,0, 0.4) inset;
}
.form-address-table{
width:300px;
}
.form-address-line{
width:280px;
}
.form-address-city, .form-address-state{
width:130px;
}
.form-address-table td, .form-address-table th{
padding-bottom:10px;
}
.form-address-table select{
width:120px;
}
.form-spinner{
border-collapse:inherit !important;
border:1px solid #555 !important;
-webkit-border-radius:5px 5px;
-webkit-box-shadow:0 2px 4px rgba(0,0,0, 0.4) inset;
-moz-border-radius:5px 5px;
-moz-box-shadow:0 2px 4px rgba(0,0,0, 0.4) inset;
border-radius:5px 5px;
box-shadow:0 2px 4px rgba(0,0,0, 0.4) inset;
}
.form-spinner-up, .form-spinner-down{
padding:0 8px !important;
border:none !important;
border-left:1px solid #555 !important;
}
.form-spinner-up{
-moz-border-radius-topright:5px 5px;
-webkit-border-top-right-radius:5px 5px;
border-top-right-radius:5px 5px;
border-bottom:1px solid #555 !important;
}
.form-spinner-down{
-moz-border-radius-bottomright:5px 5px;
-webkit-border-bottom-right-radius:5px 5px;
border-bottom-right-radius:5px 5px;
}
.form-spinner-input-td{
padding-right:6px !important;
}
.form-spinner-input-td input{
padding:4px !important;
background:none;
}
.form-sub-label-container img[id*="pick"]{
width:25px;
}
div.form-header-group{
margin:0px !important;
}
div.form-pagebreak .form-label-left{
display:inline-block !important;
float:left;
}
.form-submit-button, .form-submit-reset{
font-size:18px;
line-height:30px;
}
.form-captcha{
border:1px solid #555;
}
.form-captcha input{
width:120px !important;
}
}
.clearfix2:before,.clearfix2:after{content:" ";display:table;}
.clearfix2:after{clear:both;}
/*
Fix for spinner on firefox 29 and chrome browsers
credits for http://stackoverflow.com/questions/23372903/hide-spinner-in-input-number-firefox-29/23374725#23374725
*/
/* hides the spin-button for firefox */
input[type=number] {
-moz-appearance:textfield;
}
input[id*="_donation"] {
width: 46px;
}
/* hides the spin-button for chrome*/
input[type=number]::-webkit-outer-spin-button,
input[type=number]::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
/* encrypted form-submit-button icon, omer, 15-07-2015 */
.form-submit-button.icon-encrypt {
position: relative;
}
.form-submit-button.icon-encrypt + button {
margin-left: 25px;
}
.form-submit-button.icon-encrypt:before {
/*background: url("../../images/security-icon.png") rgba(0,0,0,0) no-repeat center center;*/
content: url("../../images/security-icon.png");
display: inline-block;
position: absolute;
width: 32px;
height: 32px;
/*background: inherit;*/
right: -36px;
top: 50%;
margin-top: -16px;
/*border-radius: inherit;
-moz-border-radius: inherit;
-webkit-border-radius: inherit;*/
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
/*box-shadow: inherit;
-moz-box-shadow: inherit;
-webkit-box-shadow: inherit;
border: inherit;*/
padding-top: 4px;
}
.form-submit-button.icon-encrypt:after {
content: "This form is encrypted";
display: none;
position: absolute;
width: 128px;
background-color: rgba(0, 0, 0, 0.85);
text-shadow: none;
color: #eee;
font-size: 10px;
top: 50%;
right: -166px;
padding: 5px 0 4px;
border-radius: 2px;
-moz-border-radius: 2px;
-webkit-border-radius: 2px;
line-height: 15px;
margin-top: -12px;
}
/*.form-submit-button.icon-encrypt:hover:before {
background-color: rgba(0, 0, 0, 0.85);
}*/
.form-submit-button.icon-encrypt:hover:after {
display: inline-block;
}
.jotform-ad {
background: red;
display: block !important;
visibility: visible !important;
}
.jotform-ad > a{
text-decoration: none !important;
color: #aaa !important;
}
.jotform-ad > a + a{
color: #f38632 !important;
}
/*jslint nomen:false, debug:true, evil:true, vars:false, browser:true, forin:true, undef:false, white:false */
/**
* JotForm Form object
*/
/* eslint-disable */
var JotForm = {
/**
* JotForm domain
* @var String
*/
url: "//www.jotform.com/", // Will get the correct URL from this.getServerURL() method
/**
* JotForm request server location
* @var String
*/
server: "//www.jotform.com/server.php", // Will get the correct URL from this.getServerURL() method
/**
* All conditions defined on the form
* @var Object
*/
conditions: {},
/**
* All calculations defined on the form
* @var Object
*/
calculations: {},
/**
* Condition Values
* @var Object
*/
condValues: {},
/**
* Progress bar object above form
* @var Object
*/
progressBar: false,
/**
* All JotForm forms on the page
* @var Array
*/
forms: [],
/**
* Will this form be saved on page changes
* @var Boolean
*/
saveForm: false,
/**
* Array of extensions
* @var Array
*/
imageFiles: ["png", "jpg", "jpeg", "ico", "tiff", "bmp", "gif", "apng", "jp2", "jfif"],
/**
* array of autocomplete elements
* @var Object
*/
autoCompletes: {},
/**
* Array of default values associated with element IDs
* @var Object
*/
defaultValues: {},
/**
* Debug mode
* @var Boolean
*/
debug: false,
/**
* Check if the focused inputs must be highligted or not
* @var Boolean
*/
highlightInputs: true,
/**
* it will disable the automatic jump to top on form collapse
* @var Boolean
*/
noJump: false,
/**
* Indicates that form is still under initialization
* @var Boolean
*/
initializing: true,
/**
* Keeps the last focused input
* @var Boolean
*/
lastFocus: false,
/**
* Form's payment type, if any
* @var String
*/
payment: false,
/**
* Fields to preserve (or duplicate) prior to encryption
* @var Array
*/
fieldsToPreserve: [],
/**
* Status of multipage save
* @var Boolean
*/
saving: false,
/**
* Texts used in the form
* @var Object
*/
texts: {
confirmEmail: 'E-mail does not match',
pleaseWait: 'Please wait...',
confirmClearForm: 'Are you sure you want to clear the form',
lessThan: 'Your score should be less than or equal to',
incompleteFields: 'There are incomplete required fields. Please complete them.',
required: 'This field is required.',
requireOne: 'At least one field required.',
requireEveryRow: 'Every row is required.',
requireEveryCell: 'Every cell is required.',
email: 'Enter a valid e-mail address',
alphabetic: 'This field can only contain letters',
numeric: 'This field can only contain numeric values',
alphanumeric: 'This field can only contain letters and numbers.',
cyrillic: 'This field can only contain cyrillic characters',
url: 'This field can only contain a valid URL',
currency: 'This field can only contain currency values.',
fillMask: 'Field value must fill mask.',
uploadExtensions: 'You can only upload following files:',
noUploadExtensions: 'File has no extension file type (e.g. .txt, .png, .jpeg)',
uploadFilesize: 'File size cannot be bigger than:',
uploadFilesizemin: 'File size cannot be smaller than:',
gradingScoreError: 'Score total should only be less than or equal to',
inputCarretErrorA: 'Input should not less than the minimum value:',
inputCarretErrorB: 'Input should not greater than the maximum value:',
maxDigitsError: 'The maximum digits allowed is',
freeEmailError: 'Free email accounts are not allowed',
minSelectionsError: 'The minimum required number of selections is ',
maxSelectionsError: 'The maximum number of selections allowed is ',
pastDatesDisallowed: 'Date must not be in the past.',
dateLimited: 'This date is unavailable.',
dateInvalid: 'This date is not valid. The date format is {format}',
multipleFileUploads_typeError: '{file} has invalid extension. Only {extensions} are allowed.',
multipleFileUploads_sizeError: '{file} is too large, maximum file size is {sizeLimit}.',
multipleFileUploads_minSizeError: '{file} is too small, minimum file size is {minSizeLimit}.',
multipleFileUploads_emptyError: '{file} is empty, please select files again without it.',
multipleFileUploads_onLeave: 'The files are being uploaded, if you leave now the upload will be cancelled.',
multipleFileUploads_fileLimitError: 'Only {fileLimit} file uploads allowed.',
generalError: 'There are errors on the form. Please fix them before continuing.',
generalPageError: 'There are errors on this page. Please fix them before continuing.',
wordLimitError: 'Too many words. The limit is',
wordMinLimitError: 'Too few words. The minimum is',
characterLimitError: 'Too many Characters. The limit is',
characterMinLimitError: 'Too few characters. The minimum is',
ccInvalidNumber: 'Credit Card Number is invalid.',
ccInvalidCVC: 'CVC number is invalid.',
ccInvalidExpireDate: 'Expire date is invalid.',
ccMissingDetails: 'Please fill up the credit card details.',
ccMissingProduct: 'Please select at least one product.',
ccMissingDonation: 'Please enter numeric values for donation amount.',
disallowDecimals: 'Please enter a whole number.'
},
paymentTexts: {
couponApply: 'Apply',
couponChange: 'Change',
couponEnter: 'Enter Coupon',
couponExpired: 'Coupon is expired. Please try another one.',
couponInvalid: 'Coupon is invalid. Please try another one.',
couponValid: 'Coupon is valid.',
couponBlank: 'Please enter a coupon.',
shippingShipping: 'Shipping',
totalTotal: 'Total',
totalSubtotal: 'Subtotal',
taxTax: 'Tax'
},
isEncrypted : false,
encryptAll : function(e, callback) {
e.stop();
var ignoredFields = [
'control_captcha',
'control_paypal',
'control_stripe',
'control_paypalexpress',
'control_authnet',
'control_paypalpro',
'control_paymill',
'control_braintree',
];
var sendAsHiddenField = [
"control_number",
"control_spinner",
"control_email"
];
// payment fields that will submit the form on their own
var selfSubmitFields = [
"control_stripe",
"control_braintree",
];
var submitFormAfterEncrypt = true;
var alreadyEncrypted = [];
var fieldsToPreserve = JotForm.fieldsToPreserve;
$$('.form-textbox, .form-textarea, .form-radio, .form-checkbox, .form-dropdown > option').each(function(field){
// Really? Why? Are they assumed empty? - Alp
//if(JotForm.isVisible(field)) {
var fieldType = field.up('li').readAttribute('data-type');
if (selfSubmitFields.indexOf(fieldType) > -1) {
submitFormAfterEncrypt = false;
}
if (ignoredFields.indexOf(fieldType) !== -1) {
return;
}
//prevent double encryption (especially of textareas)
if (alreadyEncrypted.indexOf(field.name) !== -1) {
return;
}
if (JotForm.paymentTotal > 0) {
fieldId = field.id.replace(/\w+_(\d+)(.+)?/, '$1');
if (fieldsToPreserve.indexOf(fieldId) > -1) {
// duplicate this field, its value is needed in original unencrypted format
var form = $$('.jotform-form')[0];
var name = field.name.replace(/(\w+)(\[\w+\])?/, "$1_unencrypted$2");
form.insert(new Element('input', {type: 'hidden', name: name }).putValue(field.value));
}
}
var encryptedAnswer = JotEncrypted.encrypt(field.value);
//add to encrypted list
alreadyEncrypted.push(field.name);
//handle duplication of textareas, by forcefully encrypting the hidden previous sibling
if (fieldType == "control_textarea") {
var allFields = $$('[name="'+field.name+'"]');
for (x=0; x < allFields.length ; x++) {
allFields[x].value = encryptedAnswer;
}
return;
}
// Send these fields in a hidden field
if(sendAsHiddenField.indexOf(fieldType) !== -1){
var form = $$('.jotform-form')[0];
form.insert(new Element('input', {type: 'hidden', name: field.name}).putValue(encryptedAnswer));
return;
}
field.value = encryptedAnswer;
//}
});
callback(submitFormAfterEncrypt);
},
/**
* Find the correct server url from forms action url, if there is no form use the defaults
*/
getServerURL: function () {
var form = $$('.jotform-form')[0];
var action;
if (form) {
if ((action = form.readAttribute('action'))) {
if (action.include('submit.php') || action.include('server.php')) {
var n = !action.include('server.php') ? "submit" : "server";
this.server = action.replace(n + '.php', 'server.php');
this.url = action.replace(n + '.php', '');
} else {
var d = action.replace(/\/submit\/.*?$/, '/');
this.server = d + 'server.php';
this.url = d;
}
}
}
},
/**
* Changes only the given texsts
* @param {Object} newTexts
*/
alterTexts: function (newTexts, payment) {
if (payment) {
Object.extend(this.paymentTexts, newTexts || {});
this.changePaymentStrings(newTexts);
} else {
Object.extend(this.texts, newTexts || {});
}
},
/**
* A short snippet for detecting versions of IE in JavaScript
* without resorting to user-agent sniffing
*/
ie: function () {
var undef,
v = 3,
div = document.createElement('div'),
all = div.getElementsByTagName('i');
while (
div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
all[0]
);
return v > 4 ? v : undef;
},
/**
* Creates the console arguments
*/
createConsole: function () {
var consoleFunc = ['log', 'info', 'warn', 'error'];
$A(consoleFunc).each(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() + ": " + $A(arguments).join(', '));
} else {
if (Prototype.Browser.IE) {
alert(c + ": " + arguments[0]);
} else {
console[c](arguments[0]);
}
}
}
}
}
};
}.bind(this));
if (JotForm.debug) {
JotForm.debugOptions = document.readJsonCookie('debug_options');
}
},
/**
* Initiates the form and all actions
*/
init: function (callback) {
var ready = function () {
try {
this.populateGet();
if (document.get.debug == "1") {
this.debug = true;
}
this.createConsole();
this.getServerURL();
this.checkJSON();
if (callback) {
callback();
}
if (window.location.href.indexOf("/edit/") !== -1) {
document.get.sid = window.location.href.split("/").last();
this.editMode();
}
//will load editMode script dynamically
if ((document.get.mode == "edit" || document.get.mode == "inlineEdit" || document.get.mode == 'submissionToPDF') && document.get.sid) {
this.editMode();
}
this.noJump = ("nojump" in document.get);
this.uniqueID = this.uniqid();
this.handleSavedForm();
this.setTitle();
this.setHTMLClass();
this.getDefaults();
if(this.noJump) {
window.parent.postMessage("removeIframeOnloadAttr", '*');
}
if ($$('input[name="simple_fpc"]').length > 0) {
this.payment = $$('input[name="simple_fpc"]')[0].getAttribute('data-payment_type');
}
if (!!$$('.form-product-custom_price').length) {
this.handleSubscriptionPrice();
}
if (this.payment === "paypalpro") {
this.handlePaypalPro();
this.isFormEmbedded();
}
if (this.payment === "braintree") {
this.handleBraintree();
}
if (this.payment === "authnet") {
this.handleAuthNet();
}
if (this.payment === "paypalexpress") {
this.handlePaypalExpress();
this.isFormEmbedded();
}
// If coupon button exists, load checkCoupon
if ($('coupon-button')) {
this.handleCoupon();
}
if ($$('.paypal-button').length > 0 && $('use_paypal_button')) {
this.handlePaypalButtons();
}
this.handleFormCollapse();
this.handlePages();
if ($$('.form-product-has-subproducts').length > 0) {
this.handlePaymentSubProducts();
}
// If form is hosted in an iframe, calculate the iframe height
if (window.parent && window.parent != window) {
this.handleIFrameHeight();
// this.removeCover();
}
this.jumpToPage();
this.highLightLines();
this.setButtonActions();
this.initGradingInputs();
this.initSpinnerInputs();
this.initNumberInputs();
this.setConditionEvents();
this.setCalculationEvents();
this.runAllCalculations();
this.setCalculationResultReadOnly();
this.prePopulations();
this.handleAutoCompletes();
this.handleTextareaLimits();
this.handleDateTimeChecks();
this.handleOtherOptions(); // renamed from handleRadioButtons
this.setFocusEvents();
this.disableAcceptonChrome();
this.handleScreenshot();
// this.handleChinaCensorship();
$A(document.forms).each(function (form) {
if (form.name == "form_" + form.id || form.name == "q_form_" + form.id) {
this.forms.push(form);
}
}.bind(this));
var hasCaptcha = $$('div[id^=recaptcha_input]').length;
if (!hasCaptcha || $$('*[class*="validate"]').length > hasCaptcha) {
this.validator();
}
this.fixIESubmitURL();
this.disableHTML5FormValidation();
if ($('progressBar')) {
this.setupProgressBar();
}
// if there is a donation field
if ($$('input[id*="_donation"]').length > 0) {
this.handleDonationAmount();
}
//disable submit if nosubmit=true on request parameters
if (getQuerystring('nosubmit')) {
$$('.form-submit-button').each(function (b) {
b.disable();
});
}
//display all sections
//used for pdf generation
if (getQuerystring('displayAllSections')) {
var sections = $$('.form-section');
// First hide all the pages
sections.each(function (section) {
section.setStyle({display: 'block'});
});
}
// re-enable submit buttons upon browser back button on iOS devices
// #725072
if (!!navigator.userAgent.match(/iPhone|iPad/g)) {
window.onpageshow = function (e) {
if (e.persisted) {
JotForm.enableButtons();
}
}
}
var isPreview = getQuerystring('preview');
isPreview = isPreview ? isPreview === 'true' : false;
if (isPreview) {
this.handlePreview(getQuerystring('filled') === 'true');
} else if(this.initializing) {
this.track();
}
// when a form is embedded via a 3rd party app
this.additionalActionsFormEmbedded();
// render JotForm ad
if(JotForm.showJotFormLogo) {
var formAll = $$('.form-all')[0];
if(formAll) {
var _formID = $$('input[name="formID"]')[0].value;
var colorScheme = 'orange';
var primaryTextColor = '#f38632';
var secondaryTextColor = '#aaa';
var primaryImgSrc = '//cdn.jotfor.ms/img/jot-logo-orange.png?v3';
var primaryBgColor = '#fff';
if(colorScheme === 'white') {
primaryTextColor = '#fff';
secondaryTextColor = '#fff';
primaryImgSrc = '//cdn.jotfor.ms/img/jot-logo-white.png?v2';
primaryBgColor = '#f38632';
}
var bannerWrapper = document.createElement('div');
bannerWrapper.className = 'jotform-ad'
bannerWrapper.style.overflow = 'hidden';
bannerWrapper.style.borderTop = '1px solid #eee';
bannerWrapper.style.padding = '0 18px';
bannerWrapper.style.textDecoration = 'none';
bannerWrapper.style.fontFamily = '"Lucida Grande", "Lucida Sans", "Lucida Sans Unicode", sans-serif';
bannerWrapper.style.fontSize = '12px';
bannerWrapper.style.color = secondaryTextColor
bannerWrapper.style.background = primaryBgColor;
var bannerImgLink = document.createElement('a');
bannerImgLink.href = 'https://www.jotform.com/?utm_source=formfooter&utm_medium=banner&utm_term=' + _formID + '&utm_content=form_footer_banner&utm_campaign=form_footer';
bannerImgLink.target = '_blank';
bannerImgLink.setText('Powered by');
bannerImgLink.style.lineHeight = '48px';
bannerImgLink.style.float = 'left';
bannerImgLink.style.textDecoration = 'none';
var bannerImg = document.createElement('img');
bannerImg.src = primaryImgSrc;
bannerImg.alt = 'JotForm';
bannerImg.style.height = '23px';
bannerImg.style.width = '100px';
bannerImg.style.marginLeft = '3px';
bannerImg.style.marginTop = '-1px';
bannerImg.style.display = 'inline-block';
bannerImg.style.verticalAlign = 'middle';
bannerImg.style.border = 'none';
bannerImgLink.appendChild(bannerImg);
bannerTextLink = document.createElement('a');
bannerTextLink.target = '_blank';
bannerTextLink.href = 'https://www.jotform.com/?utm_source=formfooter&utm_medium=banner&utm_term=' + _formID + '&utm_content=form_footer_text&utm_campaign=form_footer';
bannerTextLink.style.float = 'right';
bannerTextLink.style.color = primaryTextColor;
bannerTextLink.style.lineHeight = '48px';
bannerTextLink.setText('Create your own form today!');
bannerWrapper.appendChild(bannerImgLink);
bannerWrapper.appendChild(bannerTextLink);
formAll.appendChild(bannerWrapper);
}
}
} catch (err) {
JotForm.error(err);
}
this.initializing = false; // Initialization is over
}.bind(this);
if (document.readyState == 'complete' || (this.jsForm && (document.readyState === undefined || document.readyState === 'interactive'))) {
ready();
} else {
document.ready(ready);
}
},
iframeRezizeTimeout: null,
/**
** Call handleIFrameHeight only periodically so millions of messages are not sent when user has lots of conditions
*/
iframeHeightCaller: function() {
if (window.parent && window.parent != window) {
clearTimeout(this.iframeRezizeTimeout);
this.iframeRezizeTimeout = setTimeout((function() {
this.handleIFrameHeight();
}).bind(this), 50);
}
},
handleIFrameHeight: function () {
var form = $$('.jotform-form').length > 0 ? $$('.jotform-form')[0] : $$('body')[0];
var height = Math.max(form.getHeight(), form.scrollHeight, form.offsetHeight);
// if this is a captcha verification page, set height to 300
height = ( document.title === 'Please Complete' ) ? 300 : height;
if ("console" in window) {
if ("log" in console) {
console.log('Debug : setting height to ', height, ' from iframe');
}
}
window.parent.postMessage('setHeight:' + height, '*');
},
removeCover: function () {
$$('.form-cover-wrapper').each(function (el) {
el.remove();
});
$$('.form-all').each(function (el) {
el.removeClassName('top-cover').removeClassName('left-cover').removeClassName('right-cover');
});
},
fixIESubmitURL: function () {
try {
// IE on XP does not support TLS SSL
// http://en.wikipedia.org/wiki/Server_Name_Indication#Support
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, // Cached version of screenshot
passive: false, // States if wishbox iis getting screenshot passively
onprogress: false, // Are we currently processing a screenshot?
compact: false, // Use the compact mode of the editor
imageSaved: false, // Check if the image saved by screenshot editor
/**
* Find screenshot buttons and set events
* HIDE or SHOW according to the environment
*/
handleScreenshot: function () {
var $this = this;
setTimeout(function () {
$$('.form-screen-button').each(function (button) {
//$this.getContainer(button).hide();
// If window parent has feedback then show screenshot
if (window.parent && window.parent.JotformFeedbackManager) {
$this.getContainer(button).show();
button.observe('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';
},
/**
* Convert number of bytes into human readable format
*
* @param integer bytes Number of bytes to convert
* @param integer precision Number of digits after the decimal separator
* @return string
*/
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];
},
/*
* Disables HTML5 validation for stopping browsers to stop submission process
* (fixes bug of pending submissions when jotform validator accepts email field
* and browsers' own validator doesn't )
*/
disableHTML5FormValidation: function () {
$$("form").each(function (f) {
f.setAttribute("novalidate", true);
});
},
/**
* When button clicked take the screenshot and display it in the editor
*/
takeScreenShot: function (id) {
var p = window.parent; // parent window
var pleaseWait = '<div id="js_loading" ' +
'style="position:fixed; z-index:10000000; text-align:center; ' +
'background:#333; border-radius:5px; top: 20px; right: 20px; ' +
'padding:10px; box-shadow:0 0 5 rgba(0,0,0,0.5);">' +
'<img src="' + this.url + 'images/loader-black.gif" />' +
'<div style="font-family:verdana; font-size:12px;color:#fff;">' +
'Please Wait' +
'</div></div>';
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(); // Unique ID to be used in the screenshot
this.scID = id; // Field if which we will place the screen shot in
var f = JotForm.getForm($('button_' + this.scID));
this.sformID = f.formID.value;
this.onprogress = true;
var $this = this; // Cache the scope
//this.wishboxServer = '//ec2-107-22-70-25.compute-1.amazonaws.com/wishbox-bot.php';
this.wishboxServer = 'http://screenshots.jotform.com/wishbox-server.php'; //kemal: made this http since https not working anyway
//this.wishboxServer = "//beta23.jotform.com/server.php";//JotForm.server;
// Create a form element to make a hidden post. We need this to overcome xDomain Ajax restrictions
var form = new Element('form', {
action: this.wishboxServer,
target: 'screen_frame',
id: 'screen_form',
method: 'post',
"accept-charset": 'utf-8'
}).hide();
// Create a syntethic doctype for page source. This is the most common doctype so I choose this
var doc = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" >';
// Hide Jotform specific page element on the parent, so they do not appear on screenshot
/*if(this.compact){
p.$jot('.jt-dimmer').hide();
}else{*/
p.$jot('.jt-dimmer, .jotform-feedback-link, .jt-feedback').hide();
//}
p.$jot('.hide-on-screenshot, .hide-on-screenshot *').css({'visibility': 'hidden'});
// Read the source of parent window
var parentSource = p.document.getElementsByTagName('html')[0].innerHTML;
parentSource = parentSource.replace(/(<noscript\b[^>]*>.*?<\/noscript>)+/gim, ''); // remove single line tags
parentSource = parentSource.replace(/(<noscript\b[^>]*>(\s+.*\s+)+)+<\/noscript>/gim, ''); // remove multi line tags
p.$jot('.hide-on-screenshot, .hide-on-screenshot *').css({'visibility': 'visible'});
parentSource = parentSource.replace(/(\<\/head\>)/gim, "<style>body,html{ min-height: 800px; }</style>$1");
var ie = $this.ie();
// When it's the broken IE use a totally different aproach but IE9 works correctly so skip it
if (ie !== undefined && ie < 9) {
parentSource = parentSource.replace(/(\<\/head\>)/gim, "<style>*{ border-radius:0 !important; text-shadow:none !important; box-shadow:none !important; }</style>$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');
}
// create form elements and place the values respectively
var html = new Element('textarea', {name: 'html'});
var nozip = this.getCharset(p.document).toLowerCase() !== 'utf-8';
if (nozip) {
html.value = encodeURIComponent(doc + parentSource + "</html>");
form.insert(new Element('input', {type: 'hidden', name: 'nozip'}).putValue("1"));
} else {
form.insert(new Element('input', {type: 'hidden', name: 'nozip'}).putValue("0"));
html.value = encodeURIComponent(p.$jot.jSEND((doc + parentSource + "</html>")));
}
var charset = new Element('input', {type: 'hidden', name: 'charset'}).putValue(this.getCharset(p.document));
var height = new Element('input', {type: 'hidden', name: 'height'}).putValue(parseFloat(p.$jot(p).height()));
var scrollTop = new Element('input', {type: 'hidden', name: 'scrollTop'}).putValue(p.$jot(p).scrollTop());
var url = new Element('input', {type: 'hidden', name: 'url'}).putValue(p.location.href);
var uid = new Element('input', {type: 'hidden', name: 'uniqID'}).putValue(this.scuniq);
var fid = new Element('input', {type: 'hidden', name: 'formID'}).putValue(this.sformID);
var action = new Element('input', {type: 'hidden', name: 'action'}).putValue("getScreenshot");
// This is the iframe that we will submit the form into
var iframe = new Element('iframe', {name: 'screen_frame', id: 'screen_frame_id'}).hide();
// When iframe is loaded it usually means screenshot is completed but we still need to make sure.
iframe.observe('load', function () {
// Let's check server if screenshot correctly created there
$this.checkScreenShot();
});
if (p.wishboxInstantLoad && (ie === undefined || ie > 8)) {
this.injectEditor(false, false);
}
// Insert all created elements on the page and directly submit the form
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();
},
/**
* Checks if JSON is available and loads it if not
*/
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);
}
},
/**
* Send a request to server and asks if given screenshot is created
*/
checkScreenShot: function () {
var $this = this;
var p = window.parent;
var count = 10; // will try 10 times after that it will fail
p.$jot.getJSON('http://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); // If screenshot is created inject the editor on the page
}
$this.screenshot = res;
$this.onprogress = false;
// Remove the form and iframe since we don't need them anymore
$('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(); // If not try again. {TODO: We need to limit this check}
}, 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');
}
}
}
);
},
/**
* Injects the screenshot editor on the page and sets necessery functions for editor to use
*/
injectEditor: function (data, url) {
if (this.injected) {
return;
}
this.injected = true;
var $this = this;
var p = window.parent;
p.$jot('#js_loading').remove();
// Ask for editor template code
p.$jot.getJSON(this.server + '?callback=?', {
action: 'getScreenEditorTemplate',
compact: this.compact
},
function (res) {
var iff = '<iframe allowtransparency="true" id="wishbox-frame" src="" ' +
'frameborder="0" style="display:none;border:none; ';
if (!$this.compact) {
iff += 'position:fixed;top:0;width:100%;height:100%;left:0;z-index:100000000;';
} else {
iff += ('position:absolute;left:0;top:10px;height:' + (p.$jot(p).height() - 120) + 'px;width:' + ((p.$jot(p).width() - 100) - p.$jot('#js-form-content').width()) + 'px;');
}
iff += '" scrolling="no"></iframe>';
var editorFrame;
p.iframeWidth = ((p.$jot(p).width() - 100) - p.$jot('#js-form-content').width());
p.iframeHeight = (p.$jot(p).height() - 120);
// create an empty iframe on the page, we will then write the contents of this iframe manually
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({ // when compact
'float': 'right'
});
}
var ie = $this.ie();
// When it's the broken IE use a totally different aproach but IE9 works correctly so skip it
if (ie !== undefined && ie < 9) {
// Set src for iframe inseat of writing the editor template in it.
editorFrame.attr('src', 'http://screenshots.jotform.com/opt/templates/screen_editor.html?shot=' + url + '&uniq=' + $this.scuniq);
// Put a close button outside of the iframe
var b = p.$jot('<button style="color:#fff;font-size:14px;background:#F59202;border:1px solid #Fa98a2;font-weight:bold;position:fixed;top:5px;right:40px;width:100px;z-index:100000001;">Close Editor</button>').appendTo('body');
// When close button clicked go fetch the saved image, if image is not saved then ask user are they sure?
b.click(function () {
p.$jot.getJSON('http://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 {
// Write retrieved editor template into newly created iframe
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);
// Cache the screenshot URL on parent window so editor can find it
p.jotformScreenshotURL = data;
}
// Closes the frame and removes all trace behind it
var closeFrame = function () {
if ($this.compact) {
editorFrame.remove();
p.$jot('#js-form-content').css('width', '100%');
// p.$jot('.jt-content, .jt-title').css('width', 'auto');
} else {
editorFrame.hide('slow', function () {
editorFrame.remove();
});
}
$this.injected = false;
p.$jot('.jt-dimmer, .jotform-feedback-link').show();
p.$jot('.jt-feedback').show('slow');
};
// When image saved. Places it on the form
var putImageOnForm = function (image, url) {
// if(!$this.compact){
$('screen_' + $this.scID).update('<img width="100%" align="center" src="' + (url ? url : image) + '" />');
$('data_' + $this.scID).value = image;
$('screen_' + $this.scID).up().show();
// }
};
// Cancel and close the editor
p.JotformCancelEditor = function () {
closeFrame();
};
// When editing completed retrive the edited screenshot code and place it on the form
p.JotformFinishEditing = function (image) {
closeFrame();
putImageOnForm(image);
$this.imageSaved = true;
if ($this.compact) {
setTimeout(function () {
$(document).fire('image:loaded');
}, 100);
}
};
}
);
},
/**
* Will get additional URL queries from SCRIPT embed or feedback widget
*/
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) {
}
},
/**
* Php.js uniqueID generator
* @param {Object} prefix
* @param {Object} more_entropy
*/
uniqid: function (prefix, more_entropy) {
if (typeof prefix == 'undefined') {
prefix = "";
}
var retId;
var formatSeed = function (seed, reqWidth) {
seed = parseInt(seed, 10).toString(16); // to hex str
if (reqWidth < seed.length) {
return seed.slice(seed.length - reqWidth);
}
if (reqWidth > seed.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;
},
/**
* Initiates multiple upload scripts
*/
initMultipleUploads: function () {
var self = this;
$$('.form-upload-multiple').each(function (file) {
var parent = file.up('div');
var f = JotForm.getForm(file);
var formID = f.formID.value;
var uniq = formID + "_" + JotForm.uniqueID;
// Handle default validations. reuired field
var className = file.className;
if (className.include("validate[required]")) {
if (parent.className.indexOf("validate[required]") === -1) {
parent.addClassName("validate[required]");
}
parent.validateInput = function () {
// Don't fire validations for hidden elements
if (!JotForm.isVisible(parent)) {
JotForm.corrected(parent);
return true;
}
if (parent.select('.qq-upload-list li').length < 1) {
JotForm.errored(parent, JotForm.texts.required);
return false;
} else {
JotForm.corrected(parent);
return true;
}
};
}
// Create temp upload folder key
var hidden = new Element('input', {type: 'hidden', name: 'temp_upload_folder'}).setValue(uniq);
f.insert({top: hidden});
// Handle limited extensions
var exts = (file.readAttribute('file-accept') || "").strip();
exts = (exts !== '*') ? exts.split(', ') : [];
// Handle sublabels
var n, subLabel = "";
if ((n = file.next()) && n.hasClassName('form-sub-label')) {
subLabel = n.innerHTML;
}
//Emre: to make editing "text of multifile upload button" possible (33318)
var m, buttonText;
if (m = file.previous('.qq-uploader-buttonText-value')) {
buttonText = m.innerHTML;
}
if (!buttonText) {
buttonText = "Upload a File";
}
;
// Hasan
// Get button style class
var classNames = file.className.split(' '),
buttonStyle = '';
$A(classNames).each(function (className) {
if (className.indexOf('form-submit-button-') === 0) {
buttonStyle = className;
}
});
// Initiate ajax uploader
var uploader = new qq.FileUploader({
debug: JotForm.debug,
element: parent,
action: JotForm.server,
subLabel: subLabel,
buttonText: buttonText,
buttonStyle: buttonStyle,
fileLimit: file.readAttribute('file-limit'),
sizeLimit: parseInt(file.readAttribute('file-maxsize'), 10) * 1024, // Set file size limit
allowedExtensions: exts,
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, aa, result) {
if (result.success) {
// This is needed for validations.
// removes reuired message
parent.value = "uploaded";
JotForm.corrected(parent);
}
},
showMessage: function (message) {
// Display errors in JotForm's way
JotForm.errored(parent, message);
setTimeout(function () {
// JotForm.corrected(parent);
}, 3000);
},
params: {
action: 'multipleUpload',
field: file.name.replace('[]', ''),
folder: uniq
}
});
});
},
/**
* Hiddenly submits the form on backend
*/
hiddenSubmit: function (frm) {
if (JotForm.currentSection) {
JotForm.currentSection.select('.form-pagebreak')[0].insert(
new Element('div', {className: 'form-saving-indicator'})
.setStyle('float:right;padding:21px 12px 10px')
.update('<img src="' + JotForm.url + 'images/ajax-loader.gif" align="absmiddle" /> Saving...')
);
}
/**
* Wait just a little to set saving status.
* We need this because of the back button hack for last page.
* Last page back button has two click events they both should work
* but saving status prevents second one to be working
*/
setTimeout(function () {
JotForm.saving = true;
}, 10);
if (!$('hidden_submit_form')) {
var iframe = new Element('iframe', {name: 'hidden_submit', id: 'hidden_submit_form'}).hide();
iframe.observe('load', function () {
JotForm.makeUploadChecks();
$$('.form-saving-indicator').invoke('remove');
JotForm.saving = false;
});
$(document.body).insert(iframe);
}
$$('.form-radio-other,.form-checkbox-other').each(function (el) { //disable other textbox if not "other" option selected
if (!el.checked && el.next()) {
el.next().disable();
}
});
$$('.custom-hint-group').each(function (elem) { //remove textarea hints
elem.hideCustomPlaceHolder();
});
$('current_page').value = JotForm.currentSection.pagesIndex;
frm.writeAttribute('target', 'hidden_submit');
frm.insert({
top: new Element('input', {
type: 'hidden',
name: 'hidden_submission',
id: 'hidden_submission'
}).putValue("1")
});
frm.submit();
frm.writeAttribute('target', '');
$('hidden_submission').remove();
$$('.custom-hint-group').each(function (elem) { //reapply textarea hints
elem.showCustomPlaceHolder();
});
$$('.form-radio-other,.form-checkbox-other').each(function (el) { //reenable other textbox if not "other" option selected
if (!el.checked && el.next()) {
el.next().enable();
}
});
},
/**
* Checks the upload fields after hidden submission
* If they are completed, then makes them empty to prevent
* Multiple upload of the same file
*/
makeUploadChecks: function () {
var formIDField = $$('input[name="formID"]')[0];
var a = new Ajax.Jsonp(JotForm.url + 'server.php', {
parameters: {
action: 'getSavedUploadResults',
formID: formIDField.value,
sessionID: document.get.session
},
evalJSON: 'force',
onComplete: function (t) {
var res = t.responseJSON;
if (res.success) {
if (res.submissionID && !$('submission_id')) {
formIDField.insert({
after: new Element('input', {
type: 'hidden',
name: 'submission_id',
id: 'submission_id'
}).putValue(res.submissionID)
});
}
JotForm.editMode(res, true); // Don't reset fields
}
}
});
},
/**
* Handles the form being saved stuation
*/
handleSavedForm: function () {
if (!('session' in document.get) || !(document.get.session.length > 0)) {
return;
}
JotForm.saveForm = true;
var formIDField = $$('input[name="formID"]')[0];
formIDField.insert({
after: new Element('input', {
type: 'hidden',
name: 'session_id',
id: "session"
}).putValue(document.get.session)
});
formIDField.insert({
after: new Element('input', {
type: 'hidden',
id: 'current_page',
name: 'current_page'
}).putValue(0)
});
var a = new Ajax.Jsonp(JotForm.url + 'server.php', {
parameters: {
action: 'getSavedSubmissionResults',
formID: formIDField.value,
sessionID: document.get.session,
URLparams: window.location.href
},
evalJSON: 'force',
onComplete: function (t) {
var res = t.responseJSON;
if (res.success) {
if (res.submissionID) {
formIDField.insert({
after: new Element('input', {
type: 'hidden',
name: 'submission_id',
id: 'submission_id'
}).putValue(res.submissionID)
});
try {
JotForm.editMode(res);
} catch (e) {
console.error(e);
}
JotForm.openInitially = res.currentPage - 1;
}
}
}
});
},
/**
* Place the form title on pages title to remove the Form text on there
*/
setTitle: function () {
// Do this only when page title is form. otherwise it can overwrite the users own title
if (document.title == "Form") {
var head;
if ((head = $$('.form-header')[0])) {
try {
document.title = head.innerHTML.stripTags().strip();
document.title = document.title.unescapeHTML();
} catch (e) {
document.title = head.innerHTML;
}
}
}
},
/*
* Add browser class to html element.
*/
setHTMLClass: function () {
// only ie for now
var ie = this.ie();
if (ie) {
$$('html')[0].addClassName('ie-' + ie);
}
},
/**
* Sets the last focus event to keep latest focused element
*/
setFocusEvents: function () {
$$('.form-radio, .form-checkbox').each(function (input) { //Neil: use mousedown event for radio & checkbox (Webkit bug:181934)
input.observe('mousedown', function () {
JotForm.lastFocus = input;
})
});
$$('.form-textbox, .form-password, .form-textarea, .form-upload, .form-dropdown').each(function (input) {
input.observe('focus', function () {
JotForm.lastFocus = input;
});
});
},
/**
* Disables Accept for Google Chrome browsers
*/
disableAcceptonChrome: function () {
if (!Prototype.Browser.WebKit) {
return;
}
$$('.form-upload').each(function (input) {
if (input.hasAttribute('accept')) {
var r = input.readAttribute('accept');
input.writeAttribute('accept', '');
input.writeAttribute('file-accept', r);
}
});
},
/**
* Populate hidden field with user's browser info
*/
populateBrowserInfo: function (id) {
var userAgent = 'navigator' in window && 'userAgent' in navigator && navigator.userAgent.toLowerCase() || '';
var vendor = 'navigator' in window && 'vendor' in navigator && navigator.vendor.toLowerCase() || '';
var appVersion = 'navigator' in window && 'appVersion' in navigator && navigator.appVersion.toLowerCase() || '';
var is = {
chrome: function(){return /chrome|chromium/i.test(userAgent) && /google inc/.test(vendor)},
firefox: function(){return /firefox/i.test(userAgent)},
ie: function(){return /msie/i.test(userAgent) || "ActiveXObject" in window || /edge\//i.test(userAgent)},
safari: function(){return /safari/i.test(userAgent) && /apple computer/i.test(vendor)},
operabrowser: function(){return userAgent.indexOf("Opera") > -1},
iphone: function(){return /iphone/i.test(userAgent) || /iphone/i.test(appVersion)},
ipad: function(){return /ipad/i.test(userAgent) || /ipad/i.test(appVersion)},
ios: function(){return is.iphone() || is.ipad()},
android: function(){return /android/i.test(userAgent)},
androidPhone: function(){return is.android() && /mobile/i.test(userAgent)},
androidTablet: function(){return is.android() && !is.androidPhone()},
blackberry: function(){return /blackberry/i.test(userAgent) || /BB10/i.test(userAgent)},
linux: function(){return /linux/i.test(appVersion)},
mac: function(){return /mac/i.test(appVersion)},
windows: function(){return /win/i.test(appVersion)},
windowsPhone: function(){return is.windows() && /phone/i.test(userAgent)},
windowsTablet: function(){return is.windows() && !is.windowsPhone() && /touch/i.test(userAgent)},
mobile: function(){return is.iphone() || is.androidPhone() || is.blackberry() || is.windowsPhone();},
tablet: function(){return is.ipad() || is.androidTablet() || is.windowsTablet()},
desktop: function(){return !is.mobile() && !is.tablet()}
};
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()) {
// separate ios detection because the new windows phone user agent now includes ios
// http://www.neowin.net/news/ie11-fakes-user-agent-to-fool-gmail-in-windows-phone-81-gdr1-update
if (is.windowsPhone() || is.androidPhone() || is.blackberry()) return "Mobile";
else if (is.ios()) return "iPhone";
}
else if (is.tablet()) {
// same above
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');
setTimeout(function(){
if ($(id).getValue().length > 0) {
val = [$(id).getValue(), val].join('\n');
}
$(id).setValue(val);
}, 20);
},
/**
* Show Difference Between time ranges
*/
displayTimeRangeDuration: function (id) {
var displayDuration = function () {
if ($('input_' + id + '_hourSelectRange')) {
var sHour = $('input_' + id + '_hourSelect').value;
var sMin = $('input_' + id + '_minuteSelect').value;
var sAMPM = $('input_' + id + '_ampm') ? $('input_' + id + '_ampm').value : 'no';
var eHour = $('input_' + id + '_hourSelectRange').value;
var eMin = $('input_' + id + '_minuteSelectRange').value;
var eAMPM = $('input_' + id + '_ampmRange') ? $('input_' + id + '_ampmRange').value : 'no';
var lab = $('input_' + id + '_ampmRange') ? '_ampmRange' : '_dummy';
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 time is next day
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;
$$('label[for=input_' + id + lab + ']').first().update('<b>Total ' + hours + ':' + min + '</b>');
$$('label[for=input_' + id + lab + ']').first().setStyle({'color': 'black'});
$$('input[id=duration_' + id + '_ampmRange][type="hidden"]').first().setValue(hours + ':' + min);
} else {
$$('label[for=input_' + id + lab + ']').first().update(' ');
}
}
};
$('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);
}
displayDuration();
},
/**
* Set current local time if nodefault not set
*/
displayLocalTime: function (hh, ii, ampm) {
if ($(hh) && !$(hh).hasClassName('noDefault')) {
var date = new Date();
var hour = date.getHours();
var currentAmpm = "";
var twentyFour = true;
if ($(ampm)) {
twentyFour = false;
currentAmpm = (hour > 11) ? 'PM' : 'AM';
hour = (hour > 12) ? hour - 12 : hour;
hour = (hour == 0) ? 12 : hour;
}
var min = date.getMinutes();
var step = Number($(ii).options[2].value) - Number($(ii).options[1].value);
min = Math.round(min / step) * step;
min = this.addZeros(min, 2);
if (min >= 60) { //ntw roll over to next hour/day
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;
}
}
$(hh).value = hour;
$(ii).value = min;
if ($(hh + 'Range')) {
$(hh + 'Range').value = hour;
$(ii + 'Range').value = min;
}
if ($(ampm)) {
if (currentAmpm == 'PM') {
if ($(ampm).select('option[value="PM"]').length > 0) $(ampm).value = 'PM';
if ($(ampm + 'Range') && $(ampm + 'Range').select('option[value="PM"]').length > 0) $(ampm + 'Range').value = 'PM';
} else {
if ($(ampm).select('option[value="AM"]').length > 0) $(ampm).value = 'AM';
if ($(ampm + 'Range') && $(ampm + 'Range').select('option[value="AM"]').length > 0) $(ampm + 'Range').value = 'AM';
}
}
}
},
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: $("id_" + id)});
},
dateLimits: {},
/**
* Sets calendar to field
* @param {Object} id
*/
setCalendar: function (id, startOnMonday, limits) {
try {
JotForm.dateLimits[id] = limits;
var field = $('id_' + id);
var calendar = Calendar.setup({
triggerElement: "input_" + id + "_pick",
dateField: "year_" + id,
closeHandler: function () {
JotForm.calendarClose.apply(this, arguments);
},
selectHandler: function () {
JotForm.formatDate.apply(this, arguments);
},
startOnMonday: startOnMonday,
limits: limits
});
field.observe('keyup', function () {
field.fire('date:changed');
});
var clearDate = function() {
$("month_"+id).value = $("day_"+id).value = $("year_"+id).value = "";
}
var invalidDate = function(invalidDate, calendar) {
invalidDate.addClassName("invalidDate");
clearDate();
}
if ($('lite_mode_' + id)) {
$('lite_mode_' + id).dateChanged = function (e, calendar) {
var lite_mode = e.currentTarget;
var seperator = lite_mode.readAttribute('seperator');
var format = lite_mode.readAttribute('format').toLowerCase();
lite_mode.removeClassName("invalidDate");
if(lite_mode.value === "") {
return clearDate();
}
if(lite_mode.value.length == ((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()) {
invalidDate(lite_mode, calendar);
} else {
calendar.date = _tempDate;
calendar.selectHandler(calendar);
}
} else {
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('keyup', function (e) {
e.stopPropagation();
e.currentTarget.dateChanged(e, calendar);
return false;
});
$('lite_mode_' + id).observe('blur', function (e) {
e.stopPropagation();
/*Dogus: set new date value and run handler*/
e.currentTarget.dateChanged(e, calendar);
e.currentTarget.setAttribute("date-val", calendar.date.getTime());
return false;
});
}
var openCalendar = function () {
var ele = this;
setTimeout(function () {
calendar.showAtElement(ele);
}, 50);
};
if ($('input_' + id + '_pick').hasClassName('showAutoCalendar')) {
var _selectors = [('#day_' + id), ('#month_' + id), ('#year_' + id), ('#lite_mode_' + id)];
$$(_selectors.join(',')).each(function (elem) {
elem.observe('focus', openCalendar);
elem.observe('click', openCalendar);
});
}
$("year_"+id).observe("blur", function() {
calendar.hide();
});
} catch (e) {
JotForm.error(e);
}
},
currentDateReadonly: function () {},
calendarClose: function (calendar) {
var calendarFields = $$('input[id*="' + calendar.dateField.id.match(/[0-9]+/)[0] + '"]');
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();
}
calendar.hide();
},
/**
* Collects all inital values of the fields and saves them as default values
* to be restored later
*/
getDefaults: function () {
$$('.form-textbox, .form-dropdown, .form-textarea').each(function (input) {
if (input.hinted || input.value === "") {
return;
/* continue; */
}
JotForm.defaultValues[input.id] = input.value;
});
$$('.form-radio, .form-checkbox').each(function (input) {
if (!input.checked) {
return;
/* continue; */
}
JotForm.defaultValues[input.id] = input.value;
});
},
/**
* Enables or disables the Other option on radiobuttons/checkboxes
*/
handleOtherOptions: function () {
$$('.form-radio-other-input, .form-checkbox-other-input').each(function (inp) {
inp.hint(inp.getAttribute('data-otherHint') || 'Other');
});
$$('.form-radio, .form-checkbox').each(function (input) {
var id = input.id.replace(/input_(\d+)_\d+/gim, '$1');
if (id.match('other_')) {
id = input.id.replace(/other_(\d+)/, '$1');
}
if ($('other_' + id)) {
var other = $('other_' + id);
var other_input = $('input_' + id);
var otherOption = input.type === 'radio' ? input : other;
other_input.observe('keyup', function () {
other.value = other_input.value;
});
other_input.observe('click', function () {
$('other_' + id).checked = true;
other_input.value = other_input.value === other_input.getAttribute('data-otherHint') ? '' : other_input.value;
});
// perform only on the "Other" option if input is check box
otherOption.observe('click', function () {
if (other.checked) {
other_input.select();
} else {
if (other_input.hintClear) {
other_input.hintClear();
}
}
});
}
});
},
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; //don't shuffle "other"
for (var i = 0; i < length - 1; i++) {
var toSwap = $("id_" + id).select('.form-' + type + '-item')[i];
var randy = Math.floor(Math.random() * length);
var swappedOut = options[randy].replace(toSwap);
var insertAfter = $("id_" + id).select('.form-' + type + '-item')[i].next() ? $("id_" + id).select('.form-' + type + '-item')[i].next() : $("id_" + id).select('.form-' + type + '-item')[i];
insertAfter.insert({after: swappedOut});
}
//deal with columns
if ($("id_" + id).down('.form-multiple-column')) {
var columnCount = $("id_" + id).down('.form-multiple-column').readAttribute("data-columncount");
$("id_" + id).select('.form-' + type + '-item').each(function (item, i) {
item.setStyle({'clear': (i % columnCount == 0) ? 'left' : 'none'});
});
}
} catch (e) {
console.log(e);
}
} else if (type === "select") {
try {
var clone = $('input_' + id).clone(true);
$('input_' + id).update("");
var length = clone.length;
$('input_' + id).insert(clone[0].clone(true));
for (var i = 1; i < length; i++) {
var randy = Math.floor(Math.random() * (clone.length - 1)) + 1;
$('input_' + id).insert(clone[randy].clone(true));
clone[randy].remove();
}
} catch (e) {
console.log(e);
}
} else if (type === "matrix") {
try {
var rows = $("id_" + id).select('tr');
var len = rows.length
for(var i=1; i<len; i++) {
var randy = Math.floor(Math.random() * (len-1)) + 1;
var swappedOut = rows[randy].replace(rows[i]);
var insertAfter = rows[i].next() ? rows[i].next() : rows[i];
insertAfter.insert({after: swappedOut});
}
} catch(e) {
console.log(e);
}
}
},
handleDateTimeChecks: function () {
try {
$$('[name$=\[month\]]').each(function (monthElement) {
var isBirthdate = monthElement.type !== "tel" && monthElement.type !== "text";
var questionId = isBirthdate ? monthElement.id.replace(new RegExp('.*?([0-9]+).*', 'gim'), '$1') : monthElement.id.split('month_').last() ;
var dateElement = $('id_' + questionId);
if (!dateElement)
return;
var dayElement = dateElement.down('[id*=day]');
var yearElement = dateElement.down('[id*=year]');
var hourElement = dateElement.select('#hour_' + questionId).first();
var minElement = dateElement.select('#min_' + questionId).first();
var ampmElement = dateElement.select('#ampm_' + questionId).first();
var dateTimeCheck = function (e) {
var erroredElement = null;
var ignoreBirthdate = isBirthdate && (monthElement.value === "" || dayElement.value === "" || yearElement.value === "");
if (!ignoreBirthdate && (monthElement.value != "" || dayElement.value != "" || yearElement.value != "")) {
var month = isBirthdate ? monthElement.selectedIndex : monthElement.value;
month = parseInt(month);
var day = +dayElement.value;
var year = +yearElement.value;
if (isNaN(year) || year < 0) {
erroredElement = yearElement;
} else if ((isNaN(month) || month < 1 || month > 12) && (document.activeElement != monthElement && document.activeElement != dayElement)) {
erroredElement = monthElement;
} else if ((isNaN(day) || day < 1)) {
// timeout to get correct active element
setTimeout(function () {
if ((document.activeElement != monthElement && document.activeElement != dayElement)) {
erroredElement = dayElement;
}
}, 50)
} 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;
}
}
}
if (!erroredElement && hourElement && minElement && (hourElement.value != "" || minElement.value != "")
&& !(e.target && e.target === document.activeElement)) // do not produce an error yet if target is currently active
{
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) {
if (erroredElement === hourElement || erroredElement === minElement) {
erroredElement.errored = false;
JotForm.errored(erroredElement, 'Enter a valid time');
} else {
erroredElement.errored = false;
JotForm.errored(erroredElement, 'Enter a valid date');
}
dateElement.addClassName('form-line-error');
dateElement.addClassName('form-datetime-validation-error');
} else {
JotForm.corrected(monthElement);
JotForm.corrected(dayElement);
JotForm.corrected(yearElement);
if (hourElement && minElement) {
JotForm.corrected(hourElement);
JotForm.corrected(minElement);
}
dateElement.removeClassName('form-line-error');
dateElement.removeClassName('form-datetime-validation-error');
}
};
//fired when date is changed by calendar
dateElement.observe('date:changed', dateTimeCheck);
monthElement.observe('change', dateTimeCheck);
dayElement.observe('change', dateTimeCheck);
yearElement.observe('change', dateTimeCheck);
if (hourElement && minElement) {
hourElement.observe('change', dateTimeCheck);
minElement.observe('change', dateTimeCheck);
}
});
} catch(e) {
console.error(e);
}
},
handleTextareaLimits: function () {
$$('.form-textarea-limit-indicator span').each(function (el) {
var inpID = el.id.split('-')[0];
if (!$(inpID)) {
return;
} // cannot find the main element
var minimum = el.readAttribute('minimum');
var limit = el.readAttribute('limit');
var input = $(inpID);
var count;
var countText = function (firstRun) {
if (input.hasClassName('form-custom-hint')) {
el.update("0/" + (minimum > -1 ? minimum : limit));
return;
}
var contents;
if (input.hasClassName("form-textarea") && input.up('div').down('.nicEdit-main')) { //rich text
contents = input.value.stripTags().replace(/ /g, ' ');
} else {
contents = input.value;
}
// remove html tags and space chars, to prevent wrong counts on text copied from MS WORD
var cleaned_contents = contents.replace(/<.[^<>]*?>/g, ' ').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('typeMinimum') : el.readAttribute('type');
if (limitType == 'Words') {
count = $A(cleaned_contents.split(/\s+/)).without("").length;
} else if (limitType == 'Letters') {
count = cleaned_contents.length;
}
var limiting = false;
if (((type == "min" && count < minimum) || (type == "max" && count > limit)) && !(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.texts[lettersWords + minMax + "LimitError"] + " " + lim;
JotForm.errored(el.up('.form-line').down('textarea'), msg + '.');
limiting = true;
}
el.update(count + "/" + ((minimum && count < minimum && type == "min") || limit == -1 ? minimum : limit));
return limiting;
}
var runMax = true;
if (minimum && minimum > 0) {
runMax = !limitByType("min")
}
if (limit && limit > 0 && runMax) {
limitByType("max");
}
};
countText(true);
input.observe('change', countText);
input.observe('focus', countText);
input.observe('keyup', countText);
//check whether rich text
if (input.hasClassName("form-textarea") && input.up('div').down('.nicEdit-main')) {
var cEditable = input.up('div').down('.nicEdit-main');
cEditable.observe('keyup', function () {
input.value = cEditable.innerHTML;
countText();
});
}
});
},
/**
* Activates all autocomplete fields
*/
handleAutoCompletes: function () {
// Get all autocomplete fields
$H(JotForm.autoCompletes).each(function (pair) {
var el = $(pair.key); // Field itself
el.writeAttribute('autocomplete', 'off');
var parent = $(el.parentNode); // Parent of the field for list to be inserted
var values = $A(pair.value.split('|')); // Values for auto complete
var lastValue; // Last entered value
var selectCount = 0; // Index of the currently selected element
//parent.setStyle('position:relative;z-index:1000;'); // Set parent position to relative for inserting absolute positioned list
var liHeight = 0; // Height of the list element
// Create List element with must have styles initially
var list = new Element('div', {
className: 'form-autocomplete-list'
}).setStyle({
listStyle: 'none',
listStylePosition: 'outside',
position: 'absolute',
zIndex: '10000'
}).hide();
var render = function () {
var dims = el.getDimensions(); // Dimensions of the input box
var offs = el.cumulativeOffset();
list.setStyle({
top: ((dims.height + offs[1])) + 'px',
left: offs[0] + 'px',
width: ((dims.width < 1 ? 100 : dims.width) - 2) + 'px'
});
list.show();
};
// Insert list onto page
// parent.insert(list);
$(document.body).insert(list);
list.close = function () {
list.update();
list.hide();
selectCount = 0;
};
// Hide list when field get blurred
el.observe('blur', function () {
list.close();
});
// Search entry in values when user presses a key
el.observe('keyup', function (e) {
var word = el.value;
// If entered value is the same as the old one do nothing
if (lastValue == word) {
return;
}
lastValue = word; // Set last entered word
list.update(); // Clean up the list first
if (!word) {
list.close();
return;
} // If input is empty then close the list and do nothing
// Get matches
var fuzzy = el.readAttribute('data-fuzzySearch') == 'Yes';
var matches;
if (fuzzy) {
matches = values.collect(function (v) {
if (v.toLowerCase().include(word.toLowerCase())) {
return v;
}
}).compact();
} else {
matches = values.collect(function (v) {
if (v.toLowerCase().indexOf(word.toLowerCase()) == 0) {
return v;
}
}).compact();
}
// If matches found
var maxMatches = el.readAttribute('data-maxMatches');
if (maxMatches > 0) matches = matches.slice(0, maxMatches);
if (matches.length > 0) {
matches.each(function (match) {
var li = new Element('li', {
className: 'form-autocomplete-list-item'
});
var val = match;
li.val = val;
try {
val = match.replace(new RegExp('(' + word + ')', 'gim'), '<b>$1</b>');
}
catch (e) {
JotForm.error(e);
}
li.insert(val);
li.onmousedown = function () {
el.value = match;
list.close();
};
list.insert(li);
});
render();
// Get li height by adding margins and paddings for calculating 10 item long list height
liHeight = liHeight || $(list.firstChild).getHeight() + (parseInt($(list.firstChild).getStyle('padding'), 10) || 0) + (parseInt($(list.firstChild).getStyle('margin'), 10) || 0);
// limit list to show only 10 item at once
list.setStyle({
height: (liHeight * ((matches.length > 9) ? 10 : matches.length) + 4) + 'px',
overflow: 'auto'
});
} else {
list.close(); // If no match found clean the list and close
}
});
// handle navigation through the list
el.observe('keydown', function (e) {
//e = document.getEvent(e);
var selected; // Currently selected item
// If the list is not visible or list empty then don't run any key actions
if (!list.visible() || !list.firstChild) {
return;
}
// Get the selected item
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: // 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) { // selected element is at the top of the list
if (selected && selected.previousSibling) {
$(selected.previousSibling).scrollIntoView(true);
selectCount = 0; // scroll element into view then reset the number
} else {
$(list.lastChild).scrollIntoView(false);
selectCount = 10; // reverse the list
}
} else {
selectCount--;
}
break;
case Event.KEY_DOWN: // 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 element is at the bottom of the list
if (selected && selected.nextSibling) {
$(selected.nextSibling).scrollIntoView(false);
selectCount = 10; // scroll element into view then reset the number
} else {
$(list.firstChild).scrollIntoView(true);
selectCount = 0; // reverse the list
}
} else {
selectCount++;
}
break;
case Event.KEY_ESC:
list.close(); // Close list when pressed esc
break;
case Event.KEY_TAB:
case Event.KEY_RETURN:
if (selected) { // put selected field into the input bıx
el.value = selected.val;
lastValue = el.value;
}
list.close();
if (e.keyCode == Event.KEY_RETURN) {
e.stop();
} // Prevent return key to submit the form
break;
default:
return;
}
});
});
},
/**
* Returns the extension of a file
* @param {Object} filename
*/
getFileExtension: function (filename) {
return (/[.]/.exec(filename)) ? (/[^.]+$/.exec(filename))[0] : undefined;
},
/**
* Fill fields from the get values prepopulate
*/
prePopulations: function () {
{ // Event simulator
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();
}
}
}
$H(document.get).each(function (pair) {
var stricterMatch = pair.key.length < 3 ? true : false; //this will prevent "a=fill" matching any name that starts with an a
var n = stricterMatch ? '[name$="_' + pair.key + '"]' : '[name*="_' + pair.key + '"]';
var strict = '[name$="_' + pair.key + '"]';
var input;
input = $$('.form-star-rating' + n)[0];
if (input) {
input.setRating(parseInt(pair.value));
return;
}
input = $$('.form-slider' + n)[0]; //Add classname in builder?
if (input) {
input.setSliderValue(parseInt(pair.value));
return;
}
if (pair.key == "coupon-input" && $('coupon-input')) {
$('coupon-input').setValue(pair.value);
$('coupon-button').triggerEvent('click');
return;
}
input = $$('.form-textbox%s, .form-dropdown%s, .form-textarea%s, .form-hidden%s'.replace(/\%s/gim, strict))[0];
if (!input) {
input = $$('.form-textbox%s, .form-dropdown%s, .form-textarea%s, .form-hidden%s'.replace(/\%s/gim, n))[0];
}
if (!input && pair.key.indexOf("[") > 0) {
var name = pair.key.substr(0, pair.key.lastIndexOf('['));
if (name.length > 0 && $$("select[name*=" + name + "], input[name*=" + name + "]").length > 0) {
var index = pair.key.substr(pair.key.lastIndexOf('[') + 1).replace("]", "");
if ($$("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":
$$("select[name*=" + name + "]")[index].value = pair.value.replace(/\+/g, ' ');
break;
case "text":
case "tel":
case "number":
$$("input[name*=" + name + "]")[index].value = pair.value.replace(/\+/g, ' ');
break;
case "radio":
case "checkbox":
if ((pair.value == "true" || pair.value == 1) && $$("input[name*=" + name + "]")[index]) {
$$("input[name*=" + name + "]")[index].click();
}
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 < grades.length; i++) {
if ($(stub + i)) $(stub + i).value = grades[i];
}
} else if (input && (input.hasClassName('form-checkbox-other-input') || input.hasClassName('form-radio-other-input'))) {
if (n.indexOf('[other]') > -1) {
input.value = pair.value.replace(/\+/g, ' ');
JotForm.defaultValues[input.id] = input.value;
}
} else if (input && input.hasClassName("form-textarea") && input.up('div').down('.nicEdit-main')) {
input.up('div').down('.nicEdit-main').update(pair.value.replace(/\+/g, ' '));
} else if (input && input.hasClassName("form-dropdown") && input.readAttribute("multiple")) {
var val = pair.value.replace(/\+/g, ' ');
var arr = val.split(",");
var options = input.select('option');
$A(options).each(function(option) {
if(arr.include(option.value)) {
option.selected = true;
}
});
} else if (input) {
input.value = pair.value.replace(/\+/g, ' ');
JotForm.defaultValues[input.id] = input.value;
}
try {
var formLine = input ? input.up('.form-line') : false;
if (formLine && formLine.readAttribute('data-type') == "control_datetime" && formLine.down('input[id*="lite_mode_"]')) {
if (formLine.down('input[id*="year_"]').value != "" && formLine.down('input[id*="month_"]').value != "" && formLine.down('input[id*="day_"]').value != "") {
JotForm.formatDate({
date: new Date(formLine.down('input[id*="year_"]').value, formLine.down('input[id*="month_"]').value - 1, formLine.down('input[id*="day_"]').value),
dateField: formLine
});
}
}
} catch (e) {
console.log(e);
}
$$('.form-textbox%s, .form-textarea%s, .form-hidden%s'.replace(/\%s/gim, n)).each(function (input) {
//simulate 'keyup' event to execute conditions upon prepopulation
input.triggerEvent('keyup');
});
$$('.form-dropdown%s'.replace(/\%s/gim, n)).each(function (input) {
//simulate 'change' event to execute conditions upon prepopulation
input.triggerEvent('change');
});
$$('.form-checkbox%s, .form-radio%s'.replace(/\%s/gim, n)).each(function (input) {
//input.checked = $A(pair.value.split(',')).include(input.value);
//Emre: when checkboxed is checked, total count does not increase on payment forms (79814)
var disabled = input.disabled ? !!(input.enable()) : false;
if ($A(pair.value.split(',')).include(input.value)) {
if(!input.checked) {
if(disabled) {
setTimeout(function() { input.click()});
} else {
input.click();
}
}
} else if ($A(pair.value.split(',')).include('other')) {
if ((input.name.indexOf('[other]') > -1) || (input.id && input.id.indexOf('other_') > -1)) {
input.click(); //select other option
}
}
if(disabled) setTimeout(function() { input.disable(); });
});
//if textarea is hinted and has content remove the hint class
if (input && input.hasClassName('form-textarea') && input.hasClassName('form-custom-hint') && input.hasContent) {
input.removeClassName('form-custom-hint');
}
});
},
/**
* Reset form while keeping the values of hidden fields
* @param {Object} frm
*/
resetForm: function (frm) {
var hiddens = $(frm).select('input[type="hidden"]');
hiddens.each(function (h) {
h.__defaultValue = h.value;
});
$(frm).reset();
hiddens.each(function (h) {
h.value = h.__defaultValue;
});
return frm;
},
/**
* Bring the form data for edit mode
*
* dynamically load editMode function from form.edit.mode.js
* it will add a function named editModeFunction to global scope
*/
editMode: function (data, noreset, skipField) {
var preLink = "";
if (!JotForm.debug) {
if (this.url.search("https") == -1) {
preLink = "http://cdn.jotfor.ms/";
} else {
preLink = "https://cdn.jotfor.ms/";
}
}
if (!window.editModeFunction) {
var self = this;
this.loadScript('/js/form.edit.mode.js?v_' + (new Date()).getTime(), function () {
//editModeFunction is function name defined in form.edit.mode.js
self.editMode = editModeFunction;
self.editMode(data, noreset, skipField);
});
} else {
self.editMode(data, noreset, skipField);
}
},
/**
* Helper function that will tell if form is in edit mode
*/
isEditMode: function () {
return (typeof window.editModeFunction !== 'undefined');
},
/**
* add the given condition to conditions array to be used in the form
* @param {Object} qid id of the field
* @param {Object} condition condition array
*/
setConditions: function (conditions) {
conditions.reverse();
JotForm.conditions = conditions;
// Ozan, IMPORTANT NOTE: To enable chainig multiple field/email actions to a single/multiple conditions,
// any "condition.action" is expected to be an array, regardless of "condition.type". Since old conditions
// are stored in the database with a single action, "condition.action" is converted to an array, concatting
// the only action which condition has.
conditions.each(function (condition) {
condition.action = [].concat(condition.action);
});
},
setCalculations: function (calculations) {
JotForm.calculations = calculations;
},
runConditionForId: function (id) {
$H(JotForm.fieldConditions).each(function (pair) {
var conds = pair.value.conditions;
$A(conds).each(function (cond) {
$A(cond.terms).each(function (term) {
if (term.field === id) {
JotForm.checkCondition(cond);
}
});
});
});
},
otherConditionTrue: function (field, visibility) {
visibility = visibility.replace(/multiple/, "");
var otherConditionTrue = false;
$H(JotForm.fieldConditions).each(function (pair) {
var conds = pair.value.conditions;
$A(conds).each(function (cond) {
$A(cond.action).each(function (action) {
if (action.fields) {
action.fields.each(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;
},
/**
* Shows a field
* @param {Object} field
*/
showField: function (field, multiple) {
if (JotForm.otherConditionTrue(field, 'hide')) return;
var element = null;
var idField = $('id_' + field);
var cidField = $('cid_' + field);
var sectionField = $('section_' + field);
if (sectionField && cidField) { // Form collapse
element = sectionField;
} else if (cidField && !idField) { // Heading
element = cidField;
} else { // Regular field
element = idField;
}
//If no form element is found check for hidden single product field
if (!element) {
var productField = $$('input[name*="q' + field + '"][type="hidden"]');
if (productField.length > 0) {
productField[0].setAttribute('selected', true);
}
return element;
}
element.removeClassName('form-field-hidden');
element.removeClassName('always-hidden');
if(!element.hasClassName("form-section") && element.down(".always-hidden")) {
element.down(".always-hidden").removeClassName('always-hidden');
}
// kemal:bug::#145986 Form collapse bug
if (sectionField) {
if (element.hasClassName('form-section-closed')) { //if a closed form-section
//check for .form-collapse-table has class form-collapse-hidden
if (element.select('.form-collapse-table')[0].hasClassName('form-collapse-hidden')) {
//element is hidden remove class add class
element.removeClassName('form-section-closed');
element.addClassName('form-section');
element.setStyle({
height: "auto",
overflow: "hidden"
});
} else {
//element is visible do not add auto height
element.setStyle({
overflow: "hidden"
});
}
} else {
//case for status = closed
element.setStyle({
height: "auto",
overflow: "hidden"
});
}
}
if (JotForm.getInputType(field) === 'html' && $('text_' + field).innerHTML.match(/google.*maps/gi)) { //google maps hack to get the iframe to redisplay in the right place
$('text_' + field).innerHTML = $('text_' + field).innerHTML;
}
var elemShown = element.show();
if (JotForm.getInputType(field) === 'widget') {
JotForm.showWidget(field);
}
// kenneth: form callapse + condition + widgets bug when collapse opened by default
if (JotForm.getInputType(field) === 'collapse') {
// do something under collapse bar if shown opened by default
if (sectionField && !element.hasClassName('form-section-closed')) {
element.select('li.form-line').each(function (node, i) {
var id = node.id.split('_')[1];
// show widget fields
if (JotForm.getInputType(id) === 'widget') {
JotForm.showWidget(id);
}
});
}
}
return elemShown;
},
showWidget: function (id) {
var referrer = document.getElementById("customFieldFrame_" + id) ? document.getElementById("customFieldFrame_" + id).src : false;
if (referrer) {
var frame = (navigator.userAgent.indexOf("Firefox") != -1) ? getIframeWindow(window.frames["customFieldFrame_" + id]) : window.frames["customFieldFrame_" + id];
if (frame) {
XD.postMessage(JSON.stringify({type: "show", qid: id}), referrer, frame);
// send ready message event at the same time for widgets
// that doesn't work with show
if (typeof window.JCFServerCommon !== 'undefined') {
// only send ready if the section of the frame is current visible
if (JotForm.isVisible(JotForm.getSection($("id_" + id))) && JotForm.isVisible($("id_" + id))) {
// verify existence of widget frame
if (window.JCFServerCommon.frames.hasOwnProperty(id)) {
window.JCFServerCommon.frames[id].sendReadyMessage(id);
}
}
}
}
}
},
/**
* Hides a field
* @param {Object} field
*/
hideField: function (field, multiple, dontClear) {
if (JotForm.otherConditionTrue(field, 'show')) return;
var idPrefix = 'id_';
// For headings
if ($('cid_' + field) && !$('id_' + field)) {
idPrefix = 'cid_';
}
// For form collapses
if ($('cid_' + field) && $('section_' + field)) {
idPrefix = 'section_';
}
var element = $(idPrefix + field);
if (element) {
element.addClassName('form-field-hidden');
if (JotForm.clearFieldOnHide == "enable" && !dontClear) {
try {
JotForm.clearField(field);
} catch (e) {
console.log(e);
}
}
return element.hide();
}
//If no form element is found check for hidden single product field
var productField = $$('input[name*="q' + field + '"][type="hidden"]');
if (productField.length > 0) {
productField[0].setAttribute('selected', false);
}
},
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 (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"]').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(input.id in JotForm.defaultValues) {
input.checked = true;
} else {
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) {
var eventType;
if(firstField.nodeName.toLowerCase() === 'input') {
if(firstField.type === "checkbox" || firstField.type === "radio") {
firstField.up().triggerEvent('click');
} else {
firstField.triggerEvent('keyup');
}
} else {
firstField.triggerEvent('change');
}
}
} else if (["address", "combined", "datetime", "time"].include(type)) {
$('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("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 == "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") {
$("id_" + field).select('input[type="radio"], input[type="checkbox"]').each(function (input) {
if(input.id in JotForm.defaultValues) {
input.checked = true;
} else {
input.checked = false;
}
});
if ($('id_' + field).triggerEvent && !dontTrigger) $('id_' + field).triggerEvent('click');
} else if (type == "select") {
if ($('input_' + field)) {
$('input_' + field).value = defaultValue;
if ($('input_' + field).triggerEvent && !dontTrigger) $('input_' + field).triggerEvent('change');
} else { //select matrices
$("id_" + field).select('select').each(function (element) {
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(); //ie8&9
}
if ($('input_' + field).readAttribute("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);
}
}
}
},
/**
* Checks the fieldValue by given operator string
* @param {Object} operator
* @param {Object} condValue
* @param {Object} fieldValue
*/
checkValueByOperator: function (operator, condValueOrg, fieldValueOrg) {
try {
if (typeof condValueOrg == "string" && condValueOrg.indexOf("{") > -1 && condValueOrg.indexOf("}") > -1) { //contains other field reference
condValueOrg = condValueOrg.replace(/\{.*?\}/gi, function (match, contents, offset, s) {
var stripped = match.replace(/[\{\}]/g, "");
var elements = $$('input[name$="_' + stripped + '"]');
if (elements.length > 0) {
var element = elements.first();
if (element && element.value) {
return element.value;
}
}
return match;
});
}
} catch (e) {
console.log(e);
}
var fieldValue = Object.isBoolean(fieldValueOrg) ? fieldValueOrg : fieldValueOrg.toString().strip().toLowerCase();
var condValue = Object.isBoolean(condValueOrg) ? condValueOrg : condValueOrg.toString().strip().toLowerCase();
switch (operator) {
case "equals":
case "quantityEquals":
case "equalDate":
return fieldValue == condValue;
case "equalDay":
return JotForm.getDayOfWeek(fieldValue) == condValue;
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.split(",");
return $A(condValues).any(function (cv) {
return fieldValue.include(cv.trim());
});
case "notContains":
condValues = condValue.split(",");
return !$A(condValues).any(function (cv) {
return fieldValue.include(cv.trim());
});
case "greaterThan":
case "quantityGreater":
return (parseFloat(fieldValue, 10) || 0) > (parseFloat(condValue, 10) || 0);
case "lessThan":
case "quantityLess":
//Emre: if Scale Rating doesn't have value it returns "true" so we need to check wheater its length is greater than 0 (52809)
//fieldValue is string, not number
if (fieldValue.length) {
return (parseFloat(fieldValue, 10) || 0) < (parseFloat(condValue, 10) || 0);
} else {
return false;
}
case "isEmpty":
if (Object.isBoolean(fieldValue)) {
return !fieldValue;
}
return fieldValue.empty();
case "isFilled":
if (Object.isBoolean(fieldValue)) {
return fieldValue;
}
return !fieldValue.empty();
case "before":
return fieldValueOrg < condValueOrg;
case "after":
return fieldValueOrg > condValueOrg;
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: {}, // Cahcke the check type results for performance
/**
*
* @param {Object} id
*/
getInputType: function (id) {
if (JotForm.typeCache[id]) {
return JotForm.typeCache[id];
}
var type = false;
if ($('id_' + id) && $('id_' + id).readAttribute('data-type') == "control_text") {
type = 'html';
} 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("form-checkbox-other-input")) {
type = "checkbox";
}
// Neil: set type for autocomplete fields
if ($('input_' + id).hasClassName('form-autocomplete')) {
type = "autocomplete";
}
if ($('input_' + id).hasClassName('form-slider')) {
type = 'slider';
}
if ($('input_' + id).hasClassName('form-widget')) {
type = 'widget';
}
} else if ($('input_' + id + '_pick') || ($('id_' + id) && $('id_' + id).readAttribute('data-type') == "control_datetime")) {
type = 'datetime';
} 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 + ' .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 + ' .pad').length > 0) {
type = 'signature';
} else {
if ($$('#id_' + id + ' input')[0]) {
type = $$('#id_' + id + ' input')[0].readAttribute('type').toLowerCase();
if (type == "text" || type == 'tel' || type === 'number') {
type = "combined";
}
} else if ($$('#id_' + id + ' select')[0]) {
type = "select"; //select matrices
}
}
JotForm.typeCache[id] = type;
return type;
},
/**
* Parses ISO Date string to a real date
* @param {Object} str
*/
strToDate: function (str) {
// When cannot parse return an invalid date
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(!str.include("T")){ str += "T00:00"; }
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 = $('input_' + id + '_day').getValue() || "%empty%";
var month = $('input_' + id + '_month').selectedIndex || "%empty%";
month = String(month);
var year = $('input_' + id + '_year').getValue() || "%empty%";
var date = year + "-" + (month.length == 1 ? '0' + month : month) + "-" + (day.length == 1 ? '0' + day : day);
if (date.include("%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) {
var date = "";
if ($('year_' + id)) {
date += ($('year_' + id).value || "%empty%");
}
if ($('month_' + id)) {
var mm = $('month_' + id).value ? ($('month_' + id).value.length > 1 ? $('month_' + id).value : "0" + $('month_' + id).value) : "%empty%";
date += "-" + mm;
}
if ($('day_' + id)) {
var dd = $('day_' + id).value ? ($('day_' + id).value.length > 1 ? $('day_' + id).value : "0" + $('day_' + id).value) : "%empty%";
date += "-" + dd;
}
if (date.include("%empty%")) {
JotForm.info("Wrong date: " + date);
return "";
}
var h = "";
if ($('ampm_' + id)) {
if ($('hour_' + id)) {
h = $('hour_' + id).value;
if ($('ampm_' + id).value == 'pm') {
h = parseInt(h, 10) + 12;
}
if (h == "24") {
h = 0;
}
date += "T" + ((h.length == 1 ? "0" + h : h) || "00");
}
} else {
if ($('hour_' + id)) {
h = $('hour_' + id).value;
date += "T" + ((h.length == 1 ? "0" + h : h) || "00");
}
}
if ($('min_' + id)) {
date += ":" + ($('min_' + id).value || "00");
}
if (h === "") {
date += "T00:00";
}
return date;
},
/**
*
* @param {Object} condition
*/
checkCondition: function (condition) {
var any = false, all = true;
var filled;
$A(condition.terms).each(function (term) {
var value;
try {
var fieldType = JotForm.getInputType(term.field);
switch (fieldType) {
case "combined":
if (['isEmpty', 'isFilled'].include(term.operator)) {
filled = $$('#id_' + term.field + ' input').collect(function (e) {
return e.value;
}).any();
if (JotForm.checkValueByOperator(term.operator, term.value, filled)) {
any = true;
} else {
all = false;
}
return;
/* continue; */
} else {
//for matrices
value = $$('#id_' + term.field + ' input').collect(function (e) {
return 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').collect(function (e) {
return e.value;
}).any();
if (JotForm.checkValueByOperator(term.operator, term.value, filled)) {
any = true;
} else {
all = false;
}
} else {
var option;
$('input_' + term.field + '_country').select("option").each(function(opt) {
if(term.value === opt.value) {
option = opt;
throw $break;
}
});
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;
}
}
}
break;
case "birthdate":
case "datetime":
value = (fieldType == "datetime") ? JotForm.getDateValue(term.field) : JotForm.getBirthDate(term.field);
if (value === undefined) {
return;
/* continue; */
}
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;
}
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 (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;
/* continue; */
}
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') : "";
$$('#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();
if (JotForm.checkValueByOperator(term.operator, termValue, value)) {
any = true;
} else {
// If not equals item is found condition should fail
if (term.operator == 'notEquals' && termValue == value) {
any = false;
all = false;
throw $break;
}
if (input.value == termValue || (input.hasClassName('form-' + fieldType + '-other') && termValue == '-- '+otherValue+' --')) {
all = false;
}
}
});
break;
case "select":
if (term.value) term.value = term.value.replace(/&/g, '&');
if ($('input_' + term.field) && $('input_' + term.field).multiple) {
if (term.operator == 'equals') {
var option = $('input_' + term.field).select('option[value=' + term.value + ']');
if (option.length > 0 && option[0].selected) {
any = true;
} else {
all = false;
}
} else if (term.operator == 'notEquals') {
var option = $('input_' + term.field).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 = $('input_' + term.field).options;
for (var i = 0; i < arr.length; i++) {
if (!arr[i].value.empty() && arr[i].selected == true) {
selected = true;
}
}
if (term.operator == 'isEmpty') {
if (!selected) any = true;
else all = false;
}
if (term.operator == 'isFilled') {
if (selected) any = true;
else all = false;
}
}
} else if ($('input_' + term.field)) {
value = $('input_' + term.field).value;
if (value === undefined) {
return;
/* continue; */
}
if (JotForm.checkValueByOperator(term.operator, term.value, value)) {
any = true;
} else {
all = false;
}
} else {
filled = $$('#id_' + term.field + ' select').collect(function (e) {
return e.value;
}).any();
if (JotForm.checkValueByOperator(term.operator, term.value, filled)) {
any = true;
} else {
all = false;
}
}
break;
case "grading":
if (['isEmpty', 'isFilled'].include(term.operator)) {
filled = $$('input[id^=input_' + term.field + '_]').collect(function (e) {
return e.value;
}).any();
if (JotForm.checkValueByOperator(term.operator, term.value, filled)) {
any = true;
} else {
all = false;
}
} else {
value = $('grade_point_' + term.field).innerHTML.stripTags();
if (JotForm.checkValueByOperator(term.operator, term.value, value)) {
any = true;
} else {
all = false;
}
}
break;
case "file":
if ($('id_' + term.field).select('.qq-uploader').length > 0) {
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;
/* continue; */
}
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;
/* continue; */
}
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;
if (value === undefined) {
return;
}
if (value.indexOf("widget_metadata") > -1) { //object not simple
try {
value = JSON.parse(value).widget_metadata.value;
var matchingItem = false;
for (var i = 0; i < value.length; i++) {
var obj = value[i];
for (var item in obj) {
if (JotForm.checkValueByOperator(term.operator, term.value, obj[item], term.field)) {
any = true;
matchingItem = true;
}
}
}
if (!matchingItem) all = false;
} catch (e) {
console.log(e);
}
} else {
if (JotForm.checkValueByOperator(term.operator, term.value, value, term.field)) {
any = true;
} else {
all = false;
}
}
break;
case "hidden":
if($('input_' + term.field + "_donation")) {
value = $('input_' + term.field + "_donation").value;
} else {
value = $('input_' + term.field).value;
}
if (JotForm.checkValueByOperator(term.operator, term.value, value, term.field)) {
any = true;
} else {
all = false;
}
break;
default:
if(!$('input_' + term.field)) {
return;
}
value = $('input_' + term.field).value;
if ($('input_' + term.field).hinted) {
value = "";
}
if (value === undefined) {
return;
/* continue; */
}
if (JotForm.checkValueByOperator(term.operator, term.value, value, term.field)) {
any = true;
} else {
all = false;
}
}
} catch (e) {
JotForm.error(e);
}
});
if (condition.type == 'field') { // Field Condition
// JotForm.log("any: %s, all: %s, link: %s", any, all, condition.link.toLowerCase());
var isConditionValid = (condition.link.toLowerCase() == 'any' && any) || (condition.link.toLowerCase() == 'all' && all);
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) {
action.fields.each(function (field) {
JotForm.showField(field, true);
});
} else if (action.visibility.toLowerCase() == 'hidemultiple' && action.fields) {
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);
} else if (action.visibility.toLowerCase() == 'showmultiple' && action.fields) {
action.fields.each(function (field) {
JotForm.hideField(field, true, matchingTermAction);
});
} else if (action.visibility.toLowerCase() == 'hidemultiple' && action.fields) {
action.fields.each(function (field) {
JotForm.showField(field, true);
});
}
}
JotForm.iframeHeightCaller();
if ($('section_' + action.field)) {
JotForm.runAllCalculations(true);
}
if ($('input_' + action.field) && $('input_' + action.field).triggerEvent) {
if (!matchingTermAction) { //rule matches action so don't rerun to avoid infinite loop
$('input_' + action.field).triggerEvent('keyup'); //trigger calculations when hiding/showing
}
}
});
} 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 (!isConditionValid && JotForm.otherConditionTrue(action.field, action.visibility.toLowerCase())) {
return;
}
if (action.visibility.toLowerCase() == 'require') {
JotForm.requireField(action.field, isConditionValid);
} else if (action.visibility.toLowerCase() == 'unrequire') {
JotForm.requireField(action.field, !isConditionValid);
} else if (action.visibility.toLowerCase() == 'requiremultiple' && action.fields) {
action.fields.each(function (field) {
JotForm.requireField(field, isConditionValid);
});
} 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 (condition.type == 'mask') {
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);
$("input_" + action.field).writeAttribute('masked', "true");
} else {
condition.conditionTrue = false;
//if no other mask conditions for this field are true remove the mask
var removeMask = true;
$A(JotForm.conditions).each(function (cond) {
if (cond.disabled == true) return; //go to next condition
if (cond.type !== 'mask') return;
if (!cond.conditionTrue) return;
$A(cond.action).each(function (act) {
if (act.field == action.field) {
removeMask = false; //there is a different true mask cond on this field so do not remove mask
}
});
});
if (removeMask) {
JotForm.setQuestionMasking("#input_" + action.field, "", "", true);
$("input_" + action.field).writeAttribute('masked', "false");
}
}
});
} else if (condition.type == 'calculation') {
if (!$("id_" + condition.action[0].resultField)) {
return;
}
var calcs = JotForm.calculations;
var cond = null;
for (var i = 0; i < calcs.length; i++) {
if (calcs[i].conditionId === condition.id) {
calc = calcs[i];
}
}
if ((condition.link.toLowerCase() == 'any' && any) || (condition.link.toLowerCase() == 'all' && all)) {
calc.conditionTrue = true;
if(JotForm.ignoreInsertionCondition) return;
JotForm.checkCalculation(calc);
} else {
calc.conditionTrue = false;
if(JotForm.ignoreInsertionCondition) return;
//check if any other conditions are true for this result field
setTimeout(function (calc) {
var matchForThisResult = {};
var subfield;
for (var i = 0; i < calcs.length; i++) {
if ((condition.action[0].resultField == calcs[i].resultField && calcs[i].hasOwnProperty('conditionTrue') && calcs[i].conditionTrue)
&& !(JotForm.getInputType(condition.action[0].resultField) === "html" && condition.action[0].replaceText !== calcs[i].replaceText)) {
subfield = calcs[i].resultSubField || "";
matchForThisResult[calcs[i].resultField+subfield] = true;
}
}
subfield = "resultSubField" in condition.action[0] ? condition.action[0].resultSubField : "";
if (!matchForThisResult[condition.action[0].resultField+subfield]) {
try {
var dontTrigger = condition.terms.map(function (term) {
return term.field === condition.action[0].resultField;
}).any();
if(!dontTrigger) {
dontTrigger = condition.action[0].operands && condition.action[0].operands.split(',').include(condition.action[0].resultField);
}
JotForm.clearField(condition.action[0].resultField, subfield, dontTrigger);
} catch (e) {
console.log(e);
}
}
}, 50, calc);
}
} else { // Page condition
JotForm.log("any: %s, all: %s, link: %s", any, all, condition.link.toLowerCase());
if (JotForm.nextPage) {
return;
}
if ((condition.link.toLowerCase() == 'any' && any) || (condition.link.toLowerCase() == 'all' && all)) {
var action = condition.action[0];
JotForm.info('Correct: Skip To: ' + action.skipTo);
var sections = $$('.page-section');
if (action.skipTo == 'end') {
JotForm.nextPage = sections[sections.length - 1];
} else {
JotForm.nextPage = sections[parseInt(action.skipTo.replace('page-', ''), 10) - 1];
}
} else {
JotForm.info('Fail: Skip To: page-' + JotForm.currentPage + 1);
JotForm.nextPage = false;
}
}
JotForm.enableDisableButtonsInMultiForms();
},
currentPage: false,
nextPage: false,
previousPage: false,
fieldConditions: {},
setFieldConditions: function (field, event, condition) {
if (!JotForm.fieldConditions[field]) {
JotForm.fieldConditions[field] = {
event: event,
conditions: []
};
}
JotForm.fieldConditions[field].conditions.push(condition);
},
widgetsAsCalculationOperands: [],
/*
* Require or Unrequire a field
*/
requireField: function (qid, req) {
if (!$('id_' + qid)) return;
$$('#id_' + qid + ' input, #id_' + qid + ' textarea, #id_' + qid + ' select').each(function (el) {
//do not required non-necessary parts of combined field
if (el.id === 'coupon-input'
|| (el.type === 'hidden' && !el.up('.form-star-rating') && !el.hasClassName('form-widget'))
|| el.hasClassName('form-checkbox-other-input') || el.hasClassName('form-radio-other-input')
|| $A(['prefix', 'middle', 'suffix', 'addr_line2', 'state']).any(function (name) {
return el.name.indexOf("[" + name + "]") > -1;
})) {
return;
}
//get all validations
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('.jf-required')) {
el.up('.jf-required').className = el.up('.jf-required').className.replace(/validate\[required\]/gi, '');
if (req) {
el.up('.jf-required').addClassName("validate[required]");
} else {
el.up('.jf-required').removeClassName("form-validation-error");
}
}
//remove all validation from class
el.className = el.className.replace(/validate\[.*\]/, '');
//remove required from validations array
for (var i = validations.length - 1; i >= 0; i--) {
if (validations[i] === 'required') {
validations.splice(i, 1);
}
}
if (req) {
validations.push('required'); //add required to validations
if (el.hasClassName('form-widget')) {
el.addClassName('widget-required');
}
} else {
el.removeClassName('form-validation-error');
el.removeClassName('widget-required');
}
//add validations back to class
if (validations.length > 0) {
el.addClassName('validate[' + validations.join(',') + ']');
}
JotForm.setFieldValidation(el);
});
if (req) {
if ($('label_' + qid) && !$('label_' + qid).down('.form-required')) {
$('label_' + qid).insert('<span class="form-required">*</span>');
}
} else {
if ($('label_' + qid) && $('label_' + qid).down('.form-required')) {
$('label_' + qid).down('.form-required').remove();
}
//remove any existing errors
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) {
if (!$('id_' + qid)) return;
try {
$('id_' + qid).select("input, textarea, select, button").each(function(input) {
if(enable) {
input.removeClassName("conditionallyDisabled");
input.enable();
} else {
input.addClassName("conditionallyDisabled");
input.disable();
}
});
} catch(e) {console.log(e);}
},
/**
* When widget value is updated check whether to trigger calculation
*/
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 () {
$A(JotForm.calculations).each(function (calc, index) {
if (calc.readOnly && $('input_' + calc.resultField) != null) {
$('input_' + calc.resultField).setAttribute('readOnly', 'true');
}
});
},
setCalculationEvents: function () {
var setCalculationListener = function (el, ev, calc) {
$(el).observe(ev, function () {
if (ev === "paste") { //same action as other events but wait for the text to be pasted
setTimeout(function () {
el.addClassName('calculatedOperand');
JotForm.checkCalculation(calc);
}, 10);
} else {
el.addClassName('calculatedOperand');
JotForm.checkCalculation(calc);
}
});
};
$A(JotForm.calculations).each(function (calc, index) {
if (!calc.operands) return;
var ops = calc.operands.split(',');
for (var i = 0; i < ops.length; i++) {
var opField = ops[i];
if (!opField || opField.empty() || !$('id_' + opField)) continue;
var type = JotForm.calculationType(opField),
ev;
switch (type) {
case "widget":
setCalculationListener($('id_' + opField), 'change', calc);
JotForm.widgetsAsCalculationOperands.push(opField);
break;
case 'radio':
case 'checkbox':
setCalculationListener($('id_' + opField), 'click', 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);
$$("#id_" + opField + ' select').each(function (el) {
setCalculationListener($(el), 'change', calc);
});
break;
case 'time':
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);
break;
}
}
});
},
runAllCalculations: function (ignoreEditable) {
$A(JotForm.calculations).each(function (calc, index) {
if (!(ignoreEditable && !calc.readOnly) && !!calc.equation) {
JotForm.checkCalculation(calc);
}
});
},
calculationType: function (id) {
var paymentTypes = ['control_stripe', 'control_paymill', 'control_payment', 'control_paypal', 'control_paypalexpress', 'control_paypalpro', 'control_clickbank', 'control_2co', 'control_googleco', 'control_worldpay', 'control_onebip', 'control_authnet', 'control_dwolla', 'control_braintree'];
if ($('id_' + id) && $('id_' + id).readAttribute('data-type') && paymentTypes.include($('id_' + id).readAttribute('data-type'))) {
return $('id_' + id).readAttribute('data-type').replace("control_", "");
} else if ($('id_' + id) && $('id_' + id).readAttribute('data-type') == 'control_matrix') {
return 'matrix';
} else {
return JotForm.getInputType(id);
}
},
checkCalculation: function (calc) {
if (calc.hasOwnProperty('conditionTrue') && !calc.conditionTrue) {
return '';
}
var result = calc.resultField;
var showBeforeInput = calc.showBeforeInput;
var ignoreHidden = calc.ignoreHiddenFields;
var useCommasForDecimals = calc.useCommasForDecimals;
if (!$('id_' + result)) return;
try {
if (!['text', 'email', 'textarea', 'calculation', 'combined', 'address', 'datetime', 'time', 'html', 'authnet', 'paypalpro', 'number', 'radio', 'checkbox', 'select', 'matrix', 'braintree', 'stripe'].include(JotForm.calculationType(result))) return;
} catch (e) {
console.log(e);
}
var combinedObject = {};
var getValue = function (data, numeric) {
var subField = "";
if (data.indexOf("_") > -1) { //matrix sub field
subField = data.substring(data.indexOf("_"));
data = data.substring(0, data.indexOf("_"));
}
if (!$('id_' + data)) return '';
if (!$('id_' + data).hasClassName('calculatedOperand') && showBeforeInput) return ''; //no input yet so ignore field
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 : '';
}
var type = JotForm.calculationType(data);
var val = '';
switch (type) {
case 'matrix':
if ($("id_" + data).down('.form-radio')) {
var rowNum = parseInt(subField.replace("_", "")) + 2;
var row = $("id_" + data).down("tr:nth-child(" + rowNum + ")");
row.select(".form-radio").each(function (radio) {
if (radio.checked) {
val = radio.readAttribute('calcValue') ? radio.readAttribute('calcValue') : radio.value;
}
});
} else {
if ($("input_" + data + subField)) {
if ($("input_" + data + subField).type == "checkbox") {
if ($("input_" + data + subField).checked) {
var chk = $("input_" + data + subField);
if (chk.readAttribute('calcValue')) {
val = chk.readAttribute('calcValue');
} else {
val = chk.value;
}
}
} else {
val = $("input_" + data + subField).value;
}
}
}
break;
case 'stripe':
case 'paymill':
case 'payment':
case 'paypal':
case 'paypalexpress':
case 'paypalpro':
case 'clickbank':
case '2co':
case 'googleco':
case 'worldpay':
case 'onebip':
case 'authnet':
case 'dwolla':
case 'braintree':
if ($("id_" + data).down('#payment_total')) {
val = $("id_" + data).down('#payment_total').innerHTML;
} else if ($('input_' + data + '_donation')) {
val = $('input_' + data + '_donation').value;
}
if(JotForm.currencyFormat && JotForm.currencyFormat.dSeparator === ",") {
val = val.replace(/\./g, "").replace(/\,/g, ".");
}
break;
case 'radio':
$$("#id_" + data + ' input[type="radio"]').each(function (rad, i) {
if (rad.checked) {
//grab calculation value
if (rad.readAttribute('calcValue')) {
val = rad.readAttribute('calcValue');
} else {
val = rad.value;
}
}
});
break;
case 'checkbox':
var valArr = [];
$$("#id_" + data + ' input[type="checkbox"]').each(function (chk, i) {
if (chk.checked) {
if (chk.readAttribute('calcValue')) {
valArr.push(chk.readAttribute('calcValue'));
} 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':
if ($('input_' + data).readAttribute('multiple') === 'multiple') {
if (numeric) val = 0;
$('input_' + data).select('option').each(function (option, ind) {
var option = $('input_' + data).options[ind];
if (option && option.selected) {
var current = option.readAttribute('calcValue') ? option.readAttribute('calcValue') : option.value;
if(numeric) {
val += (current === "") ? 0 : parseFloat(current.replace(/[^0-9.]/g, ""));
} else {
val += current;
}
}
});
} else {
var option = $('input_' + data).options[$('input_' + data).selectedIndex];
if (option) {
if (option.readAttribute('calcValue')) {
val = option.readAttribute('calcValue');
} else {
val = $('input_' + data).value;
}
}
}
break;
case 'number':
if ($$("#id_" + data + ' input[type="number"]').length > 1) { //ranges
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 '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);
} else {
$$("#id_" + data + ' input[type="tel"]').each(function (el) {
valArr.push(el.value);
var id = el.id.replace(/_.*/, "");
combinedObject[id] = el.value;
});
$$("#id_" + data + ' select').each(function (el) {
var id = el.id.replace(/_.*/, "");
combinedObject[id] = el.value;
});
}
$$("#id_" + data + ' select').each(function (el) {
valArr.push(el.value);
});
//if numeric calculation calculate the number of days in epoch
if (numeric) {
if(!valArr[0].empty() && !valArr[1].empty() && !valArr[2].empty()) {
var hours = mins = ampm = '';
if (valArr.length > 4 && !valArr[3].empty() && !valArr[4].empty()) {
hours = parseInt(valArr[3]);
//convert to 24hours
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 = Date.UTC(valArr[2], valArr[0] - 1, valArr[1], hours, mins);
val = millis / 60 / 60 / 24 / 1000;
} else {
val = 0;
}
} else {
if (valArr.length > 2 && !valArr[0].empty() && !valArr[1].empty() && !valArr[0].empty()) {
val = valArr[0] + '/' + valArr[1] + '/' + 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]; //ampm
}
}
break;
case 'time':
if (subField == "_duration") {
if ($("duration_" + data + "_ampmRange")) {
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;
}
}
break;
}
var valArr = [];
combinedObject = {};
if (numeric) {
$$("#id_" + data + ' select').each(function (el) {
valArr.push(el.value);
});
var hour, mins, 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 + ")";
}
}
$$("#id_" + data + ' select').each(function (el) {
var id = el.id.replace(/.*_.*_/, "");
combinedObject[id] = el.value;
});
}
break;
case 'birthdate':
var valArr = [];
if (numeric) {
try {
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
var months = monthNames.indexOf($("input_" + data + "_month").value);
var days = $("input_" + data + "_day").value;
var years = $("input_" + data + "_year").value;
var millis = new Date(years, months, days).getTime();
val = 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 = {};
$$("#id_" + data + ' input[type="text"]').each(function (el) {
if (!el.value.empty()) {
valArr.push(el.value);
}
var id = el.id.replace(/input_[0-9].*?_+/, "");
combinedObject[id] = el.value;
});
$$("#id_" + data + ' select').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 'file':
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" ? "<br/>" : "\n";
var json = $('input_' + data).value;
try {
json = JSON.parse(json);
for(var i=0; i<json.length; i++) {
var valArr = [];
for(line in json[i]) {
if(!json[i].hasOwnProperty(line)) continue;
if(!json[i][line].empty()) {
valArr.push(json[i][line]);
}
}
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, "<br/>");
}
break;
case "imagelinks":
case "links":
var br = JotForm.calculationType(result) === "html" ? "<br/>" : "\n";
var json = JSON.parse($('input_' + data).value).widget_metadata.value;
for(var i=0; i<json.length; i++) {
if(json[i].url.replace(/\s/g, "").empty()) continue;
var showName = json[i].name && !json[i].name.replace(/\s/g, "").empty();
if(JotForm.calculationType(result) === "html") {
if(widgetType === "imagelinks") {
val += '<a href="'+json[i].url+'"><img src="'+json[i].url+'" /></a>';
} else {
val += '<a href="'+json[i].url+'">'+(showName ? json[i].name : json[i].url)+'</a>';
}
} 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(/<br>/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;
default:
val = $('input_' + data).value;
break;
}
break;
default:
if ($('input_' + data) && typeof $('input_' + data).value !== 'undefined') {
val = $('input_' + data).value;
}
break;
}
if (numeric && typeof val !== 'number') {
if(useCommasForDecimals) {
if(/\..*\,/.test(val)) { //dot used as units separator before comma
val = val.replace(/\./g, "");
}
val = val.replace(",",".");
}
val = val.replace(/-?([^0-9])/g, "$1").replace(/[^0-9\.-]/g, "");
}
if (numeric && val < 0) { //ntw 343248 - this is to patch a weirdness in the parser whereby x+-y will not parse
val = '(' + val + ')';
}
if (numeric && val === '') {
val = 0;
}
return val;
};
var calculate = function (equation, numeric) {
var out = '';
var acceptableFunctions = {
"abs": Math.abs,
"acos": Math.acos,
"acosh": Math.acosh,
"asin": Math.asin,
"asinh": Math.asinh,
"atan": Math.atan,
"atanh": Math.atanh,
"atan2": Math.atan2,
"cbrt": Math.cbrt,
"ceil": Math.ceil,
"cos": Math.cos,
"cosh": Math.cosh,
"exp": Math.exp,
"expm1": Math.expm1,
"floor": Math.floor,
"fround": Math.fround,
"hypot": Math.hypot,
"imul": Math.imul,
"log": Math.log,
"log1p": Math.log1p,
"log10": Math.log10,
"log2": Math.log2,
"max": Math.max,
"min": Math.min,
"pow": Math.pow,
"random": Math.random,
"round": Math.round,
"sign": Math.sign,
"sin": Math.sin,
"sinh": Math.sinh,
"sqrt": Math.sqrt,
"tan": Math.tan,
"tanh": Math.tanh,
"toSource": Math.toSource,
"trunc": Math.trunc,
"E": Math.E,
"LN2": Math.LN2,
"LN10": Math.LN10,
"LOG2E": Math.LOG2E,
"LOG10E": Math.LOG10E,
"PI": Math.PI,
"SQRT1_2": Math.SQRT1_2,
"SQRT2": Math.SQRT2
};
for (var i = 0; i < equation.length; i++) {
character = equation.charAt(i);
if (character === '[' && !numeric) {
var end = equation.indexOf(']', i);
try {
var num = calculate(equation.substring(i + 1, end), true);
if (num) {
if (num.indexOf(",") == -1) { //normal calc string
num = new MathProcessor().parse(num);
if (JotForm.getInputType(calc.resultField) !== "datetime") {
num = num.toFixed(calc.decimalPlaces);
if (!calc.showEmptyDecimals) {
num = parseFloat(num);
}
}
if (!isFinite(num)) {
num = 0;
}
}
if(useCommasForDecimals) {
num = num.toString().replace(".", ",");
}
out += num;
}
} catch (e) {
console.log('exception in ' + calc.conditionId + " : " + num + "(" + equation + ")");
}
i = end;
} else if (equation.substr(i, 3) === '|*|') {
try {
i += 3;
var end = equation.indexOf('|*|', i);
if (end === -1) continue;
var specOp = equation.substring(i, end);
i += end + 2 - i;
if (equation.charAt(i + 1) === '(' || (equation.charAt(i + 1) === '[' && equation.charAt(i + 2) === '(')) {
i += (equation.charAt(i + 1) === '[') ? 3 : 2;
var endSpecial = -1;
var balance = 1;
for (var k = i; k < equation.length; k++) {
if (equation.charAt(k) === ')') {
balance--;
if (balance === 0) {
endSpecial = k;
break;
}
} else if (equation.charAt(k) === '(') {
balance++;
}
}
if (endSpecial === -1) continue;
var args = equation.substring(i, endSpecial);
args = args.split(',');
var originalArgs = args.slice(0);
for (var j = 0; j < args.length; j++) {
args[j] = calculate(args[j], true);
if (args[j]) {
args[j] = new MathProcessor().parse(args[j]);
}
}
i += endSpecial - i;
if (specOp === 'dateString') {
var millis = args[0] * 24 * 60 * 60 * 1000 + 30000;
var date = new Date(millis);
var getUTCStringDate = function(date) {
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var day = dayNames[date.getUTCDay()];
var month = monthNames[date.getUTCMonth()];
var dayOfMonth = JotForm.addZeros(date.getUTCDate(), 2);
var year = date.getUTCFullYear();
return day+" "+month+" "+dayOfMonth+" "+year;
};
out += getUTCStringDate(date);
if (equation.charAt(i) === ']') {
i++;
} else {
equation = equation.substr(0, i + 1) + '[' + equation.substr(i + 1);
}
} else if (specOp === 'date') {
if (args.length > 2) {
var millis = new Date(args[0], args[1] - 1, args[2]).getTime();
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 (parseInt(a) > parseInt(b)) return 1;
if (parseInt(b) > parseInt(a)) return -1;
return 0;
});
args = args.reverse();
out += args[parseInt(n) - 1];
} else if (specOp === 'avg' || specOp === 'avgNoZero') {
var len = sum = 0;
for (var j = 0; j < args.length; j++) {
if (parseFloat(args[j]) > 0) {
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 {
out += acceptableFunctions[specOp].apply(undefined, args);
}
} 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);
} 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) && parseFloat(output) === 0 && $('input_' + result) && $('input_' + result).readAttribute('defaultValue') != null) {
output = $('input_' + result).readAttribute('defaultValue');
}
var resultFieldType = JotForm.calculationType(result);
switch (resultFieldType) {
case "html":
try {
if(!calc.replaceText) calc.replaceText = "";
if(calc.replaceText.indexOf(":") > -1) {
var subfield = calc.replaceText.substr(calc.replaceText.indexOf(":")+1);
if(subfield in combinedObject) {
output = combinedObject[subfield];
}
}
if (output.empty() && calc.defaultValue) {
output = calc.defaultValue;
}
var spans = $$("." + result + "_" + calc.replaceText.replace(":","\\:"));
if (spans.length == 0) {
var contents = $('text_' + result).innerHTML;
var re = new RegExp("\{" + calc.replaceText + "\(\\[.*?\\]\){0,1}\}", "g");
var def = calc.defaultValue || "";
contents = contents.replace(re, '<span class="replaceTag ' + result + "_" + calc.replaceText + '" default="'+def+'">' + output + '</span>');
$('text_' + result).update(contents);
} else {
spans.each(function (span) {
span.update(output);
});
}
} catch (e) {
console.log(e);
}
break;
case "address":
case "authnet":
case "paypalpro":
case "combined":
case "time":
case "braintree":
case "stripe":
for (var inputId in combinedObject) {
if ($('id_' + result).select('input[id*=' + inputId + '], select[id*=' + inputId + ']').length > 0) {
$('id_' + result).select('input[id*=' + inputId + '], select[id*=' + inputId + ']').first().value = combinedObject[inputId];
}
}
if ($('input_' + result + '_full') && $('input_' + result + '_full').readAttribute("masked") == "true") { //mask if phone is masked
JotForm.setQuestionMasking('#input_' + result + '_full', "textMasking", $('input_' + result + '_full').readAttribute("maskValue"));
}
break;
case "datetime":
if (combinedObject && "year" in combinedObject) {
for (var inputId in combinedObject) {
if ($('id_' + result).select('input[id*=' + inputId + '], select[id*=' + inputId + ']').length > 0) {
$('id_' + result).select('input[id*=' + inputId + '], select[id*=' + inputId + ']').first().value = combinedObject[inputId];
}
}
} else {
try {
if ((typeof output == "number" && output > 0) || (typeof output == "string" && output.replace(/\s/g, "").length > 0 && output !== "0")) {
var date = new Date(Math.round(output * 60 * 60 * 24 * 1000));
var year = date.getUTCFullYear();
var month = JotForm.addZeros(date.getUTCMonth() + 1, 2);
var day = JotForm.addZeros(date.getUTCDate(), 2);
if (!isNaN(year)) $("year_" + result).value = year;
if (!isNaN(month)) $("month_" + result).value = month;
if (!isNaN(day)) $("day_" + result).value = day;
}
} 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":
output = output.replace(/[^\-0-9\.]/g, "");
$('input_' + result).value = output;
break;
case "radio":
var radios = $$("#id_" + result + ' input[type="radio"]');
$A(radios).each(function (rad) {
rad.checked = false;
if (rad.value == output.strip()) {
rad.checked = true;
}
});
break;
case "checkbox":
var checks = $$("#id_" + result + ' input[type="checkbox"]');
var outputs = output.split(",");
outputs = outputs.collect(function (out) {
return out.strip();
});
$A(checks).each(function (chk) {
chk.checked = false;
if (outputs.include(chk.value)) {
chk.checked = true;
}
});
break;
case "select":
$('input_' + result).setValue(output.strip());
break;
case "matrix":
if ("resultSubField" in calc) {
if ($(calc.resultSubField)) {
$(calc.resultSubField).value = output;
}
}
break;
case "textarea":
output = output.replace(/<br>|<br\/>/gi, "\r\n");
if (output && output.length > 0) {
$('input_' + result).removeClassName('form-custom-hint').removeAttribute('spellcheck');
}
var richArea = $("id_" + result).down('.nicEdit-main');
if (richArea) {
richArea.innerHTML = output;
richArea.setStyle({'color': ''});
}
$('input_' + result).value = output;
break;
default:
if ($('input_' + result).hinted === true) { //IE8&9 make sure inserted value is not hinted
$('input_' + result).clearHint();
}
$('input_' + result).value = output;
if (output && output.length === 0 && $('input_' + result).hintClear) { //IE8&9 if value is empty reapply hint
$('input_' + result).hintClear();
}
if ($('input_' + result).readAttribute("masked") == "true") {
JotForm.setQuestionMasking("#input_" + result, "textMasking", $('input_' + result).readAttribute("maskValue"));
}
}
var infiniteLoop = function () {
// prevent calculation&condition infinite loop by limiting the nuber of times
// a calculation can be run on an element in a 500ms period
var timestamp = new Date().getTime();
var msPart = timestamp % 1000;
if (msPart < 500) {
msPart = "0";
} else {
msPart = "1";
}
var secPart = parseInt(timestamp / 1000);
var antiLoopKey = 'input_' + result + '-' + secPart + '-' + msPart;
//create global antiLoop variable if not created yet
if (!("__antiLoopCache" in window)) {
window.__antiLoopCache = {};
}
if (antiLoopKey in window.__antiLoopCache) {
window.__antiLoopCache[antiLoopKey]++;
if (window.__antiLoopCache[antiLoopKey] > 9) {
return true; //only allow same calc to trigger nine times in half a second - multiple are needed for things like sliders that change quickly
}
} else {
window.__antiLoopCache[antiLoopKey] = 1;
}
return false; //not infinite loop
}
if (infiniteLoop()) {
return;
}
if ($('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 = "click";
triggerMe = $('id_' + result)
} else if (resultFieldType == "select") {
eventType = "change";
if ($('input_' + result)) {
triggerMe = $('input_' + result);
}
} else {
eventType = "keyup";
triggerMe = $('input_' + result) ? $('input_' + result) : $('id_' + result).select('input').first();
}
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);
}
},
getWidgetType: function(qid) {
try {
if(!$("id_"+qid || $("id_"+qid).down("iframe"))) return false;
if($('input_' + qid).value.indexOf("widget_metadata") > 1) {
return JSON.parse($('input_' + qid).value).widget_metadata.type;
}
var iframe = $("id_"+qid).down("iframe");
var src = iframe.src;
var reg = new RegExp( 'jotform.io/(.*)/');
var 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: [],
/**
* When widget value is updated check whether to trigger conditions
*/
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');
}
}
},
/**
* Sets all events and actions for form conditions
*/
setConditionEvents: function () {
try {
$A(JotForm.conditions).each(function (condition) {
if (condition.disabled == true) return; //go to next condition
if (condition.type == 'field' || condition.type == 'calculation' || condition.type == 'require' || condition.type == 'mask') {
var fields = [];
$A(condition.terms).each(function (term) {
fields.push(term.field);
//add dyanmic {fields} to array to trigger events
if (condition.type == "field" && "value" in term && typeof term.value == "string") {
var val = term.value;
try {
val.replace(/\{.*?\}/gi, function (match, contents, offset, s) {
var stripped = match.replace(/[\{\}]/g, "");
var elements = $$('input[name$="_' + stripped + '"]');
if (elements.length > 0) {
var element = elements[0];
var id = element.id;
id = id.replace(/input_/, "");
fields.push(id);
}
});
} catch (e) {
console.log(condition);
}
}
});
$A(fields).each(function (id) {
switch (JotForm.getInputType(id)) {
case "widget":
JotForm.setFieldConditions('input_' + id, 'change', condition);
JotForm.widgetsWithConditions.push(id);
break;
case "combined":
case "email":
JotForm.setFieldConditions('id_' + id, 'autofill', condition);
break;
case "address":
JotForm.setFieldConditions('id_' + id, 'autofill', condition);
JotForm.setFieldConditions('input_' + id + '_country', '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, 'click', condition);
break;
case "number":
JotForm.setFieldConditions('input_' + id, 'number', condition);
break;
case "autocomplete": // Neil: Set custom event for autocomplete fields (classname: "form-autocomplete")
JotForm.setFieldConditions('input_' + id, 'autocomplete', condition);
break;
case "grading":
JotForm.setFieldConditions('id_' + id, 'keyup', condition);
break;
case "text":
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;
default: // text, textarea, dropdown
JotForm.setFieldConditions('input_' + id, 'keyup', condition);
}
});
} else {
if (document.get.mode == "edit" || document.get.mode == "inlineEdit") { //only run page condition on last page that a condition field exists so we don't jump prematurely based on populated data
var isLaterPage = function (current, testing) {
var nexts = $$('.form-pagebreak-next');
for (var i = 0; i < nexts.length; i++) {
var btn = nexts[i];
if (btn == current) return true;
if (btn == testing) return false;
}
};
var highestPage = false;
$A(condition.terms).each(function (term) {
var id = term.field.toString();
if (id.indexOf("_") !== -1) {
id = id.split("_")[0];
}
var nextButton = JotForm.getSection($('id_' + id)).select('.form-pagebreak-next')[0];
if (!nextButton) {
return;
}
var pageNumber = parseInt(nextButton.id.substring(nextButton.id.lastIndexOf("_") + 1));
if (!highestPage || isLaterPage(highestPage, nextButton)) {
highestPage = nextButton;
}
});
if (highestPage) {
highestPage.observe('mousedown', function () {
JotForm.checkCondition(condition);
});
}
} else {
$A(condition.terms).each(function (term) {
var id = term.field.toString();
// if this is a product quantity option (e.g. 4_quantity_1009_0)
if (id.indexOf("_") !== -1) {
id = id.split("_")[0];
}
if(!$('id_' + id)) {
return;
}
var nextButton = JotForm.getSection($('id_' + id)).select('.form-pagebreak-next')[0];
if (!nextButton) {
return;
}
nextButton.observe('mousedown', function () {
// JotForm.warn('Checking ' + $('label_' + id).innerHTML.strip());
JotForm.checkCondition(condition);
});
});
}
}
});
$H(JotForm.fieldConditions).each(function (pair) {
var field = pair.key;
var event = pair.value.event;
var conds = pair.value.conditions;
// JotForm.info("Has Condition:", field, $(field));
// If field is not found then continue
if (!$(field)) {
return;
}
if (event == "autocomplete") { // if event type is trigger by autocomplete, listen to blur and keyup events
$(field).observe('blur', function () {
$A(conds).each(function (cond) {
JotForm.checkCondition(cond);
});
}).run('blur');
$(field).observe('keyup', function () {
$A(conds).each(function (cond) {
JotForm.checkCondition(cond);
});
}).run('keyup');
} else if (event == "number") {
$(field).observe('change', function () {
$A(conds).each(function (cond) {
JotForm.checkCondition(cond);
});
}).run('change');
$(field).observe('keyup', function () {
$A(conds).each(function (cond) {
JotForm.checkCondition(cond);
});
}).run('keyup');
} else if (event == "autofill") {
$(field).observe('blur', function () {
$A(conds).each(function (cond) {
JotForm.checkCondition(cond);
});
}).run('blur');
$(field).observe('keyup', function () {
$A(conds).each(function (cond) {
JotForm.checkCondition(cond);
});
}).run('keyup');
if (!(!Prototype.Browser.IE9 && !Prototype.Browser.IE10 && Prototype.Browser.IE)) {
$(field).observe('change', function () {
$A(conds).each(function (cond) {
JotForm.checkCondition(cond);
});
}).run('change');
}
} else {
$(field).observe(event, function () {
$A(conds).each(function (cond) {
JotForm.checkCondition(cond);
});
});
if (!$(field).id.match(/input_[0-9]+_quantity_[0-9]+_[0-9]+/)) { // b#652068 (do not auto-run condition events on quantity fields)
$(field).run(event);
}
}
});
} catch (e) {
JotForm.error(e);
}
},
/**
* Sets field values to be duplicated before encryption
* These fields are needed by some payment gateways
* for example, braintree gets the first email field on the form
* but it should be unencrypted, so we duplicate the fields
* before encryption (at JotForm.encryptAll)
*/
setFieldsToPreserve: function (param) {
// gateways that need these fields
var gateways = [
"braintree",
"dwolla",
"stripe",
"paypal",
"paypalpro",
"paypalexpress",
"authnet"
];
if (gateways.indexOf($$('input[name="simple_fpc"]')[0].getAttribute('data-payment_type')) == -1) {
return;
}
var additionalPaymentFields = [{
type: "phone",
pattern: /Phone|Contact/i
}, {
type: "email",
pattern: /email|mail|e-mail/i
}, {
type: "company",
pattern: /company|organization/i
}];
var fields = $$('.form-line[data-type*="email"], .form-line[data-type*="textbox"], .form-line[data-type*="phone"]');
// arrange all fields by id
sortedFields = fields.sort(function (a, b) {
return Number(a.id.replace("id_", "")) - Number(b.id.replace("id_", ""));
});
var fieldsToPreserve = {};
// get the first field that matches the regex and type
sortedFields.each(function (field) {
if (Object.keys(fieldsToPreserve).length == 3) {
throw $break;
}
additionalPaymentFields.each(function (reg) {
var fieldType = field.getAttribute('data-type').replace('control_', '');
/*
valid form field type
email => email and textbox
phone => phone field and textbox
company => textbox only
*/
if (fieldType == 'textbox' || fieldType == reg.type) {
var label = field.down('label').innerHTML.strip();
var fieldId = field.id.replace('id_', '');
if (reg.pattern.exec(label) && !fieldsToPreserve[reg.type]) {
fieldsToPreserve[reg.type] = fieldId;
JotForm.fieldsToPreserve.push(fieldId);
}
}
});
});
},
/**
* Changes payment strings upon form load
* @param {type} text
* @returns {undefined}
*/
changePaymentStrings: function (text) {
if ($('coupon-header') && text.couponEnter) {
$('coupon-header').innerHTML = text.couponEnter;
}
if ($('shipping-text') && text.shippingShipping) {
$('shipping-text').innerHTML = text.shippingShipping;
}
if ($('tax-text') && text.taxTax) {
$('tax-text').innerHTML = text.taxTax;
}
if ($('subtotal-text') && text.totalSubtotal) {
$('subtotal-text').innerHTML = text.totalSubtotal;
}
if ($('total-text') && text.totalTotal) {
$('total-text').innerHTML = text.totalTotal;
}
},
handleSubscriptionPrice: function () {
// safari fix (input focus bug)
if (navigator.userAgent.toLowerCase().indexOf('safari/') > -1) {
$$('.form-product-custom_price').each(function (inp) {
// form-product-custom_price
inp.onclick = function (e) {
e.preventDefault();
};
})
}
var inputs = $$('input[data-price-source]');
if (inputs.length < 1) {
return;
}
var priceSources = [];
var events = {};
inputs.each(function (inp) {
var sourceId = inp.getAttribute('data-price-source');
var source = $('input_' + sourceId);
if (!source) {
return;
}
if (!events[sourceId]) {
events[sourceId] = [];
}
var getVal = function () {
var val = source.value;
if (typeof val !== 'number') {
val = val.replace(/[^0-9\.]/gi, "");
}
return !isNaN(val) && val > 0 ? val : 0;
}
// collect source fields
priceSources.push(source);
// collect events
events[sourceId].push(function() {
inp.value = getVal();
});
});
// attach events to source fields
priceSources.each(function (source) {
var id = source.id.replace('input_', '');
source.onkeyup = function () {
events[id].each(function (evt) {
evt();
});
JotForm.countTotal(); // re-count total
};
});
},
/*
* Handles payment donations
*/
handleDonationAmount: function () {
// donation amount input
var donationField = $$('input[id*="_donation"]')[0];
// if donation gets its amount from a calculation widget
if ($$('input[id*="_donation"]')[0].getAttribute('data-custom-amount-field') > 0) {
var calcField = $('input_' + donationField.getAttribute('data-custom-amount-field'));
// if calculation widget does not exist
if (!calcField) {
return;
}
var getVal = function () {
var val = calcField.value;
if (typeof val !== 'number') {
val = val.replace(/[^0-9\.]/gi, "");
}
return !isNaN(val) && val > 0 ? val : 0;
}
// get value from calculation widget
setTimeout(function () {
donationField.value = getVal();
}, 1000);
// observe calc widget value changes
// prototype can't observe changes initiated by a js function to a field value
// so we use Form.element.Observer which checks for changes every 'x' milliseconds
new Form.Element.Observer(
calcField,
0.5, // 500 milliseconds
function (el, value) {
donationField.value = getVal();
donationField.triggerEvent('keyup');
}
);
// if donation field requires a minimum amount
} else if (donationField.hasAttribute('data-min-amount')) {
var currency = donationField.nextSibling.textContent.strip();
var minAmount = parseFloat(donationField.readAttribute('data-min-amount'));
donationField.validateMinimum = function () { // called at setFieldValidation
var val = this.getValue();
if (isNaN(val) || val < minAmount) {
return JotForm.errored(donationField, "Minimum amount is " + minAmount + " " + currency);
} else {
return JotForm.corrected(donationField);
}
};
}
},
/**
* Checks whether form should process a payment
* @returns {Boolean}
*/
isPaymentSelected: function () {
var selected = false;
var paymentFieldId = $$('input[name="simple_fpc"]')[0].value;
var paymentField = $('id_' + paymentFieldId);
if ($$('input[name="simple_fpc"]').length < 1) {
return false;
}
// if with payment field but hidden by condition
// or inside conditionally-hidden (not collapsed) form collapse section
if (paymentField && (paymentField.getStyle('display') === "none"
|| !JotForm.isVisible(paymentField) && JotForm.getSection(paymentField).id)
) {
return false;
}
// if this is a multi-item product or subscription
if (window.productID) {
// check if at least one product is selected
$H(window.productID).each(function (pair) {
var elem = $(pair.value);
if (elem.checked) {
// get quantity field
if (!!elem.up().select('[id*="_quantity_"]').length) {
var quantityField = elem.up().select('[id*="_quantity_"]')[0];
}
if (!quantityField || quantityField.getValue() > 0) {
selected = true;
throw $break;
}
}
});
// if this is a donation
} else if ($('input_' + paymentFieldId + '_donation')) {
var elem = $('input_' + paymentFieldId + '_donation');
if (/^\d+(?:\.\d+)?$/.test(elem.getValue())) {
selected = elem.getValue() > 0;
}
// if this is a hidden single item
} 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;
},
/**
* Toggles between paypal button and regular submit button
* @param {type} show
* @returns {unresolved}
*/
togglePaypalButtons: function (show) {
var paymentFieldId = $$('input[name="simple_fpc"]')[0].value;
// if this is paypal pro and credit card payment is selected
if ($('input_' + paymentFieldId + '_paymentType_express')
&& !$('input_' + paymentFieldId + '_paymentType_express').checked) {
show = false;
}
// if checkout button is not to be used
if ($$('.paypal-button').length < 1 || !$('use_paypal_button')) {
return;
}
// replace all submit buttons with express checkout buttons
$$('.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();
}
});
},
/*
* Handles toggling between PayPal checkout buttons
* and ordinary submit buttons
* @returns {undefined}
*/
handlePaypalButtons: function () {
var products = window.productID;
var requiredPayment = false;
var paymentFieldId = $$('input[name="simple_fpc"]')[0].value;
// check if payment is required
if (products) {
$H(products).each(function (p) {
// if required
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;
}
// toggle upon form load
JotForm.togglePaypalButtons(requiredPayment || JotForm.isPaymentSelected());
// set button trigger if payment is not required
if (!requiredPayment) {
$H(products).each(function (p) {
$(p.value).observe('click', function () {
JotForm.togglePaypalButtons(JotForm.isPaymentSelected());
});
});
}
},
/*
* Checks whether form is embedded or not
* Sends url of the form's parent page
* @returns {undefined}
*/
isFormEmbedded: function () {
var form = $$('.jotform-form')[0];
if (window !== window.top) {
form.insert(new Element('input', {
type: 'hidden',
name: 'embeddedForm'
}).putValue(document.referrer));
console.log(document.referrer);
}
},
/**
* Handles Paypal Express actions
* @returns {undefined}
*/
handlePaypalExpress: function () {
if (typeof _paypalExpress !== "function" || $('express_category').getAttribute('data-digital_goods') === "No") {
return;
}
var paypalExpress = new _paypalExpress();
paypalExpress.init();
},
/**
* Handles Braintree payments
*/
handleBraintree: function () {
// skip on edit mode
if (["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;
}
var JF_braintree = __braintree();
JF_braintree.init();
},
/**
* Handles the payment subproducts behavior
*/
handlePaymentSubProducts: function () {
var heights = []; // container for the heights of the products when opened and closed
var optionValues = []; // container for the values of the properties when opened and closed
var sections = $$('.form-section'); // get the sections if there are page breaks
var productPage = false; // page where the payment field is
$$('.form-product-has-subproducts').each(function (sp) {
var wasHidden = (sp.up(".form-line") && sp.up(".form-line").hasClassName("form-field-hidden")) ? sp.up(".form-line").show() : false;
// if this form has page breaks,
if (sections.length > 1) {
// get the page where the payment field is
productPage = productPage ? productPage : sections.filter(function (p) {
return sp.descendantOf(p);
})[0];
// if this page is hidden
if (!productPage.isVisible()) {
// show page temporarily
productPage.setStyle({'display': 'block'});
// get the height of the product
heights[sp.id] = [sp.parentNode.getHeight(), $$('label[for="' + sp.id + '"]')[0].getHeight()];
// hide the page
productPage.setStyle({'display': 'none'});
} else {
heights[sp.id] = [sp.parentNode.getHeight(), $$('label[for="' + sp.id + '"]')[0].getHeight()];
}
} else {
heights[sp.id] = [sp.parentNode.getHeight(), $$('label[for="' + sp.id + '"]')[0].getHeight()];
}
showSubProducts(sp);
sp.observe('click', function () {
showSubProducts(this);
});
if(wasHidden) {
sp.up(".form-line").hide();
}
});
function showSubProducts(el) {
var productSpan = el.parentNode;
if (!el.checked) {
productSpan.shift({
height: heights[el.id][1],
duration: 0.3
});
// clear the values array
optionValues[el.id] = [];
$$('#' + el.id + '_subproducts select,' + '#' + el.id + '_subproducts input[type="text"]').each(function (field, i) {
// capture the values
var fieldValue = field.tagName === "select" ? field.getSelected().value : field.value;
if (fieldValue) {
optionValues[el.id].push([field.id, fieldValue]);
}
// pause calculation functions to avoid potential browser crash
field.stopObserving();
// clear values
if (field.tagName === "SELECT") {
field.selectedIndex = 0;
} else {
field.value = 0;
}
});
} else {
productSpan.shift({
height: heights[el.id][0] - 10,
duration: 0.3
});
// populate values
if (optionValues[el.id] && optionValues[el.id].length > 0) {
optionValues[el.id].each(function (vv) {
// pause calculation functions to avoid potential browser crash
$(vv[0]).stopObserving();
if ($(vv[0]).tagName === "SELECT") {
$(vv[0]).selectOption(vv[1]);
} else {
$(vv[0]).value = vv[1];
}
});
}
}
// resume calculation
setTimeout(function () {
JotForm.totalCounter(JotForm.prices)
}, 300);
};
},
/*
* sets currency formatting for payment fields
*/
setCurrencyFormat: function (curr, useDecimal, decimalMark) {
// currencies without decimal values
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
};
},
/**
* Calculates the payment total with quantites
* @param {Object} prices
*/
countTotal: function (prices) {
var prices = prices || JotForm.prices;
var discounted = false;
// If a coupon is entered and verified
if (Object.keys(JotForm.discounts).length > 0) {
discounted = true;
// if this is a discount for order total
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 {
// If for product items
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; // total for the whole payment field
var subTotal = 0; // subtotal for all items selected, excluding shipping or taxes
var itemSubTotal = []; // subtotal for a group of subproducts
var shippingTotal = 0; // total shipping cost
var taxTotal = 0; // total tax cost
var taxRate = 0; // uniform tax rate (percentage) for the non-exempted products
var decimal = JotForm.currencyFormat.decimal; // number of decimal places to use
var dSeparator = JotForm.currencyFormat.dSeparator;
var tSeparator = JotForm.currencyFormat.tSeparator;
var flatShipping = 0;
var products = 0;
var subscriptionCustomPrice = false;
$H(prices).each(function (pair) {
if (pair.value.price == "custom") {
subscriptionCustomPrice = pair.key;
return;
}
var isSetupFee = pair.value.recurring ? true : false; // is there a setup fee for this subscription?
var isStripe = typeof Stripe === "function"; // is this a stripe payment field
total = parseFloat(total); // total for the whole payment field
var productShipping = 0; // shipping cost for current product
var price = parseFloat(pair.value.price) || 0; // price for the individual product
var taxAmount = 0; // tax amount for the individual product
var subproduct = false; // is this a subproduct?
var parentProductKey; // subproduct's parent key (see http://www.jotform.com/help/264-Create-Sub-Products-Based-on-a-Product-Option)
var recur = pair.value.recurring; // subscription's recurring payment amount
// get the parent product id if this is a subproduct
if (pair.key.split('_').length === 4) {
subproduct = true;
// get the parent product key/id
parentProductKey = pair.key.split('_');
parentProductKey.pop();
parentProductKey = parentProductKey.join("_");
// initalize item subtotal for this subproduct group
itemSubTotal[parentProductKey] = itemSubTotal[parentProductKey] || 0;
} else {
parentProductKey = pair.key;
}
// if product has special pricing, use selected option's corresponding price
if ($(pair.value.specialPriceField)) {
var specialPriceField = $(pair.value.specialPriceField);
// if this special priced product option is expanded
// Note: expanded options are inserted on the form as hidden input fields
if (pair.value.child && pair.value.specialPriceField.split("_").length === 4) {
var idx = pair.value.specialPriceField.split("_")[3];
price = parseFloat(pair.value.specialPriceList[idx]);
} 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
}
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 {
// for subproducts with special quantity, the default quantity is 0
// since we cannot show a zero price, we use the price for the 1st option
var defaultSpecial = pair.value.specialPriceList[priceIndex + 1];
price = 0;
}
}
}
// If there is a coupon, apply the discount rate to the price
if (pair.value.discount) {
var discount = pair.value.discount.split('-');
/*
* sample discount values:
* 50-percent ( 50% off for this product )
* 50-fixed ( $50 off for this product )
* 50-percent-first ( 50% off on first payment for this subscription item)
* 50-percent-all (50 % off on all payments for this subscription item)
* 50-fixed-all ( $50 off on all payments)
*/
// if this is a discount for product
if (!discount[2]) {
price = price - ( ( discount[1] === 'fixed' ) ? discount[0] : price * ( discount[0] / 100 ) );
price = price < 0 ? 0 : price;
} else {
if (discount[2] === "all") {
// calculate discount to recurring charge
if (isSetupFee) {
recur = recur - ( ( discount[1] === 'fixed' ) ? discount[0] : recur * ( discount[0] / 100 ) );
recur = recur < 0 ? 0 : recur;
}
// if this is Stripe and there is a setup fee
if (isStripe && isSetupFee) {
// calculate setup fee
var setupFee = price - recur;
setupFee = setupFee - ( ( discount[1] === 'fixed' ) ? discount[0] : setupFee * ( discount[0] / 100 ) );
setupFee = setupFee < 0 ? 0 : setupFee;
price = Number(recur) + Number(setupFee);
} else {
// calculate recurring price
price = price - ( ( discount[1] === 'fixed' ) ? discount[0] : price * ( discount[0] / 100 ) );
price = price < 0 ? 0 : price;
}
} else if (discount[2] === "first") {
if (isSetupFee) {
if (isStripe) {
/**
* Neil: Stripe is a special case since their api does not offer a setup fee, so we do a separate charge for the setup fee
* So first payment = recurring charge + separate charge
* Therefore subscription discount for first payment actually applies only to the setup fee (first payment - recurring charge))
*/
var setupFee = price - recur;
setupFee = setupFee - ( ( discount[1] === 'fixed' ) ? discount[0] : setupFee * ( discount[0] / 100 ) );
setupFee = setupFee < 0 ? 0 : setupFee;
price = Number(recur) + Number(setupFee);
} else {
price = price - ( ( discount[1] === 'fixed' ) ? discount[0] : price * ( discount[0] / 100 ) );
price = price < 0 ? 0 : price;
}
}
} else if (discount[2] === "stripe_native") {
// if native stripe coupon is used and there is a setup fee
if (isSetupFee) {
var setupFee = price - recur;
price = recur - ( ( discount[1] === 'fixed' ) ? discount[0] : recur * ( discount[0] / 100 ) );
if (!discount[3]) { // if this isn't just a one-time discount, i.e., 10-percent-stripe_native-once
recur = price; // b#593901
}
price += Number(setupFee);
} else {
// calculate recurring price
price = price - ( ( discount[1] === 'fixed' ) ? discount[0] : price * ( discount[0] / 100 ) );
price = price < 0 ? 0 : price;
}
}
}
}
// If there is no recurring payment (i.e., not a subscription), update the 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(' Free');
} else {
$(priceText).parentNode.show();
$(priceText).update(parseFloat(price).formatMoney(decimal, dSeparator, tSeparator));
}
}
} else {
var setupfeeText = $(pair.key + '_setupfee');
priceText = $(pair.key + '_price');
if (priceText) {
// if a setup fee is not present, pair.value.price (price) is the subscription's price
// otherwise, pair.value.price is the subscription's first payment amount and the subscription's price becomes pair.value.recurring (recur)
var priceAmount = isSetupFee ? recur : price;
$(priceText).update(parseFloat(priceAmount).formatMoney(decimal, dSeparator, tSeparator));
}
if (setupfeeText) {
$(setupfeeText).update(parseFloat(price).formatMoney(decimal, dSeparator, tSeparator));
}
}
// If there is a tax, get the total tax rate including location surcharges
if (pair.value.tax) {
var tax = pair.value.tax;
taxRate = parseFloat(tax.rate);
// if location surcharge dropdown exists and there is a selected value, get the corresponding surcharge value
if ($$('select[id*="input_' + tax.surcharge.field + '"]').length > 0
&& $$('select[id*="input_' + tax.surcharge.field + '"]')[0].getSelected().value) {
var selectedIndex = $$('select[id*="input_' + tax.surcharge.field + '"]')[0].getSelected().index - 1; // we subtract 1 to the index because the first index has empty value
taxRate += tax.surcharge.rates[selectedIndex] ? parseFloat(tax.surcharge.rates[selectedIndex][0]) : 0;
}
// if location surcharge text box exists and there is a value;
if ($$('input[id="input_' + tax.surcharge.field + '"]').length > 0
&& !$$('input[id="input_' + tax.surcharge.field + '"]')[0].value.empty()) {
$H(tax.surcharge.rates).each(function (r) {
if (r[1][1].toLowerCase() === $$('input[id="input_' + tax.surcharge.field + '"]')[0].value.toLowerCase()) {
taxRate += Number(r[1][0]);
throw $break;
}
});
}
}
// include addon prices for braintree subscriptions
if (pair.value.addons) {
price += pair.value.addons;
}
if ($(pair.key).checked) {
products++;
if ($(pair.value.quantityField) || $(pair.value.specialPriceField)) {
//if there is a quantity option and special pricing isn't based on it
if ($(pair.value.quantityField) && (pair.value.specialPriceField !== pair.value.quantityField)) {
// use different calculation method for custom quantity (textbox) option
if ($(pair.value.quantityField).readAttribute('type') == "text") {
price = $(pair.value.quantityField).value ? price * Math.abs(parseInt($(pair.value.quantityField).value, 10)) : 0;
}
else {
price = price * parseInt(($(pair.value.quantityField).getSelected().text || 0 ), 10);
}
}
// if this is a subproduct, add the price to the subtotal
if (subproduct) {
itemSubTotal[parentProductKey] += price;
}
// update item subtotal if available
if ($(parentProductKey + '_item_subtotal') && !isNaN(price)) {
if (!subproduct) {
$(parentProductKey + '_item_subtotal').update(parseFloat(price).formatMoney(decimal, dSeparator, tSeparator));
} else {
$(parentProductKey + '_item_subtotal').update(parseFloat(itemSubTotal[parentProductKey]).formatMoney(decimal, dSeparator, tSeparator));
}
}
}
// if this product is taxed, calculate the tax amount
if (pair.value.tax) {
taxAmount = price * (taxRate / 100);
}
// add shipping if it is available
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);
}
} else if (flatShipping == 0 && shipping.flatRate) {
// get flat shipping rate once
shippingTotal = flatShipping = parseFloat(shipping.flatRate);
}
}
taxTotal += taxAmount; // accummulate tax amounts for each product
if (!flatShipping) {
shippingTotal += productShipping; // accumulate shipping total
}
subTotal += price; // accumulate total for all items, without shipping/discount/tax
total += price + productShipping + taxAmount; // overall total
} else {
if ($(pair.key + '_item_subtotal')) {
$(pair.key + '_item_subtotal').update("0.00");
}
}
});
// add flat rate shipping to total if available
total = flatShipping > 0 ? total + flatShipping : total;
if (total === 0 || isNaN(total)) {
total = "0.00";
}
if ($('coupon-button')) {
var couponInput = $($('coupon-button').getAttribute('data-qid') + '_coupon');
}
// if there is a total discount
if (JotForm.discounts.total) {
if (subTotal >= minimum) {
var reduce = type === "fixed" ? rate : (rate / 100) * parseFloat(subTotal);
subTotal = subTotal > reduce ? subTotal - reduce : 0;
total = total - reduce;
couponInput.value = code;
} else {
reduce = 0;
// clear (hidden) coupon input if total is less than required minimum
couponInput.value = '';
}
// insert discount indicator
$$('.form-payment-total')[0].insert({'top': JotForm.discounts.container});
$('discount_total').update(parseFloat(reduce).formatMoney(decimal, dSeparator, tSeparator));
}
// if there is a shipping discount
if (JotForm.discounts.shipping && shippingTotal > 0 && subTotal >= minimum) {
var reduce = type === "fixed" ? rate : (rate / 100) * parseFloat(shippingTotal);
var oldShippingTotal = shippingTotal;
shippingTotal = shippingTotal > reduce ? shippingTotal - reduce : 0;
total = total - (oldShippingTotal - shippingTotal);
}
if (subscriptionCustomPrice && $(subscriptionCustomPrice).checked) {
total = $(subscriptionCustomPrice + '_custom_price').getValue();
}
// assign total to global var;
this.paymentTotal = Number(total);
// for PaypalPro only
if ($('creditCardTable')) {
// if total is zero and a valid coupon has been entered
if (products > 0 && this.paymentTotal === 0 && discounted) {
$('creditCardTable').hide();
} else if ($$('input[id*="paymentType_credit"]')[0].checked) {
$('creditCardTable').show();
}
}
// update payment subtotal
if ($("payment_subtotal")) {
$("payment_subtotal").update(parseFloat(subTotal).formatMoney(decimal, dSeparator, tSeparator));
}
// update tax figures
if ($("payment_tax")) {
$("payment_tax").update(parseFloat(taxTotal).formatMoney(decimal, dSeparator, tSeparator));
}
// update shipping cost total
if ($("payment_shipping")) {
$("payment_shipping").update(parseFloat(shippingTotal).formatMoney(decimal, dSeparator, tSeparator));
}
// update overall total
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"); //b#520074 trigger calculation
}
}
},
prices: {},
/**
* Sets the events for dynamic total calculation
* @param {Object} prices
*/
totalCounter: function (prices) {
// format money function
Number.prototype.formatMoney = function (c, d, t) {
/* Fix: 784398 (Erhan)
JavaScript's decimal point representation is not a thing what we think it is.
So, we do not directly apply toFixed method on them.
e.g. Try 1.925.toFixed(2) and 39.925.toFixed(2) on your browser.
jotform.jsOpen
Munish Sharma
(msharmaod@gmail.com)Displaying jotform.js.
Also see: Tab Triggers