@supports (-webkit-touch-callout: none) {#fbuilder select, #fbuilder textarea, #fbuilder input[type="text"], #fbuilder input[type="password"]{ font-size: 16px !important; }}
#fbuilder .ui-datepicker-calendar th{white-space:nowrap}
.clearer{clear:both;}
#fbuilder *,#fbuilder ::after,#fbuilder ::before{box-sizing:border-box;}
#fbuilder{}
#fbuilder .fields,#fbuilder .fform{padding:5px 0px;}
#fbuilder .fform h1{margin:5px 0px;padding:0px;}
#fbuilder .small{width:25% !important;padding-left:0;padding-right:0;}
#fbuilder .medium{width:50% !important;padding-left:0;padding-right:0;}
#fbuilder .large{width:100% !important;padding-left:0;padding-right:0;}
@media screen and (min-width: 740px){
#fbuilder .fields.column2{float:left;width:49.9%;}
#fbuilder .fields.column3{float:left;width:33.3%;}
#fbuilder .fields.column4{float:left;width:24.9%;}
}
@media screen and (max-width: 640px){
#fbuilder .small,
#fbuilder .medium{width:98% !important;padding-left:0;padding-right:0;}
}
#fbuilder .one_column{}
#fbuilder .two_column{float:left;width:48%;}
#fbuilder .three_column{float:left;width:30%;}
#fbuilder .side_by_side{float:left;}
#fbuilder .dfield{position:relative;}
#fbuilder .center_aligned *{text-align:center}
#fbuilder .top_aligned .fields label{}
#fbuilder .top_aligned .fields .dfield{}
#fbuilder .left_aligned .fields label{float:left;width:31%;}
#fbuilder .left_aligned .fields .dfield{float:left;width:65%;}
#fbuilder .right_aligned .fields label{float:left;width:31%;text-align:right;padding:3px 3px 0px 0px;}
#fbuilder .right_aligned .fields .dfield{float:left;width:65%;}
#fbuilder .right_aligned .fields .dfield label{text-align:left;}
#fbuilder .right_aligned .captcha,#fbuilder .left_aligned .captcha{margin-left:31%}
#fbuilder .one_column label,
#fbuilder .two_column label,
#fbuilder .three_column label,
#fbuilder .side_by_side label{ width:100% !important; }
#fbuilder .left_aligned .section_breaks.fields label,
#fbuilder .left_aligned .comment_area.fields label,
#fbuilder .right_aligned .section_breaks.fields label,
#fbuilder .right_aligned .comment_area.fields label{width:100%;clear:both;}
#fbuilder .cpefb_error{border1:1px solid red;}
#fbuilder .top_aligned .fields label.cpefb_error,.left_aligned .fields label.cpefb_error,.right_aligned .fields label.cpefb_error{display:block;border:0px;color:#f00;float:none;}
#fbuilder div.cpefb_error{background:#FDF9E5;border:1px solid #f00;opacity:0.9;margin-top:7px;position:relative;padding:0px 5px;z-index:1000;display:inline-block}
#fbuilder div.cpefb_error:after{content:"";position:absolute;background:transparent url(//cocotte-coworking.fr/wp-content/plugins/appointment-hour-booking/images/tooltop.gif) no-repeat scroll 10px center;color:red;font-weight:bold;height:8px;width:100%;top:-8px;left:0px;z-index:1000;}
#fbuilder .ui-datepicker{ z-index:9999 !important;}
#fbuilder span.uh{display:block;font-size:80%;clear:both;}
#fbuilder .section_break{border-top:1px dotted #555;clear:both;}
#fbuilder .uh_phone{display:inline-block;margin:0px 5px;font-size:80%;text-align:center;position:relative;}
#fbuilder .uh_phone input{text-align:center;font-size:100%;}
#fbuilder .uh_phone div.cpefb_error{white-space:nowrap;}
#fbuilder .cpp_form { text-align:left;}
#fbuilder .pbreak{display:none;}
#fbuilder .pbreak.pb0{display:block;}
#fbuilder .pbreak .pbPrevious,#fbuilder .pbreak .pbNext,#fbuilder .pbSubmit{background:#ccc;color:#000;display:inline-block;cursor:pointer;margin:10px 10px 0px 0px;padding:5px 20px;}
.left_aligned .pb0 .pbNext, .right_aligned .pb0 .pbNext{margin-left:31% !important}
.left_aligned .pbreak:not(.pb0) .pbPrevious, .right_aligned .pbreak:not(.pb0) .pbPrevious{margin-left:31% !important}
.left_aligned .pb0 .pbSubmit,  .right_aligned .pb0 .pbSubmit{margin-left:31% !important}
#fbuilder fieldset{display:inherit}
#fbuilder .pbreak.pb0 .pbPrevious{display:none;}
#fbuilder .pbreak.pbEnd .pbNext{display:none;}
#fbuilder .ignore{display:none;}
#fbuilder fieldset{border:1px solid #ccc;padding:10px;}
#fbuilder legend{border:1px solid #ccc;padding:5px 10px;}
#fbuilder .cpcaptchalayer,.cp_subbtn{display:none;}
#fbuilder .captcha img{ cursor:pointer; }
.ui-tooltip.uh-tooltip{width:250px;font-size:10px;font-weight:normal;padding:5px;}
#fbuilder  .cff-summary-title:after{ content: ': '; }
#fbuilder  .hide{ display:none; }
#fbuilder  .clear{ clear:both; }
#fbuilder .slots{border:1px solid #888;width:100%;padding:10px;-webkit-box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, .5);
-moz-box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, .5);
box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, .5);}
#fbuilder .slots div{display:inline-block;border:1px solid #005;margin:5px;padding:1px}
#fbuilder .slots div a{background: #ededed;box-shadow:none;display:inline-block;padding:4px}
#fbuilder .slots div a:hover{background: #f7f7f7;}
.cpapp_break { clear: both; }
.cpapp_no_wrap { display: inline-flex; }
.cpappb_field_0, .cpappb_field_1,
.cpappb_field_2, .cpappb_field_3,
.cpappb_field_4, .cpappb_field_5,
.cpappb_field_6, .cpappb_field_7,
.cpappb_field_7, .cpappb_field_9,
.cpappb_field_10, .cpappb_field_11
{
float: left; 
min-width: 85px;
padding-right:11px;
border-bottom: 1px dotted #777777;
margin-left: 1px;     
padding: 5px;
margin: 2px;
}
.ahb_list_service{padding:0px 10px}
.ahb_list_quantity{padding-right:10px}
#fbuilder .slots div.htmlUsed{border:1px solid #ccc;}
#fbuilder .slots div.htmlUsed a{color:#ccc;}
.summary-field-value a{display:none !important}
.ui-datepicker{min-width:260px}
.ui-tooltip {padding: 8px;position: absolute;z-index: 9999;border:1px solid #ccc;min-width:300px;background-color:#fff;}
.adminonly { display:none; }
#ahbadminedititem .adminonly { display:block; }
#fbuilder .slots div.ahbmoreinfo{display:none}
.ahbtooltip{display:none !important;max-width:200px !important;border:1px solid #888;padding:10px;-webkit-box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, .5);-moz-box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, .5);box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, .5);}  
.ahbtooltip{display:block !important;width:auto !important;max-width:500px !important;}
.notavailable{color:#f00;text-decoration: line-through;}
.ahb_slot_availability{display: none;text-align:center}
.ahb_slot_availability .p:after {content: "/"}
#fbuilder .cff-close-dlg{display:inline-block;width:16px;height:16px;position:absolute;top:10px;right:10px;cursor:pointer;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAAowAAAKMB8MeazgAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAB5SURBVDiNrZPRCcAwCEQfnUiySAZuF8kSWeH6Yz8KrQZMQAicJ+epAB0YwAmYJKIADLic0/GPPCbQAnLznCd/4NWUFfkgy1VjH8CryA95ApYltAiTRCZxpuoW+gz9WXE6NPeg+ra1UDIxGlWEObe4SGxY5fIxlc75Bkt9V4JS7KWJAAAAAElFTkSuQmCC59ef34356faa7edebc7ed5432ddb673d);
}
#fbuilder .cff-dialog{position:fixed;z-index:999999;padding:30px;width:600px;height:300px;background:#fff;top:50%;left:50%;box-shadow:rgba(0, 0, 0, 0.5) 0px 0px 10px 0px;}
#fbuilder .cff-dialog-content{width:100%;height:100%;overflow:auto;}
#fbuilder  .hide{ display:none; }
.emptyvalue{display:none !important}
#fbuilder .ui-datepicker-calendar td,#fbuilder .ui-datepicker-calendar th{padding:inherit}
#fbuilder .slots .service{border:0px}
#fbuilder .slots .service .service_title{border:0px;display:block}
#fbuilder .ahb_list_quantity1{display:none}
#fbuilder .slots .currentSelection{border:2px solid #005;padding:0px;}
#fbuilder .slots .htmlUsed.currentSelection{border:2px solid #005;padding:0px;}
#fbuilder table{margin:auto}
#fbuilder .ui-datepicker-header a{-webkit-box-shadow:none}
#fbuilder label{display:initial}
#fbuilder .slots{position:relative}
#fbuilder .slots .hide{display:none}
a.ahb_showhidelink{position: absolute;
right: 5px;
top: 0px;
}
.ahb_bt_selected a{background:#FF6961  !important}
.ahb_overlapping_detail{display:none}fbuilderjQuery = (typeof fbuilderjQuery != 'undefined' ) ? fbuilderjQuery : jQuery;
fbuilderjQuery(function(){
(function($) {
$.extend({
stringifyXX  : function stringifyXX(obj) {
var enc  = function(param) {
var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
meta = {
'\b' : '\\b',
'\t' : '\\t',
'\n' : '\\n',
'\f' : '\\f',
'\r' : '\\r',
'"' : '\\"',
'\\' : '\\\\'
};
escapable.lastIndex = 0;
return escapable.test(param) ? param.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) : param;
};
var t = typeof (obj);
if (t != "object" || obj === null) {
// simple data type
if (t == "string") obj = '"' + obj + '"';
return String(obj);
} else {
// recurse array or object
var n, v, json = [], arr = (obj && obj.constructor == Array);
for (n in obj) {
v = obj[n];
t = typeof(v);
if (t!="function")
{
if (t == "string") v = '"' + enc(v) + '"'; else if (t == "object" && v !== null) v = $.stringifyXX(v);
json.push((arr ? "" : '"' + n + '":') + String(v));
}
}
return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
}
});
})(fbuilderjQuery);
});fbuilderjQuery=(typeof fbuilderjQuery!='undefined')?fbuilderjQuery:jQuery;(function(factory){if(typeof define==="function"&&define.amd){define(["fbuilderjQuery"],factory);}else if(typeof module==="object"&&module.exports){module.exports=factory(require("fbuilderjQuery"));}else{factory(fbuilderjQuery);}}(function($){$.extend($.fn,{validate:function(options){if(!this.length){if(options&&options.debug&&window.console){console.warn("Nothing selected, can't validate, returning nothing.");} return;} var validator=$.data(this[0],"validator");if(validator){return validator;} this.attr("novalidate","novalidate");validator=new $.validator(options,this[0]);$.data(this[0],"validator",validator);if(validator.settings.onsubmit){this.on("click.validate",":submit",function(event){validator.submitButton=event.currentTarget;if($(this).hasClass("cancel")){validator.cancelSubmit=true;} if($(this).attr("formnovalidate")!==undefined){validator.cancelSubmit=true;}});this.on("submit.validate",function(event){if(validator.settings.debug){event.preventDefault();} function handle(){var hidden,result;if(validator.submitButton&&(validator.settings.submitHandler||validator.formSubmitted)){hidden=$("<input type='hidden'/>").attr("name",validator.submitButton.name).val($(validator.submitButton).val()).appendTo(validator.currentForm);} if(validator.settings.submitHandler){result=validator.settings.submitHandler.call(validator,validator.currentForm,event);if(hidden){hidden.remove();} if(result!==undefined){return result;} return false;} return true;} if(validator.cancelSubmit){validator.cancelSubmit=false;return handle();} if(validator.form()){if(validator.pendingRequest){validator.formSubmitted=true;return false;} return handle();}else{validator.focusInvalid();return false;}});} return validator;},valid:function(){var valid,validator,errorList;if($(this[0]).is("form")){valid=this.validate().form();}else{errorList=[];valid=true;validator=$(this[0].form).validate();this.each(function(){valid=validator.element(this)&&valid;if(!valid){errorList=errorList.concat(validator.errorList);}});validator.errorList=errorList;} return valid;},rules:function(command,argument){var element=this[0],settings,staticRules,existingRules,data,param,filtered;if(element==null){return;} if(!element.form&&element.hasAttribute("contenteditable")){element.form=this.closest("form")[0];element.name=this.attr("name");} if(element.form==null){return;} if(command){settings=$.data(element.form,"validator").settings;staticRules=settings.rules;existingRules=$.validator.staticRules(element);switch(command){case"add":$.extend(existingRules,$.validator.normalizeRule(argument));delete existingRules.messages;staticRules[element.name]=existingRules;if(argument.messages){settings.messages[element.name]=$.extend(settings.messages[element.name],argument.messages);} break;case"remove":if(!argument){delete staticRules[element.name];return existingRules;} filtered={};$.each(argument.split(/\s/),function(index,method){filtered[method]=existingRules[method];delete existingRules[method];});return filtered;}} data=$.validator.normalizeRules($.extend({},$.validator.classRules(element),$.validator.attributeRules(element),$.validator.dataRules(element),$.validator.staticRules(element)),element);if(data.required){param=data.required;delete data.required;data=$.extend({required:param},data);} if(data.remote){param=data.remote;delete data.remote;data=$.extend(data,{remote:param});} return data;}});$.extend($.expr.pseudos||$.expr[":"],{blank:function(a){return!$.trim(""+$(a).val());},filled:function(a){var val=$(a).val();return val!==null&&!!$.trim(""+val);},unchecked:function(a){return!$(a).prop("checked");}});$.validator=function(options,form){this.settings=$.extend(true,{},$.validator.defaults,options);this.currentForm=form;this.init();};$.validator.format=function(source,params){if(arguments.length===1){return function(){var args=$.makeArray(arguments);args.unshift(source);return $.validator.format.apply(this,args);};} if(params===undefined){return source;} if(arguments.length>2&&params.constructor!==Array){params=$.makeArray(arguments).slice(1);} if(params.constructor!==Array){params=[params];} $.each(params,function(i,n){source=source.replace(new RegExp("\\{"+i+"\\}","g"),function(){return n;});});return source;};$.extend($.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"cpefb_error",pendingClass:"pending",validClass:"valid",errorElement:"label",focusCleanup:false,focusInvalid:true,errorContainer:$([]),errorLabelContainer:$([]),onsubmit:true,ignore:":hidden",ignoreTitle:false,onfocusin:function(element){this.lastActive=element;if(this.settings.focusCleanup){if(this.settings.unhighlight){this.settings.unhighlight.call(this,element,this.settings.errorClass,this.settings.validClass);} this.hideThese(this.errorsFor(element));}},onfocusout:function(element){if(!this.checkable(element)&&(element.name in this.submitted||!this.optional(element))){this.element(element);}},onkeyup:function(element,event){var excludedKeys=[16,17,18,20,35,36,37,38,39,40,45,144,225];if(event.which===9&&this.elementValue(element)===""||$.inArray(event.keyCode,excludedKeys)!==-1){return;}else if(element.name in this.submitted||element.name in this.invalid){this.element(element);}},onclick:function(element){if(element.name in this.submitted){this.element(element);}else if(element.parentNode.name in this.submitted){this.element(element.parentNode);}},highlight:function(element,errorClass,validClass){if(element.type==="radio"){this.findByName(element.name).addClass(errorClass).removeClass(validClass);}else{$(element).addClass(errorClass).removeClass(validClass);}},unhighlight:function(element,errorClass,validClass){if(element.type==="radio"){this.findByName(element.name).removeClass(errorClass).addClass(validClass);}else{$(element).removeClass(errorClass).addClass(validClass);}}},setDefaults:function(settings){$.extend($.validator.defaults,settings);},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",number:"Please enter a valid number.",digits:"Please enter only digits.",equalTo:"Please enter the same value again.",maxlength:$.validator.format("Please enter no more than {0} characters."),minlength:$.validator.format("Please enter at least {0} characters."),rangelength:$.validator.format("Please enter a value between {0} and {1} characters long."),range:$.validator.format("Please enter a value between {0} and {1}."),max:$.validator.format("Please enter a value less than or equal to {0}."),min:$.validator.format("Please enter a value greater than or equal to {0}."),step:$.validator.format("Please enter a multiple of {0}.")},autoCreateRanges:false,prototype:{init:function(){this.labelContainer=$(this.settings.errorLabelContainer);this.errorContext=this.labelContainer.length&&this.labelContainer||$(this.currentForm);this.containers=$(this.settings.errorContainer).add(this.settings.errorLabelContainer);this.submitted={};this.valueCache={};this.pendingRequest=0;this.pending={};this.invalid={};this.reset();var groups=(this.groups={}),rules;$.each(this.settings.groups,function(key,value){if(typeof value==="string"){value=value.split(/\s/);} $.each(value,function(index,name){groups[name]=key;});});rules=this.settings.rules;$.each(rules,function(key,value){rules[key]=$.validator.normalizeRule(value);});function delegate(event){if(!this.form&&this.hasAttribute("contenteditable")){this.form=$(this).closest("form")[0];this.name=$(this).attr("name");} var validator=$.data(this.form,"validator"),eventType="on"+event.type.replace(/^validate/,""),settings=validator.settings;if(settings[eventType]&&!$(this).is(settings.ignore)){settings[eventType].call(validator,this,event);}} $(this.currentForm).on("focusin.validate focusout.validate keyup.validate",":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'], "+"[type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], "+"[type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], "+"[type='radio'], [type='checkbox'], [contenteditable], [type='button']",delegate).on("click.validate","select, option, [type='radio'], [type='checkbox']",delegate);if(this.settings.invalidHandler){$(this.currentForm).on("invalid-form.validate",this.settings.invalidHandler);}},form:function(){this.checkForm();$.extend(this.submitted,this.errorMap);this.invalid=$.extend({},this.errorMap);if(!this.valid()){$(this.currentForm).triggerHandler("invalid-form",[this]);} this.showErrors();return this.valid();},checkForm:function(){this.prepareForm();for(var i=0,elements=(this.currentElements=this.elements());elements[i];i++){this.check(elements[i]);} return this.valid();},element:function(element){var cleanElement=this.clean(element),checkElement=this.validationTargetFor(cleanElement),v=this,result=true,rs,group;if(checkElement===undefined){delete this.invalid[cleanElement.name];}else{this.prepareElement(checkElement);this.currentElements=$(checkElement);group=this.groups[checkElement.name];if(group){$.each(this.groups,function(name,testgroup){if(testgroup===group&&name!==checkElement.name){cleanElement=v.validationTargetFor(v.clean(v.findByName(name)));if(cleanElement&&cleanElement.name in v.invalid){v.currentElements.push(cleanElement);result=v.check(cleanElement)&&result;}}});} rs=this.check(checkElement)!==false;result=result&&rs;if(rs){this.invalid[checkElement.name]=false;}else{this.invalid[checkElement.name]=true;} if(!this.numberOfInvalids()){this.toHide=this.toHide.add(this.containers);} this.showErrors();$(element).attr("aria-invalid",!rs);} return result;},showErrors:function(errors){if(errors){var validator=this;$.extend(this.errorMap,errors);this.errorList=$.map(this.errorMap,function(message,name){return{message:message,element:validator.findByName(name)[0]};});this.successList=$.grep(this.successList,function(element){return!(element.name in errors);});} if(this.settings.showErrors){this.settings.showErrors.call(this,this.errorMap,this.errorList);}else{this.defaultShowErrors();}},resetForm:function(){if($.fn.resetForm){$(this.currentForm).resetForm();} this.invalid={};this.submitted={};this.prepareForm();this.hideErrors();var elements=this.elements().removeData("previousValue").removeAttr("aria-invalid");this.resetElements(elements);},resetElements:function(elements){var i;if(this.settings.unhighlight){for(i=0;elements[i];i++){this.settings.unhighlight.call(this,elements[i],this.settings.errorClass,"");this.findByName(elements[i].name).removeClass(this.settings.validClass);}}else{elements.removeClass(this.settings.errorClass).removeClass(this.settings.validClass);}},numberOfInvalids:function(){return this.objectLength(this.invalid);},objectLength:function(obj){var count=0,i;for(i in obj){if(obj[i]!==undefined&&obj[i]!==null&&obj[i]!==false){count++;}} return count;},hideErrors:function(){this.hideThese(this.toHide);},hideThese:function(errors){ this.addWrapper(errors).hide();},valid:function(){return this.size()===0;},size:function(){return this.errorList.length;},focusInvalid:function(){if(this.settings.focusInvalid){try{$(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin");}catch(e){}}},findLastActive:function(){var lastActive=this.lastActive;return lastActive&&$.grep(this.errorList,function(n){return n.element.name===lastActive.name;}).length===1&&lastActive;},elements:function(){var validator=this,rulesCache={};return $(this.currentForm).find("input, select, textarea, [contenteditable]").not(":submit, :reset, :image, :disabled").not(this.settings.ignore).filter(function(){var name=this.name||$(this).attr("name");if(!name&&validator.settings.debug&&window.console){console.error("%o has no name assigned",this);} if(this.hasAttribute("contenteditable")){this.form=$(this).closest("form")[0];this.name=name;} if(name in rulesCache||!validator.objectLength($(this).rules())){return false;} rulesCache[name]=true;return true;});},clean:function(selector){return $(selector)[0];},errors:function(){var errorClass=this.settings.errorClass.split(" ").join(".");return $(this.settings.errorElement+"."+errorClass,this.errorContext);},resetInternals:function(){this.successList=[];this.errorList=[];this.errorMap={};this.toShow=$([]);this.toHide=$([]);},reset:function(){this.resetInternals();this.currentElements=$([]);},prepareForm:function(){this.reset();this.toHide=this.errors().add(this.containers);},prepareElement:function(element){this.reset();this.toHide=this.errorsFor(element);},elementValue:function(element){var $element=$(element),type=element.type,val,idx;if(type==="radio"||type==="checkbox"){return this.findByName(element.name).filter(":checked").val();}else if(type==="number"&&typeof element.validity!=="undefined"){return element.validity.badInput?"NaN":$element.val();} if(element.hasAttribute("contenteditable")){val=$element.text();}else{val=$element.val();} if(type==="file"){if(val.substr(0,12)==="C:\\fakepath\\"){return val.substr(12);} idx=val.lastIndexOf("/");if(idx>=0){return val.substr(idx+1);} idx=val.lastIndexOf("\\");if(idx>=0){return val.substr(idx+1);} return val;} if(typeof val==="string"){return val.replace(/\r/g,"");} return val;},check:function(element){element=this.validationTargetFor(this.clean(element));var rules=$(element).rules(),rulesCount=$.map(rules,function(n,i){return i;}).length,dependencyMismatch=false,val=this.elementValue(element),result,method,rule,normalizer;if(typeof rules.normalizer==="function"){normalizer=rules.normalizer;}else if(typeof this.settings.normalizer==="function"){normalizer=this.settings.normalizer;} if(normalizer){val=normalizer.call(element,val);if(typeof val!=="string"){throw new TypeError("The normalizer should return a string value.");} delete rules.normalizer;} for(method in rules){rule={method:method,parameters:rules[method]};try{result=$.validator.methods[method].call(this,val,element,rule.parameters);if(result==="dependency-mismatch"&&rulesCount===1){dependencyMismatch=true;continue;} dependencyMismatch=false;if(result==="pending"){this.toHide=this.toHide.not(this.errorsFor(element));return;} if(!result){this.formatAndAdd(element,rule);return false;}}catch(e){if(this.settings.debug&&window.console){console.log("Exception occurred when checking element "+element.id+", check the '"+rule.method+"' method.",e);} if(e instanceof TypeError){e.message+=".  Exception occurred when checking element "+element.id+", check the '"+rule.method+"' method.";} throw e;}} if(dependencyMismatch){return;} if(this.objectLength(rules)){this.successList.push(element);} return true;},customDataMessage:function(element,method){return $(element).data("msg"+method.charAt(0).toUpperCase()+ method.substring(1).toLowerCase())||$(element).data("msg");},customMessage:function(name,method){var m=this.settings.messages[name];return m&&(m.constructor===String?m:m[method]);},findDefined:function(){for(var i=0;i<arguments.length;i++){if(arguments[i]!==undefined){return arguments[i];}} return undefined;},defaultMessage:function(element,rule){if(typeof rule==="string"){rule={method:rule};} var message=this.findDefined(this.customMessage(element.name,rule.method),this.customDataMessage(element,rule.method),!this.settings.ignoreTitle&&element.title||undefined,$.validator.messages[rule.method],"<strong>Warning: No message defined for "+element.name+"</strong>"),theregex=/\$?\{(\d+)\}/g;if(typeof message==="function"){message=message.call(this,rule.parameters,element);}else if(theregex.test(message)){message=$.validator.format(message.replace(theregex,"{$1}"),rule.parameters);} return message;},formatAndAdd:function(element,rule){var message=this.defaultMessage(element,rule);this.errorList.push({message:message,element:element,method:rule.method});this.errorMap[element.name]=message;this.submitted[element.name]=message;},addWrapper:function(toToggle){if(this.settings.wrapper){toToggle=toToggle.add(toToggle.parent(this.settings.wrapper));} return toToggle;},defaultShowErrors:function(){var i,elements,error;for(i=0;this.errorList[i];i++){error=this.errorList[i];if(this.settings.highlight){this.settings.highlight.call(this,error.element,this.settings.errorClass,this.settings.validClass);} this.showLabel(error.element,error.message);} if(this.errorList.length){this.toShow=this.toShow.add(this.containers);} if(this.settings.success){for(i=0;this.successList[i];i++){this.showLabel(this.successList[i]);}} if(this.settings.unhighlight){for(i=0,elements=this.validElements();elements[i];i++){this.settings.unhighlight.call(this,elements[i],this.settings.errorClass,this.settings.validClass);}} this.toHide=this.toHide.not(this.toShow);this.hideErrors();this.addWrapper(this.toShow).show();},validElements:function(){return this.currentElements.not(this.invalidElements());},invalidElements:function(){return $(this.errorList).map(function(){return this.element;});},showLabel:function(element,message){var place,group,errorID,v,error=this.errorsFor(element),elementID=this.idOrName(element),describedBy=$(element).attr("aria-describedby");if(error.length){error.removeClass(this.settings.validClass).addClass(this.settings.errorClass);error.html(message);}else{error=$("<"+this.settings.errorElement+">").attr("id",elementID+"-error").addClass(this.settings.errorClass).html(message||"");place=error;if(this.settings.wrapper){place=error.hide().show().wrap("<"+this.settings.wrapper+"/>").parent();} if(this.labelContainer.length){this.labelContainer.append(place);}else if(this.settings.errorPlacement){this.settings.errorPlacement.call(this,place,$(element));}else{place.insertAfter(element);} if(error.is("label")){error.attr("for",elementID);}else if(error.parents("label[for='"+this.escapeCssMeta(elementID)+"']").length===0){errorID=error.attr("id");if(!describedBy){describedBy=errorID;}else if(!describedBy.match(new RegExp("\\b"+this.escapeCssMeta(errorID)+"\\b"))){describedBy+=" "+errorID;} $(element).attr("aria-describedby",describedBy);group=this.groups[element.name];if(group){v=this;$.each(v.groups,function(name,testgroup){if(testgroup===group){$("[name='"+v.escapeCssMeta(name)+"']",v.currentForm).attr("aria-describedby",error.attr("id"));}});}}} if(!message&&this.settings.success){error.text("");if(typeof this.settings.success==="string"){error.addClass(this.settings.success);}else{this.settings.success(error,element);}} this.toShow=this.toShow.add(error);},errorsFor:function(element){var name=this.escapeCssMeta(this.idOrName(element)),describer=$(element).attr("aria-describedby"),selector="label[for='"+name+"'], label[for='"+name+"'] *";if(describer){selector=selector+", #"+this.escapeCssMeta(describer).replace(/\s+/g,", #");} return this.errors().filter(selector);},escapeCssMeta:function(string){return string.replace(/([\\!"#$%&'()*+,./:;<=>?@\[\]^`{|}~])/g,"\\$1");},idOrName:function(element){return this.groups[element.name]||(this.checkable(element)?element.name:element.id||element.name);},
validationTargetFor:function(element){if(this.checkable(element)){element=this.findByName(element.name);} return $(element).not(this.settings.ignore)[0];},checkable:function(element){return(/radio|checkbox/i).test(element.type);},findByName:function(name){return $(this.currentForm).find("[name='"+this.escapeCssMeta(name)+"']");},getLength:function(value,element){switch(element.nodeName.toLowerCase()){case"select":return $("option:selected",element).length;case"input":if(this.checkable(element)){return this.findByName(element.name).filter(":checked").length;}} return value.length;},depend:function(param,element){return this.dependTypes[typeof param]?this.dependTypes[typeof param](param,element):true;},dependTypes:{"boolean":function(param){return param;},"string":function(param,element){return!!$(param,element.form).length;},"function":function(param,element){return param(element);}},optional:function(element){var val=this.elementValue(element);return!$.validator.methods.required.call(this,val,element)&&"dependency-mismatch";},startRequest:function(element){if(!this.pending[element.name]){this.pendingRequest++;$(element).addClass(this.settings.pendingClass);this.pending[element.name]=true;}},stopRequest:function(element,valid){this.pendingRequest--;if(this.pendingRequest<0){this.pendingRequest=0;} delete this.pending[element.name];$(element).removeClass(this.settings.pendingClass);if(valid&&this.pendingRequest===0&&this.formSubmitted&&this.form()){$(this.currentForm).submit();if(this.submitButton){$("input:hidden[name='"+this.submitButton.name+"']",this.currentForm).remove();} this.formSubmitted=false;}else if(!valid&&this.pendingRequest===0&&this.formSubmitted){$(this.currentForm).triggerHandler("invalid-form",[this]);this.formSubmitted=false;}},previousValue:function(element,method){method=typeof method==="string"&&method||"remote";return $.data(element,"previousValue")||$.data(element,"previousValue",{old:null,valid:true,message:this.defaultMessage(element,{method:method})});},destroy:function(){this.resetForm();$(this.currentForm).off(".validate").removeData("validator").find(".validate-equalTo-blur").off(".validate-equalTo").removeClass("validate-equalTo-blur");}},classRuleSettings:{required:{required:true},email:{email:true},url:{url:true},date:{date:true},dateISO:{dateISO:true},number:{number:true},digits:{digits:true},creditcard:{creditcard:true}},addClassRules:function(className,rules){if(className.constructor===String){this.classRuleSettings[className]=rules;}else{$.extend(this.classRuleSettings,className);}},classRules:function(element){var rules={},classes=$(element).attr("class");if(classes){$.each(classes.split(" "),function(){if(this in $.validator.classRuleSettings){$.extend(rules,$.validator.classRuleSettings[this]);}});} return rules;},normalizeAttributeRule:function(rules,type,method,value){if(/min|max|step/.test(method)&&(type===null||/number|range|text/.test(type))){if(!/^\s*$/.test(value))value=Number(value);if(isNaN(value)){value=undefined;}} if(value||value===0){rules[method]=value;}else if(type===method&&type!=="range"){rules[method]=true;}},attributeRules:function(element){var rules={},$element=$(element),type=element.getAttribute("type"),method,value;for(method in $.validator.methods){if(method==="required"){value=element.getAttribute(method);if(value===""){value=true;} value=!!value;}else{value=$element.attr(method);} this.normalizeAttributeRule(rules,type,method,value);} if(rules.maxlength&&/-1|2147483647|524288/.test(rules.maxlength)){delete rules.maxlength;} return rules;},dataRules:function(element){var rules={},$element=$(element),type=element.getAttribute("type"),method,value;for(method in $.validator.methods){value=$element.data("rule"+method.charAt(0).toUpperCase()+method.substring(1).toLowerCase());this.normalizeAttributeRule(rules,type,method,value);} return rules;},staticRules:function(element){var rules={},validator=$.data(element.form,"validator");if(validator.settings.rules){rules=$.validator.normalizeRule(validator.settings.rules[element.name])||{};} return rules;},normalizeRules:function(rules,element){$.each(rules,function(prop,val){if(val===false){delete rules[prop];return;} if(val.param||val.depends){var keepRule=true;switch(typeof val.depends){case"string":keepRule=!!$(val.depends,element.form).length;break;case"function":keepRule=val.depends.call(element,element);break;} if(keepRule){rules[prop]=val.param!==undefined?val.param:true;}else{$.data(element.form,"validator").resetElements($(element));delete rules[prop];}}});$.each(rules,function(rule,parameter){rules[rule]=$.isFunction(parameter)&&rule!=="normalizer"?parameter(element):parameter;});$.each(["minlength","maxlength"],function(){if(rules[this]){rules[this]=Number(rules[this]);}});$.each(["rangelength","range"],function(){var parts;if(rules[this]){if($.isArray(rules[this])){rules[this]=[Number(rules[this][0]),Number(rules[this][1])];}else if(typeof rules[this]==="string"){parts=rules[this].replace(/[\[\]]/g,"").split(/[\s,]+/);rules[this]=[Number(parts[0]),Number(parts[1])];}}});if($.validator.autoCreateRanges){if(rules.min!=null&&rules.max!=null){rules.range=[rules.min,rules.max];delete rules.min;delete rules.max;} if(rules.minlength!=null&&rules.maxlength!=null){rules.rangelength=[rules.minlength,rules.maxlength];delete rules.minlength;delete rules.maxlength;}} return rules;},normalizeRule:function(data){if(typeof data==="string"){var transformed={};$.each(data.split(/\s/),function(){transformed[this]=true;});data=transformed;} return data;},addMethod:function(name,method,message){$.validator.methods[name]=method;$.validator.messages[name]=message!==undefined?message:$.validator.messages[name];if(method.length<3){$.validator.addClassRules(name,$.validator.normalizeRule(name));}},methods:{required:function(value,element,param){if(!this.depend(param,element)){return"dependency-mismatch";} if(element.nodeName.toLowerCase()==="select"){var val=$(element).val();return val&&val.length>0;} if(this.checkable(element)){return this.getLength(value,element)>0;} return value.length>0;},email:function(value,element){return this.optional(element)||/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(value);},url:function(value,element){return this.optional(element)||/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(value);},date:function(value,element){return this.optional(element)||!/Invalid|NaN/.test(new Date(value).toString());},dateISO:function(value,element){return this.optional(element)||/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(value);},number:function(value,element){return this.optional(element)||/^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value);},digits:function(value,element){return this.optional(element)||/^\d+$/.test(value);},minlength:function(value,element,param){var length=$.isArray(value)?value.length:this.getLength(value,element);return this.optional(element)||length>=param;},maxlength:function(value,element,param){var length=$.isArray(value)?value.length:this.getLength(value,element);return this.optional(element)||length<=param;},rangelength:function(value,element,param){var length=$.isArray(value)?value.length:this.getLength(value,element);return this.optional(element)||(length>=param[0]&&length<=param[1]);},min:function(value,element,param){return this.optional(element)||value>=param;},max:function(value,element,param){return this.optional(element)||value<=param;},range:function(value,element,param){return this.optional(element)||(value>=param[0]&&value<=param[1]);},step:function(value,element,param){var type=$(element).attr("type"),errorMessage="Step attribute on input type "+type+" is not supported.",supportedTypes=["text","number","range"],re=new RegExp("\\b"+type+"\\b"),notSupported=type&&!re.test(supportedTypes.join()),decimalPlaces=function(num){var match=(""+num).match(/(?:\.(\d+))?$/);if(!match){return 0;} return match[1]?match[1].length:0;},toInt=function(num){return Math.round(num*Math.pow(10,decimals));},valid=true,decimals;if(notSupported){throw new Error(errorMessage);} decimals=decimalPlaces(param);if(decimalPlaces(value)>decimals||toInt(value)%toInt(param)!==0){valid=false;} return this.optional(element)||valid;},equalTo:function(value,element,param){var target=$(param);if(this.settings.onfocusout&&target.not(".validate-equalTo-blur").length){target.addClass("validate-equalTo-blur").on("blur.validate-equalTo",function(){$(element).valid();});} return value===target.val();},remote:function(value,element,param,method){if(this.optional(element)){return"dependency-mismatch";} method=typeof method==="string"&&method||"remote";var previous=this.previousValue(element,method),validator,data,optionDataString;if(!this.settings.messages[element.name]){this.settings.messages[element.name]={};} previous.originalMessage=previous.originalMessage||this.settings.messages[element.name][method];this.settings.messages[element.name][method]=previous.message;param=typeof param==="string"&&{url:param}||param;optionDataString=$.param($.extend({data:value},param.data));if(previous.old===optionDataString){return previous.valid;} previous.old=optionDataString;validator=this;this.startRequest(element);data={};data[element.name]=value;$.ajax($.extend(true,{mode:"abort",port:"validate"+element.name,dataType:"json",data:data,context:validator.currentForm,success:function(response){var valid=response===true||response==="true",errors,message,submitted;validator.settings.messages[element.name][method]=previous.originalMessage;if(valid){submitted=validator.formSubmitted;validator.resetInternals();validator.toHide=validator.errorsFor(element);validator.formSubmitted=submitted;validator.successList.push(element);validator.invalid[element.name]=false;validator.showErrors();}else{errors={};message=response||validator.defaultMessage(element,{method:method,parameters:value});errors[element.name]=previous.message=message;validator.invalid[element.name]=true;validator.showErrors(errors);} previous.valid=valid;validator.stopRequest(element,valid);}},param));return"pending";}}});var pendingRequests={},ajax;if($.ajaxPrefilter){$.ajaxPrefilter(function(settings,_,xhr){var port=settings.port;if(settings.mode==="abort"){if(pendingRequests[port]){pendingRequests[port].abort();} pendingRequests[port]=xhr;}});}else{ajax=$.ajax;$.ajax=function(settings){var mode=("mode"in settings?settings:$.ajaxSettings).mode,port=("port"in settings?settings:$.ajaxSettings).port;if(mode==="abort"){if(pendingRequests[port]){pendingRequests[port].abort();} pendingRequests[port]=ajax.apply(this,arguments);return pendingRequests[port];} return ajax.apply(this,arguments);};} return $;}));fbuilderjQuery = (typeof fbuilderjQuery != 'undefined' ) ? fbuilderjQuery : jQuery;
fbuilderjQuery(function(){
(function($) {
// Namespace of fbuilder
$.fbuilder = $.fbuilder || {};
$.fbuilder[ 'objName' ] = 'fbuilderjQuery';	
$.fbuilder[ 'controls' ] = ( typeof $.fbuilder[ 'controls' ] != 'undefined' ) ? $.fbuilder[ 'controls' ]: {};
$.fbuilder[ 'forms' ] = ( typeof $.fbuilder[ 'forms' ] != 'undefined' ) ? $.fbuilder[ 'forms' ]: {};
$.fbuilder[ 'htmlEncode' ] = function(value)
{
value = $('<div/>').text(value).html()
value = value.replace( /&/g, '&amp;').replace(/"/g, "&quot;");
return value;
};
$.fbuilder[ 'configValidate' ] = function(elem)
{
elem.validate({
ignore:".ignore,.ignorepb",
errorElement: "div",
errorClass:"cpefb_error",
errorPlacement: function(e, element)
{
if (element.parents(".dfield").find(".cpefb_error.message").not("[style]").length>0)
return;
e.insertAfter(element.parents(".dfield").children().last());
e.addClass("message");
}
});
};
$.fbuilder['htmlDecode']=function(value)
{
if(/&(?:#x[a-f0-9]+|#[0-9]+|[a-z0-9]+);?/ig.test(value))value=$('<div/>').html(value).text();return value;
};
$.fbuilder[ 'escape_symbol' ] = function( value ) // Escape the symbols used in regulars expressions
{
return value.replace(/([\^\$\-\.\,\[\]\(\)\/\\\*\?\+\!\{\}])/g, "\\$1");
};
$.fbuilder[ 'parseValStr' ] = function( value )
{
return '"' + value.replace(/'/g, "\\'").replace( /\$/g, '') + '"';
};
$.fbuilder[ 'parseVal' ] = function( value, thousandSeparator, decimalSymbol )
{
if( value == '' ) return 0;
value += '';
thousandSeparator = new RegExp( $.fbuilder.escape_symbol( ( typeof thousandSeparator == 'undefined' ) ? ',' : thousandSeparator ), 'g' );
decimalSymbol = new RegExp( $.fbuilder.escape_symbol( ( typeof decimalSymbol == 'undefined' ) ? '.' : decimalSymbol ), 'g' );
var t = value.replace( thousandSeparator, '' ).replace( decimalSymbol, '.' ).replace( /\s/g, '' ),
p = /[+-]?((\d+(\.\d+)?)|(\.\d+))/.exec( t );
return ( p ) ? p[0]*1 : $.fbuilder[ 'parseValStr' ]( value );
};
$.fn.fbuilder = function(options){
var opt = $.extend({},
{
pub:false,
identifier:"",
title:""
},options, true);
opt.messages = $.extend({
previous: "Previous",
next: "Next",
pageof: "Page {0} of {0}",
required: "This field is required.",
email: "Please enter a valid email address.",
datemmddyyyy: "Please enter a valid date with this format(mm/dd/yyyy)",
dateddmmyyyy: "Please enter a valid date with this format(dd/mm/yyyy)",
number: "Please enter a valid number.",
digits: "Please enter only digits.",
maxlength: $.validator.format("Please enter no more than {0} characters"),
minlength: $.validator.format("Please enter at least {0} characters."),
equalTo: "Please enter the same value again.",
max: $.validator.format("Please enter a value less than or equal to {0}."),
min: $.validator.format("Please enter a value greater than or equal to {0}.")
},opt.messages);
opt.messages.max = $.validator.format(opt.messages.max);
opt.messages.min = $.validator.format(opt.messages.min);
$.extend($.validator.messages, opt.messages);
var items = [];
var reloadItemsPublic = function()
{
$("#fieldlist"+opt.identifier).closest( 'form' ).addClass( theForm.formtemplate );
$("#fieldlist"+opt.identifier).html("").addClass(theForm.formlayout);
$("#formheader"+opt.identifier).html(theForm.show());
var page = 0;
$("#fieldlist"+opt.identifier).append('<div class="pb'+page+' pbreak" page="'+page+'"></div>');
for (var i=0;i<items.length;i++)
{
items[i].index = i;
if (items[i].ftype=="fPageBreak")
{
page++;
$("#fieldlist"+opt.identifier).append('<div class="pb'+page+' pbreak" page="'+page+'"></div>');
}
else
{
$("#fieldlist"+opt.identifier+" .pb"+page).append(items[i].show());
if (items[i].predefinedClick)
{
$("#fieldlist"+opt.identifier+" .pb"+page).find("#"+items[i].name).attr("placeholder",items[i].predefined);
$("#fieldlist"+opt.identifier+" .pb"+page).find("#"+items[i].name).attr("value","");
}
if (items[i].userhelpTooltip)
{
var uh = $("#fieldlist"+opt.identifier+" .pb"+page).find("#"+items[i].name).closest(".fields");
uh.find(".uh").css("display","none");
if (uh.find(".uh").text()!="")
{
uh.attr("uh",uh.find(".uh").text());
}
}
}
}
if (page>0)
{
$("#fieldlist"+opt.identifier+" .pb"+page).addClass("pbEnd");
$("#fieldlist"+opt.identifier+" .pbreak").each(function(index) {
var code = $(this).html();
var bSubmit = '';
if (index == page)
{
if ( $( "#cpcaptchalayer"+opt.identifier ).length && !/^\s*$/.test( $( "#cpcaptchalayer"+opt.identifier ).html() ) )
{
code += '<div class="captcha">'+$("#cpcaptchalayer"+opt.identifier).html()+'</div><div class="clearer"></div>';
$("#cpcaptchalayer"+opt.identifier).html("");
}
if ($("#cp_subbtn"+opt.identifier).html())
{
bSubmit = '<button type="button" class="pbSubmit">'+$("#cp_subbtn"+opt.identifier).html()+'</button>';
}
}
$(this).html('<fieldset><legend>'+opt.messages.pageof.replace( /\{\s*\d+\s*\}/, (index+1) ).replace( /\{\s*\d+\s*\}/, (page+1) )+'</legend>'+code+'<div class="pbPrevious">'+opt.messages.previous+'</div><div class="pbNext">'+opt.messages.next+'</div>'+bSubmit+'<div class="clearer"></div></fieldset>');
});
$( '#fieldlist'+opt.identifier).find(".pbPrevious,.pbNext").bind("click", { 'identifier' : opt.identifier }, function( evt ) {
var identifier = evt.data.identifier;
function focusTop(){try {$('html, body').animate({scrollTop: $("#fieldlist"+identifier+" .pb"+page).find("fieldset").offset().top}, 100);}catch(e){}}
if (  ($(this).hasClass("pbPrevious")) || (($(this).hasClass("pbNext")) && $(this).parents("form").valid())  )
{
var page = parseInt($(this).parents(".pbreak").attr("page"));
(($(this).hasClass("pbPrevious"))?page--:page++);
$("#fieldlist"+identifier+" .pbreak").css("display","none");
$("#fieldlist"+identifier+" .pbreak").find(".field").addClass("ignorepb");
$("#fieldlist"+identifier+" .pb"+page).css("display","block");
$("#fieldlist"+identifier+" .pb"+page).find(".field").removeClass("ignorepb");
if ($("#fieldlist"+identifier+" .pb"+page).find(".field").length>0)
{
try
{
if ($("#fieldlist"+identifier+" .pb"+page).find(".field").is(":visible"))
{
var f1 = $("#fieldlist"+identifier+" .pb"+page).find(".field:visible");
if (f1.parents("fieldset").parents("#fieldlist"+identifier+" .pb"+page).length>0)
focusTop();
else
f1[0].focus();
}
else
focusTop();
}
catch(e){focusTop()}
}
else
focusTop();
}
else
{
$(this).parents("form").validate().focusInvalid();
}
return false;
});
}
else
{
if ( $( "#cpcaptchalayer"+opt.identifier ).length && !/^\s*$/.test( $( "#cpcaptchalayer"+opt.identifier ).html() ) )
{
$("#fieldlist"+opt.identifier+" .pb"+page).append('<div class="captcha">'+$("#cpcaptchalayer"+opt.identifier).html()+'</div>');
$("#cpcaptchalayer"+opt.identifier).html("");
}
if ($("#cp_subbtn"+opt.identifier).html())
{
$("#fieldlist"+opt.identifier+" .pb"+page).append('<button type="button" class="pbSubmit">'+$("#cp_subbtn"+opt.identifier).html()+'</button>');
}
}
// Set Captcha Event
$( document ).on( 'click', '#fbuilder .captcha img', function(){ var e = $( this ); e.attr( 'src', e.attr( 'src' ).replace( /&\d+$/, '' ) + '&' + Math.floor( Math.random()*1000 ) ); } );
$( document ).on("click","#fieldlist"+opt.identifier+" .pbSubmit", function( evt )
{
$("#fieldlist"+opt.identifier+" .pbSubmit").closest("form").submit();
});
if (i>0)
{
theForm.after_show( opt.identifier );
for (var i=0;i<items.length;i++)
{
items[i].after_show();
}
$.fbuilder.showHideDep(
{
'formIdentifier' : opt.identifier,
'throwEvent'	 : true
}
);
$( '#fieldlist'+opt.identifier).find(".depItemSel,.depItem").bind("change", { 'identifier' : opt.identifier }, function( evt )
{
$.fbuilder.showHideDep(
{
'formIdentifier' : evt.data.identifier,
'throwEvent'	 : true
}
);
});
try
{
$( "#fbuilder"+opt.identifier ).tooltip({show: false,hide:false,tooltipClass:"uh-tooltip",position: { my: "left top", at: "left bottom+5", collision: "none"  },items: "[uh]",content: function (){return $(this).attr("uh");} });
} catch(e){}
}
$("#fieldlist"+opt.identifier+" .pbreak:not(.pb0)").find(".field").addClass("ignorepb");
if ( theForm.autofocus)
{
var ff  = $("#fieldlist"+opt.identifier+" .pbreak.pb0").find(":focusable:first");
if( ff &&
ff.attr('type') != 'radio' &&
ff.attr('type') != 'checkbox' &&
ff.closest('[uh]').length == 0 ) ff.focus();
}
};
var fform=function(){};
$.extend(fform.prototype,
{
title:"Untitled Form",
description:"This is my form. Please fill it out. It's awesome!",
formlayout:"top_aligned",
formtemplate:"",
evalequations:1,
autocomplete:1,
autofocus:false,
show:function(){
return '<div class="fform" id="field">'+(this.title!=''?'<h1>'+this.title+'</h1>':'')+(this.description!=''?'<span>'+this.description+'</span>':'')+'</div>';
},
after_show:function( id ){
$( '#cp_calculatedfieldsf_pform'+id ).attr( 'data-evalequations', this.evalequations ).attr( 'autocomplete', ( ( this.autocomplete ) ? 'on' : 'off' ) );
}
});
//var theForm = new fform(),
var theForm,
ffunct = {
getItem: function( name )
{
for( var i in items )
{
if( items[ i ].name == name )
{
return items[ i ];
}
}
return false;
},
getItems: function()
{
return items;
},
loadData:function(f)
{
var d,
e = $("#"+f);
this.formId = e.parents( 'form' ).attr( 'id' );
if ( d = $.parseJSON( e.val() ))
{
if (d.length==2)
{
items = [];
for (var i=0;i<d[0].length;i++)
{
var obj = eval("new $.fbuilder.controls['"+d[0][i].ftype+"']();");
obj = $.extend(true, {}, obj,d[0][i]);
obj.name = obj.name+opt.identifier;
obj.form_identifier = opt.identifier;
obj.init();
items[items.length] = obj;
}
theForm = new fform();
theForm = $.extend(theForm,d[1][0]);
reloadItemsPublic();
}
}
if( typeof window[ 'cpcff_load_defaults' ] != 'undefined' )
{
window[ 'cpcff_load_defaults' ]();
}
}
};
$.fbuilder[ 'forms' ][ opt.identifier ] = ffunct;
this.fBuild = ffunct;
return this;
};
$.fbuilder[ 'showSettings' ] = {
formlayoutList : [{id:"top_aligned",name:"Top Aligned"},{id:"left_aligned",name:"Left Aligned"},{id:"right_aligned",name:"Right Aligned"},{id:"center_aligned",name:"Center Aligned"}]
};
$.fbuilder.controls[ 'ffields' ] = function(){};
$.extend($.fbuilder.controls[ 'ffields' ].prototype,
{
form_identifier:"",
name:"",
shortlabel:"",
index:-1,
ftype:"",
userhelp:"",
userhelpTooltip:false,
csslayout:"",
init:function(){},
_getAttr:function(attr)
{
var me = this, f, v = $.trim(me[attr]);
if($.isNumeric(v)) return parseFloat(v);
f = (/^fieldname\d+$/i.test(v)) ? me.getField(v) : false;
if(f)
{
v = f.val();
if(f.ftype == 'fdate') return new Date(v*86400000);
if($.isNumeric(v)) return parseFloat(v);
return v.replace(/^"+/, '').replace(/"+$/, '');
}
return v;
},
_setHndl:function(attr, one)
{
var me = this, v = $.trim(me[attr]);
if($.isNumeric(v)) return;
var s = (/^fieldname\d+$/i.test(v)) ? '[id*="'+v+me.form_identifier+'"]' : v,
i = (one) ? 'one' : 'on';
if('string' == typeof s && !/^\s*$/.test(s))
{
s = $.trim(s);
if(!$.isNumeric(s.charAt(0)))
{
$(document)[i]('change depEvent', s, function(evt){
if(me['set_'+attr]) me['set_'+attr](me._getAttr(attr), $(evt.target).hasClass('ignore'));
});
}
}
},
getField: function(f){return $.fbuilder['forms'][this.form_identifier].getItem(f);},
show:function()
{
return 'Not available yet';
},
after_show:function(){},
val:function(){
var e = $( "[id='" + this.name + "']:not(.ignore)" );
if( e.length )
{
return $.fbuilder.parseVal( $.trim( e.val() ) );
}
return 0;
}
});
$.fbuilder[ 'showHideDep' ] = function( configObj )
{
if( typeof configObj[ 'formIdentifier' ] !== 'undefined' )
{
var identifier = configObj[ 'formIdentifier' ];
if( typeof  $.fbuilder[ 'forms' ][ identifier ] != 'undefined' )
{
var toShow = [],
toHide = [],
items = $.fbuilder[ 'forms' ][ identifier ].getItems();
for( var i = 0, h = items.length; i < h; i++ )
{
if( typeof items[ i ][ 'showHideDep' ] != 'undefined' )
{
items[ i ][ 'showHideDep' ]( toShow, toHide );
}
}
if( typeof configObj[ 'throwEvent' ] == 'undefined' || configObj[ 'throwEvent' ] )
{
$( document ).trigger( 'showHideDepEvent', $.fbuilder[ 'forms' ][ identifier ][ 'formId' ] );
}
}
}
};
$.fbuilder.controls[ 'ftext' ]=function(){};
$.extend(
$.fbuilder.controls[ 'ftext' ].prototype,
$.fbuilder.controls[ 'ffields' ].prototype,
{
title:"Untitled",
ftype:"ftext",
predefined:"",
predefinedClick:false,
required:false,
size:"medium",
minlength:"",
maxlength:"",
equalTo:"",
show:function()
{
return '<div class="fields '+this.csslayout+'" id="field'+this.form_identifier+'-'+this.index+'"><label for="'+this.name+'">'+this.title+''+((this.required)?"<span class='r'>*</span>":"")+'</label><div class="dfield"><input id="'+this.name+'" name="'+this.name+'" '+((this.minlength!="")?" minlength=\""+parseInt(this.minlength)+"\"":"")+' '+((this.maxlength!="")?" maxlength=\""+parseInt(this.maxlength)+"\"":"")+'  '+((this.equalTo!="")?"equalTo=\"#"+$.fbuilder.htmlEncode(this.equalTo+this.form_identifier)+"\"":"" )+' class="field '+this.size+((this.required)?" required":"")+'" type="text" value="'+$.fbuilder.htmlEncode(this.predefined)+'"/><span class="uh">'+this.userhelp+'</span></div><div class="clearer"></div></div>';
}
}	
);	$.fbuilder.controls[ 'fcurrency' ] = function(){};
$.extend( 
$.fbuilder.controls[ 'fcurrency' ].prototype, 
$.fbuilder.controls[ 'ffields' ].prototype,
{
title:"Currency",
ftype:"fcurrency",
predefined:"",
predefinedClick:false,
required:false,
size:"small",
readonly:false,
currencyText:"USD",
thousandSeparator:",",
centSeparator:".",
min:"",
max:"",
formatDynamically:false,
getFormattedValue:function( value )
{
this.centSeparator = $.trim(this.centSeparator);	
if( /^\s*$/.test( this.centSeparator ) )
{
this.centSeparator = '.';
}
var v = $.trim( value );
v = v.replace( new RegExp( $.fbuilder[ 'escape_symbol' ](this.currencySymbol), 'g' ), '' )
.replace( new RegExp( $.fbuilder[ 'escape_symbol' ](this.currencyText), 'g' ), '' );
v = $.fbuilder.parseVal( v, this.thousandSeparator, this.centSeparator );	 
if( !isNaN( v ) )
{
v = v.toString();
var parts = v.toString().split("."),
counter = 0,
str = '';
if( !/^\s*$/.test( this.thousandSeparator ) )
{
for( var i = parts[0].length-1; i >= 0; i--){
counter++;
str = parts[0][i] + str;
if( counter%3 == 0 && i != 0 ) str = this.thousandSeparator + str;
}
parts[0] = str;
}
if( typeof parts[ 1 ] != 'undefined' && parts[ 1 ].length == 1 )
{
parts[ 1 ] += '0';
}
if( /^\s*$/.test( this.centSeparator ) )
{
this.centSeparator = '.';
}
return this.currencySymbol+parts.join( this.centSeparator )+this.currencyText;
}
else
{
return value;
}
},	
show:function()
{
return '<div class="fields '+this.csslayout+'" id="field'+this.form_identifier+'-'+this.index+'"><label for="'+this.name+'">'+this.title+''+((this.required)?"<span class='r'>*</span>":"")+'</label><div class="dfield"><input '+(( this.readonly )? 'READONLY' : '' )+' id="'+this.name+'" name="'+this.name+'" class="field '+this.dformat+' '+this.size+((this.required)?" required":"")+'" type="text" value="'+$.fbuilder.htmlEncode( this.getFormattedValue( this.predefined ) )+'" '+( ( !/^\s*$/.test( this.min) ) ? 'min="'+$.fbuilder.parseVal( this.min, this.thousandSeparator, this.centSeparator )+'" ' : '' )+( ( !/^\s*$/.test( this.max) ) ? ' max="'+$.fbuilder.parseVal( this.max, this.thousandSeparator, this.centSeparator )+'" ' : '' )+' /><span class="uh">'+this.userhelp+'</span></div><div class="clearer"></div></div>';
},
after_show:function()
{
if( this.formatDynamically )
{
var me = this;
$( document ).on( 'change', '[name="' + me.name + '"]', function(){
this.value = me.getFormattedValue( this.value );
} );
}
if( typeof $[ 'validator' ] != 'undefined' )
{
$.validator.addMethod( 'min', function( value, element, param ) 
{
var e = element;
if( element.id.match( /_\d+$/) )
{
var e = $.fbuilder[ 'forms' ][ element.id.match( /_\d+$/)[ 0 ] ].getItem( element.name )
}
var thousandSeparator = ( typeof e.thousandSeparator != 'undefined' ) ? e.thousandSeparator : '',
centSymbol = ( typeof e.centSeparator != 'undefined' && $.trim( e.centSeparator ) ) ? e.centSeparator : '.';
return this.optional(element) || $.fbuilder.parseVal( value, thousandSeparator, centSymbol ) >= param;
}
);
$.validator.addMethod( 'max', function( value, element, param ) 
{
var e = element;
if( element.id.match( /_\d+$/) )
{
var e = $.fbuilder[ 'forms' ][ element.id.match( /_\d+$/)[ 0 ] ].getItem( element.name )
}
var thousandSeparator = ( typeof e.thousandSeparator != 'undefined' ) ? e.thousandSeparator : '',
centSymbol = ( typeof e.centSeparator != 'undefined' && $.trim( e.centSeparator ) ) ? e.centSeparator : '.';
return this.optional(element) || $.fbuilder.parseVal( value, thousandSeparator, centSymbol ) <= param;
}
);
}
},
val:function()
{
var e = $( '[id="' + this.name + '"]:not(.ignore)' );
if( e.length )
{
var v = $.trim( e.val() );
v = v.replace( new RegExp( $.fbuilder[ 'escape_symbol' ](this.currencySymbol), 'g' ), '' )
.replace( new RegExp( $.fbuilder[ 'escape_symbol' ](this.currencyText), 'g' ), '' );
return $.fbuilder.parseVal( v, this.thousandSeparator, this.centSeparator );	 
}
return 0;
}	
}
);	$.fbuilder.controls[ 'fnumber' ] = function(){};
$.extend( 
$.fbuilder.controls[ 'fnumber' ].prototype, 
$.fbuilder.controls[ 'ffields' ].prototype,
{
title:"Number",
ftype:"fnumber",
predefined:"",
predefinedClick:false,
required:false,
size:"small",
thousandSeparator:"",
decimalSymbol:".",
min:"",
max:"",
dformat:"digits",
formats:new Array("digits","number"),
show:function()
{
return '<div class="fields '+this.csslayout+'" id="field'+this.form_identifier+'-'+this.index+'"><label for="'+this.name+'">'+this.title+''+((this.required)?"<span class='r'>*</span>":"")+'</label><div class="dfield"><input id="'+this.name+'" name="'+this.name+'" '+( ( !/^\s*$/.test( this.min) ) ? 'min="'+$.fbuilder.parseVal( this.min, this.thousandSeparator, this.decimalSymbol )+'" ' : '' )+( ( !/^\s*$/.test( this.max) ) ? ' max="'+$.fbuilder.parseVal( this.max, this.thousandSeparator, this.decimalSymbol )+'" ' : '' )+' class="field '+this.dformat+' '+this.size+((this.required)?" required":"")+'" type="text" value="'+$.fbuilder.htmlEncode(this.predefined)+'"/><span class="uh">'+this.userhelp+'</span></div><div class="clearer"></div></div>';
},
after_show:function()
{
if( typeof $[ 'validator' ] != 'undefined' )
{
$.validator.addMethod( 'number', function( value, element )
{
var e = element;
if( element.id.match( /_\d+$/) )
{
var e = $.fbuilder[ 'forms' ][ element.id.match( /_\d+$/)[ 0 ] ].getItem( element.name )
}
var thousandSeparator = ( typeof e.thousandSeparator != 'undefined' ) ? e.thousandSeparator : '',
decimalSymbol = ( typeof e.decimalSymbol != 'undefined' && $.trim( e.decimalSymbol ) ) ? e.decimalSymbol : '.';
var regExp = new RegExp( '^-?(?:\\d+|\\d{1,3}(?:' + $.fbuilder.escape_symbol( thousandSeparator ) + '\\d{3})+)?(?:' + $.fbuilder.escape_symbol( decimalSymbol ) + '\\d+)?$' );
return this.optional(element) || regExp.test( value );
}
);
$.validator.addMethod( 'min', function( value, element, param ) 
{
var e = element;
if( element.id.match( /_\d+$/) )
{
var e = $.fbuilder[ 'forms' ][ element.id.match( /_\d+$/)[ 0 ] ].getItem( element.name )
}
var thousandSeparator = ( typeof e.thousandSeparator != 'undefined' ) ? e.thousandSeparator : '',
decimalSymbol = ( typeof e.decimalSymbol != 'undefined' && $.trim( e.decimalSymbol ) ) ? e.decimalSymbol : '.';
return this.optional(element) || $.fbuilder.parseVal( value, thousandSeparator, decimalSymbol ) >= param;
}
);
$.validator.addMethod( 'max', function( value, element, param ) 
{
var e = element;
if( element.id.match( /_\d+$/) )
{
var e = $.fbuilder[ 'forms' ][ element.id.match( /_\d+$/)[ 0 ] ].getItem( element.name )
}
var thousandSeparator = ( typeof e.thousandSeparator != 'undefined' ) ? e.thousandSeparator : '',
decimalSymbol = ( typeof e.decimalSymbol != 'undefined' && $.trim( e.decimalSymbol ) ) ? e.decimalSymbol : '.';
return this.optional(element) || $.fbuilder.parseVal( value, thousandSeparator, decimalSymbol ) <= param;
}
);
}
},
val:function()
{
var e = $( '[id="' + this.name + '"]:not(.ignore)' );
if( e.length )
{
var v = $.trim( e.val() );
return $.fbuilder.parseVal( v, this.thousandSeparator, this.decimalSymbol );	 
}
return 0;
}		
}
);	$.fbuilder.controls[ 'femail' ] = function(){};
$.extend( 
$.fbuilder.controls[ 'femail' ].prototype, 
$.fbuilder.controls[ 'ffields' ].prototype,
{
title:"Email",
ftype:"femail",
predefined:"",
predefinedClick:false,
required:false,
size:"medium",
equalTo:"",
show:function()
{
return '<div class="fields '+this.csslayout+'" id="field'+this.form_identifier+'-'+this.index+'"><label for="'+this.name+'">'+this.title+''+((this.required)?"<span class='r'>*</span>":"")+'</label><div class="dfield"><input id="'+this.name+'" name="'+this.name+'" '+((this.equalTo!="")?"equalTo=\"#"+$.fbuilder.htmlEncode(this.equalTo+this.form_identifier)+"\"":"" )+' class="field email '+this.size+((this.required)?" required":"")+'" type="text" value="'+$.fbuilder.htmlEncode(this.predefined)+'"/><span class="uh">'+this.userhelp+'</span></div><div class="clearer"></div></div>';
},
val:function()
{
var e = $( '[id="' + this.name + '"]:not(.ignore)' );
if( e.length ) return $.fbuilder.parseValStr( e.val() );
return '';
}	
}
);	$.fbuilder.controls[ 'fdate' ] = function(){};
$.extend(
$.fbuilder.controls[ 'fdate' ].prototype,
$.fbuilder.controls[ 'ffields' ].prototype,
{
title:"Date",
ftype:"fdate",
predefined:"",
predefinedClick:false,
size:"medium",
required:false,
dformat:"mm/dd/yyyy",
dseparator:"/",
tformat:"24",
showDropdown:false,
dropdownRange:"-10:+10",
minDate:"",
maxDate:"",
invalidDates:"",
minHour:0,
maxHour:23,
minMinute:0,
maxMinute:59,
stepHour: 1,
stepMinute: 1,
showDatepicker: true,
showTimepicker: false,
ariaHourLabel: 'hours',
ariaMinuteLabel: 'minutes',
ariaAMPMLabel: 'am or pm',
defaultDate:"",
defaultTime:"",
working_dates:[true,true,true,true,true,true,true],
_set_Events : function()
{
var me = this,
f  = function(){
$( '#'+me.name+'_date' ).valid();
me.set_dateTime();
};
$( document ).on( 'change', '#'+me.name+'_date', 	function(){ f(); } );
$( document ).on( 'change', '#'+me.name+'_hours',   function(){ f(); } );
$( document ).on( 'change', '#'+me.name+'_minutes', function(){ f(); } );
$( document ).on( 'change', '#'+me.name+'_ampm', 	function(){ f(); } );
$( '#cp_calculatedfieldsf_pform'+me.form_identifier ).bind( 'reset', function(){ setTimeout( function(){ me.set_DefaultDate(); me.set_DefaultTime(); me.set_dateTime(); }, 500 ); } );
},
_validateDate: function( d, w, i )
{
try{
if( d === null || !w[ d.getDay()] ) return false;
if( i !== null )
{
for( var j = 0, h = i.length; j < h; j++ )
{
if( d.getDate() == i[ j ].getDate() && d.getMonth() == i[ j ].getMonth() && d.getFullYear() == i[ j ].getFullYear() ) return false;
}
}
}
catch( _err ){}
return true;
},
_validateTime : function( e, i )
{
if( i.showTimepicker )
{
var base = e.name.replace( '_date', '' ),
h = $('#'+base+'_hours').val(),
m = $('#'+base+'_minutes').val();
if( i.tformat == 12 )
{
if( $('#'+base+'_ampm').val() == 'pm' && h != 12 ) h = h*1 + 12;
if( $('#'+base+'_ampm').val() == 'am' && h == 12 ) h = 0;
}
if(
h < i.minHour ||
i.maxHour < h ||
(h == i.minHour && m < i.minMinute) ||
(h == i.maxHour && i.maxMinute < m)
) return false;
}
return true;
},
init:function()
{
var me 			= this,
_checkValue = function( v, min, max )
{
v = parseInt( v );
v = ( isNaN( v ) ) ? max : v;
return Math.min(Math.max(v,min),max);
};
// Date
me.dformat		= me.dformat.replace(/\//g, me.dseparator);
me.invalidDates = me.invalidDates.replace( /\s+/g, '' );
if( me.dropdownRange.indexOf( ':' ) == -1 ) me.dropdownRange = '-10:+10';
if( !/^\s*$/.test( me.invalidDates ) )
{
var	dateRegExp = new RegExp( /^\d{1,2}\/\d{1,2}\/\d{4}$/ ),
counter = 0,
dates = me.invalidDates.split( ',' );
me.invalidDates = [];
for( var i = 0, h = dates.length; i < h; i++ )
{
var range = dates[ i ].split( '-' );
if( range.length == 2 && range[0].match( dateRegExp ) != null && range[1].match( dateRegExp ) != null )
{
var fromD = new Date( range[ 0 ] ),
toD = new Date( range[ 1 ] );
while( fromD <= toD )
{
me.invalidDates[ counter ] = fromD;
var tmp = new Date( fromD.valueOf() );
tmp.setDate( tmp.getDate() + 1 );
fromD = tmp;
counter++;
}
}
else
{
for( var j = 0, k = range.length; j < k; j++ )
{
if( range[ j ].match( dateRegExp ) != null )
{
me.invalidDates[ counter ] = new Date( range[ j ] );
counter++;
}
}
}
}
}
// Time
me.minHour 		= _checkValue( me.minHour, 0, 23 );
me.maxHour 		= _checkValue( me.maxHour, 0, 23 );
me.minMinute 	= _checkValue( me.minMinute, 0, 59 );
me.maxMinute 	= _checkValue( me.maxMinute, 0, 59 );
me.stepHour 	= _checkValue( me.stepHour, 1, Math.max( 1, me.maxHour - me.minHour ) );
me.stepMinute 	= _checkValue( me.stepMinute, 1, Math.max( 1, me.maxMinute - me.minMinute ) );
// Set handles
me._setHndl('minDate');
me._setHndl('maxDate');
},
get_hours:function()
{
var me = this,
str = '',
i = 0,
h,
from = ( me.tformat == 12 ) ? 1  : me.minHour,
to   = ( me.tformat == 12 ) ? 12 : me.maxHour;
while( ( h = from + me.stepHour * i ) <= to )
{
if( h < 10 ) h = '0'+''+h;
str += '<option value="' + h + '">' + h + '</option>';
i++;
}
return '<select id="'+me.name+'_hours" name="'+me.name+'_hours" class="hours-component" aria-label="'+$.fbuilder.htmlEncode(me.ariaHourLabel)+'">' + str + '</select>:';
},
get_minutes:function()
{
var me = this,
str = '',
i = 0,
m,
n = (me.minHour == me.maxHour)?me.minMinute : 0,
x = (me.minHour == me.maxHour)?me.maxMinute : 59;
while( ( m = n + me.stepMinute * i ) <= x )
{
if( m < 10 ) m = '0'+''+m;
str += '<option value="' + m + '">' + m + '</option>';
i++;
}
return '<select id="'+me.name+'_minutes" name="'+me.name+'_minutes" class="minutes-component" aria-label="'+$.fbuilder.htmlEncode(me.ariaMinuteLabel)+'">' + str + '</select>';
},
get_ampm:function()
{
var str = '';
if( this.tformat == 12 )
{
return '<select id="'+this.name+'_ampm" class="ampm-component"  aria-label="'+$.fbuilder.htmlEncode(this.ariaAMPMLabel)+'"><option value="am">am</option><option value="pm">pm</option></select>';
}
return str;
},
set_dateTime:function()
{
var me = this,
str = $( '#'+me.name+'_date' ).val();
if( me.showTimepicker && str!="")
{
str += ' '+$( '#'+me.name+'_hours' ).val();
str += ':'+$( '#'+me.name+'_minutes' ).val();
if( $( '#'+me.name+'_ampm' ).length ) str += $( '#'+me.name+'_ampm' ).val();
}
$( '#'+me.name ).val( str ).change();
},
set_minDate:function(v, ignore)
{
var e = $('[id*="'+this.name+'"].hasDatepicker');
if(e.length)
{
e.datepicker('option', 'minDate', (ignore) ? null : v);
e.change();
}
},
set_maxDate:function(v, ignore)
{
var e = $('[id*="'+this.name+'"].hasDatepicker');
if(e.length)
{
e.datepicker('option', 'maxDate', (ignore) ? null : v);
e.change();
}
},
set_DefaultDate : function()
{
var me = this,
p  = {
dateFormat: me.dformat.replace(/yyyy/g,"yy"),
minDate: me._getAttr('minDate'),
maxDate: me._getAttr('maxDate')
},
dp = $( "#"+me.name+"_date" ),
dd = (me.defaultDate != "") ? me.defaultDate : ( ( me.predefined != "" ) ? me.predefined : new Date() );
dp.click( function(){ $(document).click(); $(this).focus(); } );
if(me.showDropdown ) p = $.extend(p,{changeMonth: true,changeYear: true,yearRange: me.dropdownRange});
p = $.extend(p, {beforeShowDay:(function(w,i) { return function(d){return [me._validateDate(d, w, i), ""];};})(me.working_dates, me.invalidDates)});
dp.datepicker(p);
if(!me.predefinedClick) dp.datepicker( "setDate", dd);
if(!me._validateDate(dp.datepicker("getDate"), me.working_dates, me.invalidDates)) dp.datepicker( "setDate", '');
},
set_DefaultTime : function()
{
var me 			= this,
_setValue 	= function( f, v, m )
{
v = Math.min( v*1, m*1 );
v = ( v < 10 ) ? 0+''+v : v;
$( '#' + f + ' [value="' + v + '"]' ).prop( 'selected', true );
};
if( me.showTimepicker )
{
var parts, time = {}, tmp = 0, max_minutes = 59;
if( ( parts = /(\d{1,2}):(\d{1,2})\s*([ap]m)?/gi.exec( me.defaultTime ) ) != null )
{
time[ 'hour' ] = parts[ 1 ]*1+((parts.length == 4 && /pm/i.test(parts[3]) && parts[1] != 12) ? 12 : 0);
time[ 'minute' ] = parts[ 2 ];
}
else
{
var d = new Date();
time[ 'hour' ] = d.getHours();
time[ 'minute' ] = d.getMinutes();
}
time[ 'hour' ] = Math.min(Math.max(time[ 'hour' ], me.minHour), me.maxHour);
if(time[ 'hour' ] <= me.minHour) time[ 'minute' ] = Math.max(time['minute'],me.minMinute);
if(me.maxHour <= time[ 'hour' ]) time[ 'minute' ] = Math.min(time['minute'],me.maxMinute);
_setValue(
me.name+'_hours',
( me.tformat == 12 ) ? ( ( time[ 'hour' ] > 12 ) ? time[ 'hour' ] - 12 : ( ( time[ 'hour' ] == 0 ) ? 12 : time[ 'hour' ] ) ) : time[ 'hour' ],
( me.tformat == 12 ) ? 12 : me.maxHour
);
_setValue( me.name+'_minutes', time[ 'minute' ], (time[ 'hour' ] == me.maxHour) ? me.maxMinute : 59);
$( '#'+me.name+'_ampm'+' [value="' + ( ( time[ 'hour' ] < 12 ) ? 'am' : 'pm' ) + '"]' ).prop( 'selected', true );
}
},
show:function()
{
var me				= this,
n 				= me.name,
attr 			= 'value',
format_label   	= [],
date_tag_type  	= 'text',
disabled		= '',
date_tag_class 	= 'field date'+me.dformat.replace(/[^a-z]/ig,"")+' '+me.size+((me.required && me.showDatepicker)?' required': '');
if( me.predefinedClick ) attr = 'placeholder';
if( me.showDatepicker ) format_label.push(me.dformat);
else{ date_tag_type = 'hidden'; disabled='disabled';}
if( me.showTimepicker ) format_label.push('HH:mm');
return '<div class="fields '+me.csslayout+' '+n+' cff-date-field" id="field'+me.form_identifier+'-'+me.index+'"><label for="'+n+'_date">'+me.title+''+((me.required)?"<span class='r'>*</span>":"")+( (format_label.length) ? ' <span class="dformat">('+format_label.join(' ')+')</span>' : '' )+'</label><div class="dfield"><input id="'+n+'" name="'+n+'" type="hidden" value="'+$.fbuilder.htmlEncode(me.predefined)+'"/><input id="'+n+'_date" name="'+n+'_date" class="'+date_tag_class+' date-component" type="'+date_tag_type+'" '+attr+'="'+$.fbuilder.htmlEncode(me.predefined)+'" '+disabled+' />'+( ( me.showTimepicker ) ? ' '+me.get_hours()+me.get_minutes()+' '+me.get_ampm() : '' )+'<span class="uh">'+me.userhelp+'</span></div><div class="clearer"></div></div>';
},
after_show:function()
{
function closeOtherDatepicker(){
$('#ui-datepicker-div').css("display","none");
}
setTimeout(closeOtherDatepicker,100);
var me = this,
date_format = 'date'+me.dformat.replace(/[^a-z]/ig,""),
validator = function( v, e )
{
try
{
var _dp			= $.datepicker,
_fb			= $.fbuilder,
p           = e.name.replace('_date', '').split('_'),
_index		= (p.length > 1) ? '_'+p[ 1 ] : '',
item        = ('forms' in _fb && _index in _fb[ 'forms' ])
? _fb[ 'forms' ][ _index ].getItem(p[ 0 ]+'_'+p[ 1 ]) : null,
inst        = _dp._getInst( e ),
minDate     = _dp._determineDate( inst, _dp._get( inst, 'minDate'), null),
maxDate     = _dp._determineDate(inst, _dp._get(inst, 'maxDate'), null),
dateFormat  = _dp._get(inst, 'dateFormat'),
date        = _dp.parseDate(dateFormat, v, _dp._getFormatConfig(inst));
if( item != null )
{
return 	this.optional( e ) ||
(
( minDate == null || date >= minDate  ) &&
( maxDate == null || date <= maxDate ) &&
item._validateDate( $( e ).datepicker( 'getDate' ), item.working_dates, item.invalidDates ) &&
item._validateTime( e, item )
);
}
return true;
}
catch( er )
{
return false;
}
};
if(!(date_format in $.validator.methods)) $.validator.addMethod(date_format, validator );
me.set_DefaultDate();
me.set_DefaultTime();
me._set_Events();
me.set_dateTime();
},
val:function(raw)
{
raw = raw || false;
var me = this,
e  = $( '[id="' + me.name + '"]:not(.ignore)' ),
dformat = me.dformat.replace(new RegExp('\\'+me.dseparator, 'g'), '/');
if( e.length )
{
var v  = e.val(), rt;
if(raw) return $.fbuilder.parseValStr(v, raw);
if( dformat == 'yyyy/mm/dd' || dformat == 'yyyy/dd/mm' )
rt = '(\\d{4})[\\/\\-\\.](\\d{1,2})[\\/\\-\\.](\\d{1,2})';
else
rt = '(\\d{1,2})[\\/\\-\\.](\\d{1,2})[\\/\\-\\.](\\d{4})';
v  = $.trim(e.val());
var re = new RegExp( rt+'(\\s(\\d{1,2})[:\\.](\\d{1,2})\s*([amp]{2})?)?' ),
d  = re.exec( v ),
h  = 0,
m  = 0,
date;
if( d )
{
if( typeof d[ 5 ] != 'undefined' ) h = d[ 5 ]*1;
if( typeof d[ 6 ] != 'undefined' ) m = d[ 6 ]*1;
if( typeof d[ 7 ] != 'undefined' )
{
var am = d[ 7 ].toLowerCase();
if(am == 'pm' && h < 12 ) h += 12;
if(am == 'am' && h == 12) h -= 12;
}
switch( dformat )
{
case 'yyyy/dd/mm':
date = new Date( d[ 1 ], ( d[ 3 ] * 1 - 1 ), d[ 2 ], h, m, 0, 0 );
break;
case 'yyyy/mm/dd':
date = new Date( d[ 1 ], ( d[ 2 ] * 1 - 1 ), d[ 3 ], h, m, 0, 0 );
break;
case 'dd/mm/yyyy':
date = new Date( d[ 3 ], ( d[ 2 ] * 1 - 1 ), d[ 1 ], h, m, 0, 0 );
break;
case 'mm/dd/yyyy':
date = new Date( d[ 3 ], ( d[ 1 ] * 1 - 1 ), d[ 2 ], h, m, 0, 0 );
break;
}
if( me.showTimepicker ) return date.valueOf() / 86400000;
else return Math.ceil( date.valueOf() / 86400000 );
}
}
return 0;
},
setVal:function( v )
{
try
{
v = $.trim(v)
.replace( /\s+/g, ' ' )
.split( ' ' );
if(this.showDatepicker)
{
this.defaultDate = v[ 0 ];
this.set_DefaultDate();
}
if(this.showTimepicker)
{
var t = (v.length == 2) ? v[1] : ((!this.showDatepicker) ? v[0] : false);
if(t !== false)
{
this.defaultTime = t;
this.set_DefaultTime();
}
}
this.set_dateTime();
}
catch( err )
{}
}
}
);	$.fbuilder.controls[ 'ftextarea' ] = function(){};
$.extend(
$.fbuilder.controls[ 'ftextarea' ].prototype, 
$.fbuilder.controls[ 'ffields' ].prototype,
{
title:"Untitled",
ftype:"ftextarea",
predefined:"",
predefinedClick:false,
required:false,
size:"medium",
minlength:"",
maxlength:"",
rows:4,
show:function()
{
return '<div class="fields '+this.csslayout+'" id="field'+this.form_identifier+'-'+this.index+'"><label for="'+this.name+'">'+this.title+''+((this.required)?"<span class='r'>*</span>":"")+'</label><div class="dfield"><textarea '+((!/^\s*$/.test(this.rows)) ? 'rows='+this.rows : '' )+' id="'+this.name+'" name="'+this.name+'" minlength="'+(this.minlength)+'" maxlength="'+$.fbuilder.htmlEncode(this.maxlength)+'" class="field '+this.size+((this.required)?" required":"")+'" '+(!this.predefinedClick?' placeholder="'+$.fbuilder.htmlEncode(this.predefined)+'"':'')+'>'+(!this.predefinedClick?this.predefined:'')+'</textarea><span class="uh">'+this.userhelp+'</span></div><div class="clearer"></div></div>';
},
val:function()
{
var e = $( '[id="' + this.name + '"]:not(.ignore)' ),
v = '';
if( e.length )
{
v = e.val();
}
return v;	
}	
}
);	$.fbuilder.controls[ 'fcheck' ]=function(){};
$.extend(
$.fbuilder.controls[ 'fcheck' ].prototype, 
$.fbuilder.controls[ 'ffields' ].prototype,
{
title:"Check All That Apply",
ftype:"fcheck",
layout:"one_column",
required:false,
showDep:false,
show:function()
{
this.choicesVal = ((typeof(this.choicesVal) != "undefined" && this.choicesVal !== null)?this.choicesVal:this.choices.slice(0));
var str = "";
if (!(typeof(this.choicesDep) != "undefined" && this.choicesDep !== null))
{
this.choicesDep = new Array();
for (var i=0;i<this.choices.length;i++)
{
this.choicesDep[i] = new Array();
}	
}
for (var i=0;i<this.choices.length;i++)
{
var classDep = "",
attrDep = "",
separator = "",
d = this.choicesDep[ i ];
for (var j=0;j<d.length;j++)
{
if( !/^\s*$/.test( d[j] ) )
{
classDep = "depItem";
attrDep += separator+d[j];
separator = ",";
}	
}
str += '<div class="'+this.layout+'"><label><input name="'+this.name+'[]" '+((classDep!="")?"dep=\""+attrDep+"\"":"")+' id="'+this.name+'" class="field '+classDep+' group '+((this.required)?" required":"")+'" value="'+$.fbuilder.htmlEncode(this.choicesVal[i])+'" vt="'+$.fbuilder.htmlEncode(this.choices[i])+'" type="checkbox" '+((this.choiceSelected[i])?"checked":"")+'/> '+this.choices[i]+'</label></div>';
}
return '<div class="fields '+this.csslayout+'" id="field'+this.form_identifier+'-'+this.index+'"><label for="'+this.name+'">'+this.title+''+((this.required)?"<span class='r'>*</span>":"")+'</label><div class="dfield">'+str+'<span class="uh">'+this.userhelp+'</span></div><div class="clearer"></div></div>';
},
showHideDep:function( toShow, toHide )
{
var item = $( '#'+this.name+'.depItem' ),
form_identifier = this.form_identifier;
try
{
if( item.length )
{
var parent = item.closest( '.fields' );
parent.find( '.field' ).each( function()
{
var item = $( this );
if(  item.attr( 'dep' ) && item.attr( 'dep' ) != '' )
{
var d = item.attr( 'dep' ).split( ',' );
for ( i=0; i<d.length; i++ )
{
if ( d[i] != "" )
{
d[i] = d[i] + form_identifier;
if ( $.inArray( d[i], toShow ) == -1 )
{
try 
{
if ( item.is( ':checked' ) && $.inArray( item.attr( 'id' ), toHide ) == -1  )
{
$( '#'+d[i] ).closest( '.fields' ).css( 'display', '' );
$( '#'+d[i] ).closest( '.fields' ).find( '.field' ).each( function(){
$(this).removeClass( 'ignore' );
});
if( $.inArray( d[i], toShow ) == -1 )
{
toShow[toShow.length] = d[i];
}
var index = $.inArray( d[ i ], toHide );
if( index != -1 )
{
toHide.splice( index, 1);
}	
}
else
{
$( '#' + d[i] ).closest( '.fields' ).css( 'display', 'none' );
$( '#' + d[i] ).closest( '.fields' ).find( '.field' ).each(function()
{
$(this).addClass('ignore');
});
if( $.inArray( d[i], toHide ) == -1 )
{
toHide[ toHide.length ] = d[ i ];
}	
}
} catch(e){  }
}
}	
}
}
});
}
}
catch( e ){  }
},
val:function()
{
var e = $( '[id="' + this.name + '"]:checked:not(.ignore)' ),
v = 0,
me = this;
if( e.length )
{
e.each( function(){
v += $.fbuilder.parseVal( this.value );
} );
}
return v;	
}
}
);	$.fbuilder.controls[ 'fradio' ]=function(){};
$.extend(
$.fbuilder.controls[ 'fradio' ].prototype, 
$.fbuilder.controls[ 'ffields' ].prototype,
{
title:"Select a Choice",
ftype:"fradio",
layout:"one_column",
required:false,
choiceSelected:"",
showDep:false,
show:function()
{
this.choicesVal = ((typeof(this.choicesVal) != "undefined" && this.choicesVal !== null)?this.choicesVal:this.choices.slice(0));
var str = "";
if (!(typeof(this.choicesDep) != "undefined" && this.choicesDep !== null))
{
this.choicesDep = new Array();
for (var i=0;i<this.choices.length;i++)
{
this.choicesDep[i] = new Array();
}	
}
var classDep = "";
for (var i=0, h = this.choicesDep.length;i<h;i++)
{
if( this.choicesDep[i].length )
{
classDep = "depItem";
break;
}
}
for (var i=0;i<this.choices.length;i++)
{
var attrDep = "",
separator = "",
d = this.choicesDep[ i ];
for (var j=0;j<d.length;j++)
{
if( !/^\s*$/.test( d[j] ) )
{
attrDep += separator+d[j];
separator = ",";
}	
}
str += '<div class="'+this.layout+'"><label><input name="'+this.name+'" id="'+this.name+'" '+((attrDep!="")?"dep=\""+attrDep+"\"":"")+' class="field '+classDep+' group '+((this.required)?" required":"")+'" value="'+$.fbuilder.htmlEncode(this.choicesVal[i])+'" vt="'+$.fbuilder.htmlEncode(this.choices[i])+'" type="radio" i="'+i+'"  '+((this.choices[i]+' - '+this.choicesVal[i]==this.choiceSelected || this.choicesVal[i]+' - '+this.choicesVal[i]==this.choiceSelected)?"checked":"")+'/> '+this.choices[i]+'</label></div>';
}
return '<div class="fields '+this.csslayout+'" id="field'+this.form_identifier+'-'+this.index+'"><label for="'+this.name+'">'+this.title+''+((this.required)?"<span class='r'>*</span>":"")+'</label><div class="dfield">'+str+'<span class="uh">'+this.userhelp+'</span></div><div class="clearer"></div></div>';
},
showHideDep:function( toShow, toHide )
{
var item = $( '#'+this.name+'.depItem' ),
form_identifier = this.form_identifier;
try
{
if( item.length )
{
var parent = item.closest( '.fields' );
parent.find( '.field' ).each( function()
{
var item = $( this );
if(  item.attr( 'dep' ) && item.attr( 'dep' ) != '' )
{
var d = item.attr( 'dep' ).split( ',' );
for ( i=0; i<d.length; i++ )
{
if ( d[i] != "" )
{
d[i] = d[i] + form_identifier;
if ( $.inArray( d[i], toShow ) == -1 )
{
try 
{
if ( item.is( ':checked' ) && $.inArray( item.attr( 'id' ), toHide ) == -1 )
{
$( '#'+d[i] ).closest( '.fields' ).css( 'display', '' );
$( '#'+d[i] ).closest( '.fields' ).find( '.field' ).each( function(){
$(this).removeClass( 'ignore' );
});
if( $.inArray( d[i], toShow ) == -1 )
{
toShow[toShow.length] = d[i];
}	
var index = $.inArray( d[ i ], toHide );
if( index != -1 )
{
toHide.splice( index, 1);
}	
}
else
{
$( '#' + d[i] ).closest( '.fields' ).css( 'display', 'none' );
$( '#' + d[i] ).closest( '.fields' ).find( '.field' ).each(function()
{
$(this).addClass("ignore");
});
if( $.inArray( d[i], toHide ) == -1 )
{
toHide[ toHide.length ] = d[ i ];
}	
}
} catch(e){  }
}
}	
}
}
});
}
}
catch( e ){  }
},
val:function()
{
var e = $( '[id="' + this.name + '"]:checked:not(.ignore)' );
if( e.length )
{
return $.fbuilder.parseVal( e.val() );
}
return 0;	
}	
}
);	$.fbuilder.controls[ 'fdropdown' ]=function(){};
$.extend(
$.fbuilder.controls[ 'fdropdown' ].prototype,
$.fbuilder.controls[ 'ffields' ].prototype,
{
title:"Select a Choice",
ftype:"fdropdown",
size:"medium",
required:false,
choiceSelected:"",
showDep:false,
show:function()
{
this.choicesVal = ((typeof(this.choicesVal) != "undefined" && this.choicesVal !== null)?this.choicesVal:this.choices.slice(0))
var lv = this.choicesVal,
l = this.choices,
str = "";
if (!(typeof(this.choicesDep) != "undefined" && this.choicesDep !== null))
{
this.choicesDep = new Array();
for (var i=0;i<l.length;i++)
{
this.choicesDep[i] = new Array();
}	
}
var classDep = "";
for (var i=0, h = this.choicesDep.length;i<h;i++)
{
if( this.choicesDep[i].length )
{
classDep = "depItem";
break;
}
}
for (var i=0;i<l.length;i++)
{
var attrDep = "",
separator = "",
d = this.choicesDep[ i ];
for (var j=0;j<d.length;j++)
{
if( !/^\s*$/.test( d[j] ) )
{
attrDep += separator+d[j];
separator = ",";
}	
}
str += '<option '+((attrDep!="")?"dep=\""+attrDep+"\"":"")+' '+((this.choiceSelected == l[i]+' - '+lv[i])?"selected":"")+' '+( ( classDep != '' ) ? 'class="'+classDep+'"' : '' )+' value="'+$.fbuilder.htmlEncode(lv[i])+'" vt="'+$.fbuilder.htmlEncode(l[i])+'" >'+l[i]+'</option>';
}
return '<div class="fields '+this.csslayout+'" id="field'+this.form_identifier+'-'+this.index+'"><label for="'+this.name+'">'+this.title+''+((this.required)?"<span class='r'>*</span>":"")+'</label><div class="dfield"><select id="'+this.name+'" name="'+this.name+'" class="field '+( ( classDep != '' ) ? ' depItemSel ' : '' )+this.size+((this.required)?" required":"")+'" >'+str+'</select><span class="uh">'+this.userhelp+'</span></div><div class="clearer"></div><div class="clearer"></div></div>';
},
showHideDep:function( toShow, toHide )
{
var item = $( '#'+this.name ),
form_identifier = this.form_identifier;
try
{
if( item.find( '.depItem' ).length )
{
var id = item.attr( 'id' );
item.find( '.depItem' ).each( function()
{
var item = $( this );
if( item.attr( 'dep' ) && item.attr( 'dep' ) != '' )
{
var d = item.attr( 'dep' ).split( ',' );
for ( i=0; i<d.length; i++ )
{
if ( d[i] != "" )
{
d[i] = d[i] + form_identifier;
if ( $.inArray( d[i], toShow ) == -1 )
{
try 
{
if ( item.is( ':selected' ) && $.inArray( id, toHide ) == -1  )
{
$( '#'+d[i] ).closest( '.fields' ).css( 'display', '' );
$( '#'+d[i] ).closest( '.fields' ).find( '.field' ).each( function(){
$(this).removeClass( 'ignore' );
});
if( $.inArray( d[i], toShow ) == -1 )
{
toShow[toShow.length] = d[i];
}
var index = $.inArray( d[ i ], toHide );
if( index != -1 )
{
toHide.splice( index, 1);
}	
}
else
{
$( '#' + d[i] ).closest( '.fields' ).css( 'display', 'none' );
$( '#' + d[i] ).closest( '.fields' ).find( '.field' ).each(function()
{
$(this).addClass("ignore");
});
if( $.inArray( d[i], toHide ) == -1 )
{
toHide[ toHide.length ] = d[ i ];
}	
}
} catch(e){}
}
}	
}
}
});
}
}
catch( e ){}					
}	
}
);	$.fbuilder.controls[ 'ffile' ] = function(){};
$.extend(
$.fbuilder.controls[ 'ffile' ].prototype,
$.fbuilder.controls[ 'ffields' ].prototype,
{
title:"Untitled",
ftype:"ffile",
required:false,
size:"medium",
accept:"",
upload_size:"",
multiple:false,
preview: false,
thumb_width: '80px',
thumb_height: '',
_patch: false, // Used only if the submission is being updated to preserves the previous values
init: function(){
this.thumb_width  = $.trim(this.thumb_width);
this.thumb_height = $.trim(this.thumb_height);
var form_identifier = this.form_identifier.replace(/[^\d]/g, '');
this._patch = ('cpcff_default' in window && form_identifier in cpcff_default) ? true : false;
},
show:function()
{
this.accept = $.fbuilder.htmlEncode($.trim(this.accept));
this.upload_size = $.fbuilder.htmlEncode($.trim(this.upload_size));
return '<div class="fields '+this.csslayout+' '+this.name+' cff-file-field" id="field'+this.form_identifier+'-'+this.index+'"><label for="'+this.name+'">'+this.title+''+((this.required)?"<span class='r'>*</span>":"")+'</label><div class="dfield"><input type="file" id="'+this.name+'" name="'+this.name+'[]"'+((this.accept.length) ? ' accept="'+this.accept+'"' : '')+((this.upload_size.length) ? ' upload_size="'+this.upload_size+'"' : '')+' class="field '+this.size+((this.required)?" required":"")+'" '+( ( this.multiple ) ? 'multiple' : '' )+' />'+((this._patch) ? '<input type="hidden" id="'+this.name+'_patch" name="'+this.name+'_patch" value="1" />' : '' )+'<span class="uh">'+this.userhelp+'</span></div><div class="clearer"></div></div>';
},
after_show:function()
{
var me = this;
if (typeof message_ffile_accept != "undefined")
$.extend($.validator.messages, {accept: $.validator.format(message_ffile_accept)});
if(!('accept' in $.validator.methods))
$.validator.addMethod("accept", function(value, element, param)
{
if( this.optional( element ) ) return true;
else{
param = typeof param === "string" ? param.replace(/,/g, '|') : "png|jpe?g|gif";
var regExpObj = new RegExp(".(" + param + ")$", "i");
for( var i = 0, h = element.files.length; i < h; i++ )
if( !element.files[ i ].name.match( regExpObj ) ) return false;
return true;
}
});
if (typeof cp_hourbk_message_ffile_size != "undefined")
$.extend($.validator.messages, {upload_size: $.validator.format(cp_hourbk_message_ffile_size)});
if(!('upload_size' in $.validator.methods))
$.validator.addMethod("upload_size", function(value, element,params)
{
if( this.optional( element ) ) return true;
else{
var total = 0;
for( var i = 0, h = element.files.length; i < h; i++ )
total += element.files[ i ].size/1024;
return ( total <= params );
}
});
$( '#'+me.name ).change( function(){
var h = this.files.length, n = 0;
$( this ).siblings( 'span.files-list' ).remove();
$('[id="'+me.name+'_patch"]').remove();
if(1 <= h)
{
var filesContainer = $('<span class="files-list"></span>');
for( var i = 0; i < h; i++ )
{
(function(i, file){
if(me.preview && file.type.match('image.*') && 'FileReader' in window)
{
var reader = new FileReader();
reader.onload = function (e) {
var img = $('<img>');
img.attr('src', e.target.result).css('maxWidth', '100%');
if(me.thumb_height != '') img.attr('height', me.thumb_height);
if(me.thumb_width  != '') img.attr('width', me.thumb_width);
filesContainer.append($('<span>'+(n ? ', ' : '')+'</span>').append(img));
n++;
};
reader.readAsDataURL(file);
}
else if(1 < h){filesContainer.append($('<span>').text((n ? ', ' : '')+file.name));n++;}
})(i, this.files[i]);
}
$( this ).after( filesContainer );
}
});
}
}
);	$.fbuilder.controls[ 'fpassword' ] = function(){};
$.extend( 
$.fbuilder.controls[ 'fpassword' ].prototype, 
$.fbuilder.controls[ 'ffields' ].prototype,
{
title:"Untitled",
ftype:"fpassword",
predefined:"",
predefinedClick:false,
required:false,
size:"medium",
minlength:"",
maxlength:"",
equalTo:"",
show:function()
{
return '<div class="fields '+this.csslayout+'" id="field'+this.form_identifier+'-'+this.index+'"><label for="'+this.name+'">'+this.title+''+((this.required)?"<span class='r'>*</span>":"")+'</label><div class="dfield"><input id="'+this.name+'" name="'+this.name+'" minlength="'+(this.minlength)+'" maxlength="'+$.fbuilder.htmlEncode(this.maxlength)+'" '+((this.equalTo!="")?"equalTo=\"#"+$.fbuilder.htmlEncode(this.equalTo+this.form_identifier)+"\"":"" )+' class="field '+this.size+((this.required)?" required":"")+'" type="password" value="'+$.fbuilder.htmlEncode(this.predefined)+'"/><span class="uh">'+this.userhelp+'</span></div><div class="clearer"></div></div>';
},
val:function()
{
var e = $( '[id="' + this.name + '"]:not(.ignore)' );
if( e.length ) return $.fbuilder.parseValStr( e.val() );
return '';
}		
}
);	$.fbuilder.controls[ 'fPhone' ]=function(){};
$.extend(
$.fbuilder.controls[ 'fPhone' ].prototype,
$.fbuilder.controls[ 'ffields' ].prototype,
{
title:"Phone",
ftype:"fPhone",
required:false,
readonly:false,
dformat:"### ### ####",
predefined:"888 888 8888",
predefinedClick:true,
show:function()
{
var me   = this,
str  = "",
tmp  = this.dformat.split(' '),
tmpv = this.predefined.split(' '),
attr = ( typeof this.predefinedClick != 'undefined' && this.predefinedClick ) ? 'placeholder' : 'value';
for (var i=0;i<tmpv.length;i++)
{
if ($.trim(tmpv[i])=="")
{
tmpv.splice(i,1);
}
}
for (var i=0;i<tmp.length;i++)
{
if ($.trim(tmp[i])!="")
{
str += '<div class="uh_phone" ><input type="tel" id="'+this.name+'_'+i+'" name="'+this.name+'_'+i+'" class="field '+((i==0) ? ' phone ' : ' digits ')+((this.required) ? ' required ' : '')+'" size="'+$.trim(tmp[i]).length+'" '+attr+'="'+((tmpv[i])?tmpv[i]:"")+'" maxlength="'+$.trim(tmp[i]).length+'" minlength="'+$.trim(tmp[i]).length+'" '+((this.readonly)?'readonly':'')+' /><div class="l">'+$.trim(tmp[i])+'</div></div>';
}
}
return '<div class="fields '+this.csslayout+' '+this.name+' cff-phone-field" id="field'+this.form_identifier+'-'+this.index+'"><label for="'+this.name+'">'+this.title+''+((this.required)?"<span class='r'>*</span>":"")+'</label><div class="dfield"><input type="hidden" id="'+this.name+'" name="'+this.name+'" class="field " />'+str+'<span class="uh">'+this.userhelp+'</span></div><div class="clearer"></div></div>';
},
after_show: function()
{
var me   = this,
tmp  = me.dformat.split(' ');
$.validator.messages["phone"] = $.validator.messages["digits"];
if(!('phone' in $.validator.methods))
$.validator.addMethod("phone", function(value, element)
{
if( this.optional( element ) ) return true;
else return /^\+{0,1}\d*$/.test(value);
});
for (var i = 0, h = tmp.length; i < h; i++ )
{
$( '#'+me.name+'_'+i ).bind( 'change', function(){
var v = '';
for( var i = 0; i < tmp.length; i++ )
{
v += $( '#'+me.name+'_'+i ).val();
}
$( '#'+me.name ).val( v ).change();
} );
if( i+1 < h )
{
$('#'+me.name+'_'+i).bind( 'keyup', { 'next': i+1 }, function( evt ){
var e = $( this );
if( e.val().length == e.attr( 'maxlength' ) )
{
e.change();
$( '#'+me.name+'_'+evt.data.next ).focus();
}
} );
}
}
},
val:function(raw)
{
raw = raw || false;
var e = $( '[id="' + this.name + '"]:not(.ignore)' );
if( e.length ) return $.fbuilder.parseValStr( e.val(), raw );
return 0;
},
setVal:function( v )
{
$( '[name="'+this.name+'"]' ).val( v );
v = $.trim( v ).replace( /[^\d]/g, ' ').split( ' ' );
for( var i in v ) $( '[id="' + this.name + '_' + i + '"]' ).val( v[ i ] );
}
}
);	$.fbuilder.controls[ 'fCommentArea' ]=function(){};
$.extend( 
$.fbuilder.controls[ 'fCommentArea' ].prototype, 
$.fbuilder.controls[ 'ffields' ].prototype,
{
title:"Comments here",
ftype:"fCommentArea",
userhelp:"A description of the section goes here.",
show:function()
{
return '<div class="fields '+this.csslayout+' comment_area" id="field'+this.form_identifier+'-'+this.index+'"><label id="'+this.name+'">'+this.title+'</label><span class="uh">'+this.userhelp+'</span><div class="clearer"></div></div>';
}	
}
);	$.fbuilder.controls[ 'fhidden' ]=function(){};
$.extend(
$.fbuilder.controls[ 'fhidden' ].prototype,
$.fbuilder.controls[ 'ffields' ].prototype,
{
ftype:"fhidden",
title:"",
predefined:"",
show:function()
{
return '<div style="display:none;"><div class="fields" id="field'+this.form_identifier+'-'+this.index+'"><label for="'+this.name+'">'+this.title+'</label><div class="dfield"><input id="'+this.name+'" name="'+this.name+'" type="hidden" value="'+$.fbuilder.htmlEncode(this.predefined)+'" class="field" /></div></div></div>';
}
}	
);	$.fbuilder.controls[ 'fSectionBreak' ] = function(){};
$.extend( 
$.fbuilder.controls[ 'fSectionBreak' ].prototype, 
$.fbuilder.controls[ 'ffields' ].prototype,
{
title:"Section Break",
ftype:"fSectionBreak",
userhelp:"A description of the section goes here.",
show:function()
{
return '<div class="fields '+this.csslayout+' section_breaks" id="field'+this.form_identifier+'-'+this.index+'"><div class="section_break" id="'+this.name+'" ></div><label>'+this.title+'</label><span class="uh">'+this.userhelp+'</span><div class="clearer"></div></div>';
}
}
);	$.fbuilder.controls[ 'fPageBreak' ]=function(){};
$.extend(
$.fbuilder.controls[ 'fPageBreak' ].prototype, 
$.fbuilder.controls[ 'ffields' ].prototype,
{
title:"Page Break",
ftype:"fPageBreak",
show:function()
{
return '<div class="fields '+this.csslayout+' section_breaks" id="field'+this.form_identifier+'-'+this.index+'"><div class="section_break" id="'+this.name+'" ></div><label>'+this.title+'</label><span class="uh">'+this.userhelp+'</span><div class="clearer"></div></div>';
}
}
);	$.fbuilder.controls[ 'fsummary' ] = function(){};
$.extend(
$.fbuilder.controls[ 'fsummary' ].prototype,
$.fbuilder.controls[ 'ffields' ].prototype,
{
title:"Summary",
ftype:"fsummary",
fields:"",
titleClassname:"summary-field-title",
valueClassname:"summary-field-value",
fieldsArray:[],
show:function()
{
var me = this,
p = $.trim( me.fields.replace( /\,+/g, ',') ).split( ',' ),
l = p.length;
if( l )
{
var str = '<div class="fields '+me.csslayout+'" id="field'+me.form_identifier+'-'+me.index+'">'+( ( !/^\s*$/.test( me.title ) ) ? '<h2>'+me.title+'</h2>': '' )+'<div id="'+me.name+'">';
for( var i = 0; i < l; i++ )
{
if( !/^\s*$/.test( p[ i ] ) )
{
p[ i ] = $.trim( p[ i ] );
str += '<div ref="'+p[i]+me.form_identifier+'" class="cff-summary-item"><span class="'+me.titleClassname+' cff-summary-title"></span><span class="'+me.valueClassname+' cff-summary-value"></span></div>';
}	
}
str += '</div></div>';
return str;
}
},
after_show: function(){
var me = this,
p = $.trim(me.fields.replace( /\,+/g, ',') ).split( ',' ),
l = p.length;
if( l )
{
for( var i = 0; i < l; i++ )
{
if( !/^\s*$/.test( p[ i ] ) )
{
p[ i ] = $.trim( p[ i ] );
me.fieldsArray.push( p[ i ] + me.form_identifier );    
$( document ).on( 'change', '#' + p[ i ] + me.form_identifier, function(){ me.update(); } );
}	
}
$( document ).on( 'showHideDepEvent', function( evt, form_identifier )
{
me.update();
});
$( '#cp_calculatedfieldsf_pform'+me.form_identifier ).bind( 'reset', function(){ setTimeout( function(){ me.update(); }, 10 ); } );
}
},    
update:function()
{
for ( var j = 0, k = this.fieldsArray.length; j < k; j++ )
{
var i  = this.fieldsArray[ j ],
e  = $( '[id="' + i + '"]'),
tt = $( '[ref="' + i + '"]');
if( e.length && tt.length )
{	
//var t  = $( '#' + i ).closest( '.fields' ).find( 'label[for="'+i+'"]' ).text(),
var t  = $( '#' + i ).closest( '.fields' ).find( 'label:first' ).html(), 
v  = [];
e.each( 
function(){ 
var e = $(this);
if( /(checkbox|radio)/i.test( e.attr( 'type' ) ) && !e.is( ':checked' ) ) 
{
return;
}
else if( e[0].tagName == 'SELECT' )
{
v.push( $(e[0].options[ e[0].selectedIndex ]).attr( 'vt' ) );
}
else
{
if( e.attr( 'vt' ) )
{
v.push( e.attr( 'vt' ) );
}
else if( e.attr( 'summary' ) )
{
v.push( $( '#' + i ).closest( '.fields' ).find( '.'+e.attr( 'summary' )+i ).html() );
}
else
{
v.push( e.val() );
}
}	
}
);
try 
{
if (t.substring(t.length-1)=='*')
t = t.substring(0, t.length-1);
if (t.substring(t.length-1)==':')
t = t.substring(0, t.length-1); 
}
catch (e) 
{}
tt.find( '.cff-summary-title' ).html( ( /^\s*$/.test( t ) ) ? '' : t );
tt.find( '.cff-summary-value' ).html( v.join( ', ' ) );
if (v.join( ', ' ).trim()=="")
tt.addClass("emptyvalue");
else
tt.removeClass("emptyvalue");
if( e.hasClass( 'ignore' ) )
{
tt.hide();
}
else
{
tt.show();
}
}	
}
}
});
$.fbuilder.controls[ 'datasource' ] = function(){};
$.fbuilder.controls[ 'datasource' ].prototype = {
isDataSource:true,
active : '',
list : {
'database' : {
databaseData: '',
queryData : {
active: 'structure',
query: '',
value: '',
text: '',
table: '',
where: '',
orderby: ''
},
getData : function( callback, p ) 
{
var url = document.location.href,
data = $.extend( {}, this.queryData );
if( data.active == 'structure' )
{
data.where = btoa(p.replaceVariables( data.where ));
data.orderby = btoa(p.replaceVariables( data.orderby ));
}
else
{
data.query = p.replaceVariables( data.query );
}
$.ajax(
{
dataType : 'json',
url : url,
cache : false,
data : $.extend( { ahbqeaction1cb2ef6a5a88c2d10054: 'dk80TlVvbE9jWHoyUWxNVHV4OVFkaFNZcVJ5Wlg0bmMreEJ2VkJ3Ynpiaz0=' }, this.databaseData, data ),
success : function( data ){
callback( data );	
}
}
);
}
},
'csv' : {
csvData : {
text : 0,
value : 0,
fields : [],
rows : []
},
getData : function( callback )
{
var obj = {
data : []
};
for( var i in this.csvData.rows )
{
var text = this.csvData.text,
value = this.csvData.value;
if( typeof this.csvData.rows[ i ].length == 'undefined' )
{
text  = this.csvData.fields[ text ];
value = this.csvData.fields[ value ];
}
obj.data.push( { text: this.csvData.rows[ i ][ text ], value : this.csvData.rows[ i ][ value ] } );
}	
callback( obj );
}
},
'posttype' : {
posttypeData:{
posttype : '',
value 	 : '',
text 	 : '',
last	 : '',
id 		 : ''
},
getData : function( callback, p )
{
var url = document.location.href,
data = $.extend( {}, this.posttypeData );
if( !/^\s*$/.test( data.id ) )
{
data.id = p.replaceVariables( data.id );
}
$.ajax(
{
dataType : 'json',
url : url,
cache : false,
data : $.extend( { ahbqeaction1cb2ef6a5a88c2d10054: 'bU9uYlh6MnJwODV0TEZreVI5Z3FEZz09' }, data ),
success : function( data ){
callback( data );	
}
}
);
}
},
'taxonomy' : {
taxonomyData:{
taxonomy : '',
value 	 : '',
text 	 : '',
id 		 : '',
slug 	 : ''
},
getData : function( callback, p )
{
var url = document.location.href,
data = $.extend( {}, this.taxonomyData );
if( !/^\s*$/.test( data.id ) )
{
data.id = p.replaceVariables( data.id );
}
if( !/^\s*$/.test( data.slug ) )
{
data.slug = p.replaceVariables( data.slug );
}
$.ajax(
{
dataType : 'json',
url : url,
cache : false,
data : $.extend( { ahbqeaction1cb2ef6a5a88c2d10054: 'TFRwaUtCQkZpdmJub0I5RjVoak9XQT09' }, data ),
success : function( data ){
callback( data );	
}
}
);
}
},
'user' : {
userData : {
logged  : false,
text 	: '',
value 	: '',
id 		: '',
login 	: ''
},
getData : function( callback, p )
{
var url = document.location.href,
data = $.extend( {}, this.userData );
if( !data.logged )
{
if( !/^\s*$/.test( data.id ) )
{
data.id = p.replaceVariables( data.id );
}
if( !/^\s*$/.test( data.login ) )
{
data.login = p.replaceVariables( data.login );
}
}
$.ajax(
{
dataType : 'json',
url : url,
cache : false,
data : $.extend( { ahbqeaction1cb2ef6a5a88c2d10054: 'WTVjQ1BkQnNGYmhuZ01Zd1g4eHpiZz09' }, data ),
success : function( data ){
callback( data );	
}
}
);
}
}	
},
getData : function( callback )
{
this.list[ this.active ].getData( callback, this );
},
replaceVariables : function( str )
{
var _match,
tmpArr = []; // To avoid duplicate handles
while ( _match = /<[%](fieldname\d+)[%]>/.exec( str ) )
{
var me 	= this,
e   = _match[ 1 ]+this.form_identifier,
f 	= $.fbuilder[ 'forms' ][ this.form_identifier ].getItem( e );
if( ( typeof this.hasBeenPutRelationHandles == 'undefined' || !this.hasBeenPutRelationHandles ) && $.inArray( _match[ 1 ], tmpArr ) == -1 )	
{
$( document ).on( 	'change', 
'#'+e, 
function()
{
me.after_show(); 
} 
);
tmpArr.push( _match[ 1 ] );				
}
if( f )
{
str = str.replace( _match[ 0 ], f.val() );
}
}
this.hasBeenPutRelationHandles = true;
return str;
}
};	$.fbuilder.controls[ 'ftextds' ]=function(){};
$.extend(
$.fbuilder.controls[ 'ftextds' ].prototype,
$.fbuilder.controls[ 'ftext' ].prototype,
$.fbuilder.controls[ 'datasource' ].prototype,
{
ftype:"ftextds",
show:function()
{
return $.fbuilder.controls[ 'ftext' ].prototype.show.call( this );
},
after_show : function(){
var me = this;
$.fbuilder.controls[ 'datasource' ].prototype.getData.call( this, function( data )
{ 
if( typeof data.error != 'undefined' )
{
alert( data.error );
}
else
{
if( data.data.length )
{
if (!me.predefined) $( '#' + me.name ).val( data.data[ 0 ][ 'value' ] ).change();
}
}	
}
);
}	
});	$.fbuilder.controls[ 'femailds' ]=function(){};
$.extend(
$.fbuilder.controls[ 'femailds' ].prototype,
$.fbuilder.controls[ 'femail' ].prototype,
$.fbuilder.controls[ 'datasource' ].prototype,
{
ftype:"femailds",
show:function()
{
return $.fbuilder.controls[ 'femail' ].prototype.show.call( this );
},
after_show : function(){
var me = this;
$.fbuilder.controls[ 'datasource' ].prototype.getData.call( this, function( data )
{ 
if( typeof data.error != 'undefined' )
{
alert( data.error );
}
else
{
if( data.data.length )
{
if (!me.predefined) $( '#' + me.name ).val( data.data[ 0 ][ 'value' ] ).change();
}
}	
}
);
}	
});	$.fbuilder.controls[ 'ftextareads' ]=function(){};
$.extend(
$.fbuilder.controls[ 'ftextareads' ].prototype,
$.fbuilder.controls[ 'ftextarea' ].prototype,
$.fbuilder.controls[ 'datasource' ].prototype,
{
ftype:"ftextareads",
show:function()
{
return $.fbuilder.controls[ 'ftextarea' ].prototype.show.call( this );
},
after_show : function(){
var me = this;
$.fbuilder.controls[ 'datasource' ].prototype.getData.call( this, function( data )
{ 
if( typeof data.error != 'undefined' )
{
alert( data.error );
}
else
{
if( data.data.length )
{
if (!me.predefined) $( '#' + me.name ).val( data.data[ 0 ][ 'value' ] ).change();
}
}	
}
);
}	
});	$.fbuilder.controls[ 'fcheckds' ] = function(){};
$.extend(
$.fbuilder.controls[ 'fcheckds' ].prototype,
$.fbuilder.controls[ 'fcheck' ].prototype,
$.fbuilder.controls[ 'datasource' ].prototype,
{
ftype:"fdropdownds",
show:function()
{
return '<div class="fields '+this.csslayout+'" id="field'+this.form_identifier+'-'+this.index+'"><label>'+this.title+''+((this.required)?"<span class='r'>*</span>":"")+'</label><div class="dfield"><span class="uh">'+this.userhelp+'</span></div><div class="clearer"></div></div>';
},
after_show : function(){
var me = this;
$.fbuilder.controls[ 'datasource' ].prototype.getData.call( this, function( data )
{ 
if( typeof data.error != 'undefined' )
{
alert( data.error );
}
else
{
var str = '';
for( var i = 0, h = data.data.length; i < h; i++ )
{
var e = data.data[ i ];
str += '<div class="'+this.layout+'"><label><input name="'+me.name+'[]" id="' + me.name + '" class="field group ' + ( ( me.required ) ? " required" : "" ) + '" value="' + $.fbuilder.htmlEncode( e.value ) + '" vt="' + $.fbuilder.htmlEncode( e.text ) + '" type="checkbox" '+(e.text==me.choiceSelected||e.value==me.choiceSelected?' checked ':'')+' /> ' + e.text + '</label></div>';
}
$( '#field' + me.form_identifier + '-' + me.index + ' .dfield' ).html( str ).change();
}	
}
);
}	
});	$.fbuilder.controls[ 'fradiods' ]=function(){};
$.extend(
$.fbuilder.controls[ 'fradiods' ].prototype,
$.fbuilder.controls[ 'fradio' ].prototype,
$.fbuilder.controls[ 'datasource' ].prototype,
{
ftype:"fradiods",
show:function()
{
return '<div class="fields '+this.csslayout+'" id="field'+this.form_identifier+'-'+this.index+'"><label>'+this.title+''+((this.required)?"<span class='r'>*</span>":"")+'</label><div class="dfield"><span class="uh">'+this.userhelp+'</span></div><div class="clearer"></div></div>';
},
after_show : function(){
var me = this;
$.fbuilder.controls[ 'datasource' ].prototype.getData.call( this, function( data )
{ 
if( typeof data.error != 'undefined' )
{
alert( data.error );
}
else
{
var str = ''; 
for( var i = 0, h = data.data.length; i < h; i++ )
{
var e = data.data[ i ];
str += '<div class="' + me.layout + '"><label><input name="' + me.name + '" id="' + me.name + '" class="field group ' + ( ( me.required ) ? " required" : "" ) + '" value="' + $.fbuilder.htmlEncode( e.value ) + '" vt="' + $.fbuilder.htmlEncode( e.text ) + '" type="radio" i="' + i + '" '+(e.text==me.choiceSelected||e.value==me.choiceSelected?' checked ':'')+'/> ' + e.text + '</label></div>';
}
$( '#field' + me.form_identifier + '-' + me.index + ' .dfield' ).html( str ).change();
}	
}
);
}
}
);	$.fbuilder.controls[ 'fPhoneds' ]=function(){};
$.extend( 
$.fbuilder.controls[ 'fPhoneds' ].prototype,
$.fbuilder.controls[ 'fPhone' ].prototype,
$.fbuilder.controls[ 'datasource' ].prototype,
{
ftype:"fPhoneds",
show:function()
{
return $.fbuilder.controls[ 'fPhone' ].prototype.show.call( this );
},
after_show : function()
{
var me = this;
$.fbuilder.controls[ 'fPhone' ].prototype.after_show.call( me );
$.fbuilder.controls[ 'datasource' ].prototype.getData.call( me, function( data )
{ 
if( typeof data.error != 'undefined' )
{
alert( data.error );
}
else
{
if( data.data.length )
{
var v = data.data[ 0 ].value,
p = $.trim( me.dformat.replace(/[^\s#]/g, '' ).replace( /\s+/g, ' ' ) ).split( ' ' ), 
h = p.length,
r = '', e;
for( var i = 0; i < h; i++ )
{
r += '(.{' + p[ i ].length + '})';
}
v = v.replace( /\s+/, '' );
e =  ( new RegExp( r ) ).exec( v );
if( e )
{
for( var i = 0; i < h; i++ )
{
if (!me.predefined) $( '#' + me.name + '_' + i ).val( e[ i+1 ] ).change();
}
}
}
}	
}
);
}
}
);	$.fbuilder.controls[ 'fdropdownds' ] = function(){};
$.extend(
$.fbuilder.controls[ 'fdropdownds' ].prototype,
$.fbuilder.controls[ 'fdropdown' ].prototype,
$.fbuilder.controls[ 'datasource' ].prototype,
{
ftype:"fdropdownds",
show:function()
{
this.choices = [];
return $.fbuilder.controls[ 'fdropdown' ].prototype.show.call( this );
},
after_show : function(){
var me = this;
$.fbuilder.controls[ 'datasource' ].prototype.getData.call( this, function( data )
{ 
if( typeof data.error != 'undefined' )
{
alert( data.error );
}
else
{
var str = '', t, v;
for( var i = 0, h = data.data.length; i < h; i++ )
{
v = ( ( typeof data.data[ i ][ 'value' ] != 'undefined' ) ? data.data[ i ][ 'value' ] : '' );
t = ( ( typeof data.data[ i ][ 'text' ] != 'undefined' )  ? data.data[ i ][ 'text' ]  :  v );
str += '<option value="' + $.fbuilder.htmlEncode( v ) + '" vt="' + $.fbuilder.htmlEncode( t ) +'"'+(t==me.choiceSelected||v==me.choiceSelected?' selected':'')+'>' + t + '</option>';
}
$( '#' + me.name ).html( str ).change();
}	
}
);
}	
});	$.fbuilder.controls[ 'fhiddends' ]=function(){};
$.extend(
$.fbuilder.controls[ 'fhiddends' ].prototype,
$.fbuilder.controls[ 'fhidden' ].prototype,
$.fbuilder.controls[ 'datasource' ].prototype,
{
ftype:"fhiddends",
show:function()
{
return $.fbuilder.controls[ 'fhidden' ].prototype.show.call( this );
},
after_show : function()
{
var me = this;
$.fbuilder.controls[ 'datasource' ].prototype.getData.call( this, function( data )
{ 
if( typeof data.error != 'undefined' )
{
alert( data.error );
}
else
{
if( data.data.length )
{
if (!me.predefined) $( '#' + me.name ).val( data.data[ 0 ][ 'value' ] ).change();
}
}	
}
);
}	
}	
);	$.fbuilder.controls[ 'fcontainer' ] = function(){};
$.fbuilder.controls[ 'fcontainer' ].prototype = {
fields:[],
columns:1,
after_show: function()
{
var e  = $( '#'+this.name ), f;
for( var i = 0, h = this.fields.length; i < h; i++ )
{
f = $( '#'+this.fields[ i ]+this.form_identifier ).closest( '.fields' ).detach();
if( this.columns > 1 )
{
f.addClass( 'column'+this.columns );
if( i%this.columns == 0 ) f.css( 'clear', 'left' );
}	
f.appendTo( e );
}					
},
showHideDep:function( toShow, toHide )
{
var hide = ( $.inArray( this.name, toHide ) != -1 ),
index;
for( var i = 0, h = this.fields; i < h; i++ )
{
if( $.inArray( this.fields[ i ]+this.form_identifier, toHide ) == -1 )
{
toHide.push( this.fields[ i ]+this.form_identifier );
index = $.inArray( d[ i ], toShow );
if( index != -1 )
{
toShow.splice( index, 1);
}
$( '#' + this.fields[ i ]+this.form_identifier ).closest( '.fields' )
.find( '.field' )
.each(function()
{
$(this).addClass('ignore');
});
}
}
}
};	$.fbuilder.controls[ 'ffieldset' ]=function(){};
$.extend(
$.fbuilder.controls[ 'ffieldset' ].prototype,
$.fbuilder.controls[ 'ffields' ].prototype,
{
title:"Untitled",
ftype:"ffieldset",
fields:[],
columns:1,
show:function()
{
return '<div class="fields '+this.csslayout+'" id="field'+this.form_identifier+'-'+this.index+'"><FIELDSET id="'+this.name+'">'+( ( !/^\s*$/.test( this.title ) ) ? '<LEGEND>'+this.title+'</LEGEND>' : '' )+'</FIELDSET><div class="clearer"></div></div>';
},
after_show: function()
{
$.fbuilder.controls[ 'fcontainer' ].prototype.after_show.call(this);
},
showHideDep:function( toShow, toHide )
{
$.fbuilder.controls[ 'fcontainer' ].prototype.showHideDep.call( this, toShow, toHide );
}
}	
);	$.fbuilder.controls[ 'fdiv' ]=function(){};
$.extend(
$.fbuilder.controls[ 'fdiv' ].prototype,
$.fbuilder.controls[ 'ffields' ].prototype,
{
ftype:"fdiv",
fields:[],
columns:1,
show:function()
{
return '<div class="fields '+this.csslayout+'" id="field'+this.form_identifier+'-'+this.index+'"><div id="'+this.name+'"></div><div class="clearer"></div></div>';
},
after_show: function()
{
$.fbuilder.controls[ 'fcontainer' ].prototype.after_show.call(this);
},
showHideDep:function( toShow, toHide )
{
$.fbuilder.controls[ 'fcontainer' ].prototype.showHideDep.call( this, toShow, toHide );
}
}	
);	$.fbuilder.controls[ 'fMedia' ]=function(){};
$.extend( 
$.fbuilder.controls[ 'fMedia' ].prototype, 
$.fbuilder.controls[ 'ffields' ].prototype,
{
ftype:"fMedia",
sMediaType:"image", // image, audio, video
data:{
image:{
sWidth:"",
sHeight:"",
sSrc:"",
sAlt:"",
sLink:"",
sTarget:"",
sFigcaption: ""
},
audio:{
sWidth:"",
sSrc:"",
sSrcAlt:"",
sControls:1,
sLoop:0,
sAutoplay:0,
sMuted:0,
sPreload: "auto",
sFallback: "",
sFigcaption: ""
},
video:{
sWidth:"",
sHeight:"",
sSrc:"",
sSrcAlt:"",
sPoster:"",
sControls:1,
sLoop:0,
sAutoplay:0,
sMuted:0,
sPreload: "auto",
sFallback: "",
sFigcaption: ""
}
},
_show_image: function()
{
var d = this.data.image,
esc = $.fbuilder.htmlEncode,
a = [],
l = [],
r = '';
if( $.trim( d.sWidth ) ) a.push( 'width="'+esc( d.sWidth )+'"' );
if( $.trim( d.sHeight ) ) a.push( 'height="'+esc( d.sHeight )+'"' );
if( $.trim( d.sSrc ) ) a.push( 'src="'+esc( d.sSrc )+'"' );
if( $.trim( d.sAlt ) ) a.push( 'alt="'+esc( d.sAlt )+'"' );
if( $.trim( d.sLink ) )
{
l.push( 'href="'+esc( d.sLink )+'"' );
if( $.trim( d.sTarget ) ) l.push( 'target="'+esc( d.sTarget )+'"' );
r = '<a '+l.join( ' ' )+' ><img '+a.join( ' ' )+' /></a>';
}
else
{
r = '<img '+a.join( ' ' )+' />';
}
return r;
},
_show_audio_video: function( d, isV )
{
var esc = $.fbuilder.htmlEncode,
a = [],
t = ( isV ) ? 'video' : 'audio' ;
if( $.trim( d.sWidth ) ) a.push( 'width="'+esc( d.sWidth )+'"' );
if( isV && $.trim( d.sHeight ) ) a.push( 'height="'+esc( d.sHeight )+'"' );
if( isV && $.trim( d.sPoster ) ) a.push( 'poster="'+esc( d.sPoster )+'"' );
if( $.trim( d.sSrc ) ) a.push( 'src="'+esc( d.sSrc )+'"' );
if( d.sAutoplay ) a.push( 'autoplay' );
if( d.sControls ) a.push( 'controls' );
if( d.sLoop ) a.push( 'loop' );
if( d.sMuted ) a.push( 'muted' );
a.push( 'preload="'+esc( d.sPreload )+'"' );
return '<'+t+' '+a.join( ' ' )+'>'+( ( $.trim( d.sSrcAlt ) ) ? '<source src="'+esc( d.sSrcAlt )+'" />' : '' )+'<p>'+d.sFallback+'</p></'+t+'>';
},
_show_audio: function()
{
return this._show_audio_video( this.data.audio, false );
},
_show_video: function()
{
return this._show_audio_video( this.data.video, true );
},
show:function()
{
return '<div class="fields '+this.csslayout+'" id="field'+this.form_identifier+'-'+this.index+'"><div class="clearer"><div class="field" id="'+this.name+'">'+this[ '_show_'+this.sMediaType]()+'</div></div><span class="uh">'+this.data[ this.sMediaType].sFigcaption+'</span><div class="clearer"></div></div>';
}
}
);	$.fbuilder.controls[ 'fButton' ]=function(){};
$.extend( 
$.fbuilder.controls[ 'fButton' ].prototype, 
$.fbuilder.controls[ 'ffields' ].prototype,
{
ftype:"fButton",
sType:"button",
sValue:"button",
sOnclick:"",
userhelp:"A description of the section goes here.",
show:function()
{
var esc  = function( v ){ v = v.replace( /&lt/g, '&amp;').replace(/"/g, "&quot;").replace( /\n+/g, ' ' ); return v;},
type = this.sType,
clss = '';
if( this.sType == 'calculate' )
{
type = 'button';
clss = 'calculate-button';
}
else if( this.sType == 'reset' )
{
clss = 'reset-button';
}	
return '<div class="fields '+this.csslayout+'" id="field'+this.form_identifier+'-'+this.index+'"><input id="'+this.name+'" type="'+type+'" value="'+esc( this.sValue )+'" class="field '+clss+'" onclick="'+esc( this.sOnclick )+'" /><span class="uh">'+this.userhelp+'</span><div class="clearer"></div></div>';
},
after_show:function()
{
$( '#'+this.name ).click(
function()
{
var e = $( this );
if( e.hasClass( 'calculate-button' ) )
{
var suffix = e.attr( 'id' ).match(/_\d+$/)[0],
items = $.fbuilder[ 'forms' ][ suffix ].getItems();
$.fbuilder[ 'calculator' ].defaultCalc( '#'+e.closest( 'form' ).attr( 'id' ) );
for(var i = 0, h = items.length; i < h; i++ )
{
if(items[i].ftype == 'fsummary')
{ 
items[i].update();
}
}    
}
if( e.hasClass( 'reset-button' ) )
{
setTimeout( 
function()
{ 
var identifier = e.closest( 'form' ).attr( 'id' ).replace( /cp_calculatedfieldsf_pform/, '' );
$.fbuilder[ 'showHideDep' ]( { 'formIdentifier' : identifier } );
var page = parseInt( e.closest( '.pbreak' ).attr( 'page' ) );
if( page )
{
$("#fieldlist"+identifier+" .pbreak").css("display","none");
$("#fieldlist"+identifier+" .pbreak").find(".field").addClass("ignorepb");
$("#fieldlist"+identifier+" .pb0").css("display","block");
if ($("#fieldlist"+identifier+" .pb0").find(".field").length>0)
{
$("#fieldlist"+identifier+" .pb0").find(".field").removeClass("ignorepb");
try 
{
$("#fieldlist"+identifier+" .pb0").find(".field")[0].focus();
} 
catch(e){}
}	
}	
}, 
50 
);
}	
}
);
}
}
);	$.fbuilder.controls[ 'fnumberds' ]=function(){};
$.extend(
$.fbuilder.controls[ 'fnumberds' ].prototype,
$.fbuilder.controls[ 'fnumber' ].prototype,
$.fbuilder.controls[ 'datasource' ].prototype,
{
ftype:"fnumberds",
show:function()
{
return $.fbuilder.controls[ 'fnumber' ].prototype.show.call( this );
},
after_show : function(){
var me = this;
$.fbuilder.controls[ 'datasource' ].prototype.getData.call( this, function( data )
{ 
var v = '';
if( typeof data.error != 'undefined' )
{
alert( data.error );
}
else
{
if( data.data.length )
{
v = data.data[ 0 ][ 'value' ];
}
}	
if (!me.predefined) $( '#' + me.name ).val( v ).change();
}
);
}	
});	$.fbuilder.controls[ 'fhtml' ]=function(){};
$.extend( 
$.fbuilder.controls[ 'fhtml' ].prototype, 
$.fbuilder.controls[ 'ffields' ].prototype,
{
ftype:"fhtml",
fcontent:"",
show:function()
{
return '<div class="fields '+this.csslayout+'" id="field'+this.form_identifier+'-'+this.index+'"><div id="'+this.name+'" class="dfield">'+$( '<div/>' ).html( this.fcontent ).html()+'</div><div class="clearer"></div></div>';
}	
}
);$.fbuilder.controls[ 'fapp' ] = function(){};
$.extend( 
$.fbuilder.controls[ 'fapp' ].prototype, 
$.fbuilder.controls[ 'ffields' ].prototype,
{
title:"Number",
ftype:"fapp",			
services:new Array({name:"Service 1",price:1,capacity:1,duration:60,pb:0,pa:0,ohindex:0}), openhours:new Array(),
allOH:new Array({name:"Default",openhours:new Array({type:"all",d:"",h1:8,m1:0,h2:17,m2:0})}),
usedSlots:new Array(),
dateFormat:"mm/dd/yy",
showDropdown:false,
showTotalCost:false,
showTotalCostFormat:"$ {0}",
showEndTime:false,
usedSlotsCheckbox:false,		
avoidOverlaping:true,
emptySelectCheckbox:false,
emptySelect:"-- Please select service --",
dropdownRange:"-10:+10",
working_dates:[true,true,true,true,true,true,true],
numberOfMonths:1,
maxNumberOfApp:0,
showAllServices:false,		
allowDifferentQuantities:false,
allowSelectSameSlot:false,
firstDay:0,
minDate:"0",
maxDate:"",
defaultDate:"",
invalidDates:"",
required:true,			
bSlotsCheckbox: true,
bSlots:30,
militaryTime:1,
cacheArr:new Array(),
getD:new Date(),
formId:0,
getMinDate:"",
getMaxDate:"",
arr:new Array(),
allUsedSlots:new Array(),
service_selected:0,
quantity_selected:1,
tz:0,
loadOK:false,
ignoreUsedSlots:false,
initialapp:"",
initialID:0,
pctByDay:new Array(),
htmlUsedSlots:new Array(),
extras:0,
sub_cost:0,
percent:0,
notShowBookedDate:true,
showWeek:false,
autonum:0,	
availableSlotsByService:[],	
slotsDate:[],
getSplittedSlots:function(d,s)
{	
function splitSlots (a,serviceindex) {
var dots = new Array();
for (var i=0;i<a.length;i++)
{
dots[dots.length] = a[i].t1;
dots[dots.length] = a[i].t2;
}
dots.sort(function(a, b){return a - b});    
var processed_dots = new Array();
for (var i=0;i<dots.length;i++)
if (i==0 || dots[i] != dots[i-1])
processed_dots[processed_dots.length] = dots[i];
var aoutput = new Array();
for (var i=0;i<processed_dots.length-1;i++)
{
var s = processed_dots[i];
var e = processed_dots[i+1];
var m1 = s%60;
var m2 = e%60;
var segment = {t1:s, t2:e, quantity:0,serviceindex:serviceindex,h1:(s-m1)/60,m1:m1,h2:(e-m2)/60,m2:m2};
for (var j=0;j<a.length;j++)
if ( 
(s>a[j].t1 && s<a[j].t2) || 
(e>a[j].t1 && e<a[j].t2) ||
(s==a[j].t1 && e==a[j].t2)
)
segment.quantity += a[j].quantity;
if (segment.quantity)    
aoutput[aoutput.length] = segment;          
}
return aoutput;
}
var data = new Array();
d.sort(function(a, b){
if ((typeof a.serviceindex !== 'undefined') && (typeof b.serviceindex !== 'undefined'))
return a.serviceindex - b.serviceindex;
else if (typeof a.serviceindex === 'undefined')
return -1  - b.serviceindex;
else 
return a.serviceindex - (-1);        
});
var sid = -2;
var dtmp = [];
for (var i=0;i<d.length;i++)
{   
if (typeof d[i].serviceindex !== 'undefined')
{
if (d[i].serviceindex!=sid)
{
if (i!=0)
data = data.concat(splitSlots(dtmp,sid));
dtmp = [];
sid = d[i].serviceindex;		                    
}
dtmp[dtmp.length] = jQuery.extend({}, d[i]);     
}    
else
data[data.length] = jQuery.extend({}, d[i]);		        
}
if (dtmp.length!=0)
data = data.concat(splitSlots(dtmp,sid));
return data;
},
getCompatSlots:function(d)
{
var data = new Array();
var find = false;
for (var i=0;i<d.length;i++)
{
if (!d[i].quantity)
d[i].quantity = 1000;
var s = -1;    
if (typeof d[i].serviceindex !== 'undefined')
s = d[i].serviceindex;
d[i].service = new Array();
d[i].service[0] = s;    
find = false; 
for (var j=0;j<data.length && !find;j++)
if (d[i].t1==data[j].t1 && d[i].t2==data[j].t2 && (d[i].serviceindex == data[j].serviceindex))
{
data[j].quantity += d[i].quantity;
data[j].currentSelection = data[j].currentSelection || d[j].currentSelection || false;
if (!$.inArray(d[i].service[0],data[j].service))
data[j].service[data[j].service.length] = d[i].service[0]; 
find = true;
}
if (!find)
data[data.length] = jQuery.extend({}, d[i]);             
}
return data;
},
normalizeSelectIndex:function(ind)
{
if (this.emptySelectCheckbox && ind > 0)
ind--;
return ind;
},
show:function()
{
return '<div class="fields '+$.fbuilder.htmlEncode(this.csslayout)+'" id="field'+this.form_identifier+'-'+this.index+'"><label for="'+this.name+'">'+this.title+''+((this.required)?"<span class='r'>*</span>":"")+'</label><div class="dfield fapp"><input class="field avoid_overlapping_before '+((this.required)?" required":"")+'" id="'+this.name+'" name="'+this.name+'" type="hidden" value="" summary="usedSlots"/><input id="'+this.name+'_services" name="'+this.name+'_services" type="hidden" value="0"/><input id="'+this.name+'_capacity" name="'+this.name+'_capacity" type="hidden" value="0"/><input class="" id="tcost'+this.name+'" name="tcost'+this.name+'" type="hidden" value=""/><div class="fieldCalendarService fieldCalendarService'+this.name+'"></div><div class="fieldCalendar fieldCalendar'+this.name+'"></div><div class="slotsCalendar slotsCalendar'+this.name+'"></div><div class="usedSlots usedSlots'+this.name+'"></div><span class="uh">'+this.userhelp+'</span></div><div class="clearer"></div></div>';
},
getSpecialDays:function()
{
var me  = this;
var a = new Array();
if (!me.emptySelectCheckbox || (me.emptySelectCheckbox && $(".fieldCalendarService"+me.name+" select option:selected").index() > 0 ))
{
var ohindex = me.services[me.normalizeSelectIndex($(".fieldCalendarService"+me.name+" select option:selected").index())].ohindex;
for (var i=0;i<me.allOH[ohindex].openhours.length;i++)
if (me.allOH[ohindex].openhours[i].type=="special")
a[a.length] = me.allOH[ohindex].openhours[i].d;
}
return a;
},
getServiceInd:function(sid)
{
var me  = this;
if (typeof me.getServiceIndArr === 'undefined')
{
me.getServiceIndArr = [];
for (var i=0; i< me.services.length;i++)
me.getServiceIndArr["idx"+me.services[i].idx] = i;
}
if (typeof me.getServiceIndArr["idx"+sid] !== 'undefined')
return me.getServiceIndArr["idx"+sid];
else    
return -1;
},
normalizeRanges:function(a)
{
for (var i=0;i<a.length;i++)
{
a[i].t1 = a[i].h1 * 60 + a[i].m1*1;
a[i].t2 = a[i].h2 * 60 + a[i].m2*1;
if (a[i].t1 >= a[i].t2)
a[i].t2 += 24 * 60;
}
},
initcacheOpenHours: function()
{
var me  = this;
for (j=0;j<me.allOH.length;j++)
me.normalizeRanges(me.allOH[j].openhours);
me.cacheOpenHours = [];
for (j=0;j<me.services.length;j++)
{
var ohindex = me.services[j].ohindex;
var arr = [];
for (var i=0;i<me.allOH[ohindex].openhours.length;i++)
{
if (me.allOH[ohindex].openhours[i].type=="special")
{
arr[me.allOH[ohindex].openhours[i].d] = arr[me.allOH[ohindex].openhours[i].d] || [];
arr[me.allOH[ohindex].openhours[i].d][arr[me.allOH[ohindex].openhours[i].d].length] = jQuery.extend({capacity:me.services[j].capacity}, me.allOH[ohindex].openhours[i]);
}
else
{
arr[me.allOH[ohindex].openhours[i].type] = arr[me.allOH[ohindex].openhours[i].type] || [];
arr[me.allOH[ohindex].openhours[i].type][arr[me.allOH[ohindex].openhours[i].type].length] = jQuery.extend({capacity:me.services[j].capacity}, me.allOH[ohindex].openhours[i]);
}
}
me.cacheOpenHours[j] = arr;
}
},
getAvailablePartialSlots: function(d, part,s) 
{   
var me  = this; if (($.inArray(d, me.special_days) == -1))
{
var d2 = $.datepicker.parseDate("yy-mm-dd",d);
if (me.working_dates[d2.getDay()]==0)
return new Array(); 
for( var i = 0, l = me.invalidDates.length; i < l; i++ )
{
if (d2.getTime() === me.invalidDates[i].getTime())
return new Array(); 
}       
}
var capacity_service = me.services[s].capacity;
var a = [];
if (me.cacheOpenHours[s][d])
a = me.cacheOpenHours[s][d].slice(0);
else if (me.cacheOpenHours[s]["d"+$.datepicker.parseDate("yy-mm-dd", d).getDay()])
a = me.cacheOpenHours[s]["d"+$.datepicker.parseDate("yy-mm-dd", d).getDay()].slice(0);
else if (me.cacheOpenHours[s]["all"])
a = me.cacheOpenHours[s]["all"].slice(0);
me.arr[d]	= a;
if (!me.duration)
{
var arr = new Array();
return arr;
}   
var data1 = me.cacheArr[d];            
if (!data1) data1 = new Array();
var duration = parseFloat(me.services[s].duration);
me.duration = duration;
me.bduration = me.duration;
if (!me.bSlotsCheckbox)
me.bduration = me.bSlots*1;
var arr = new Array();
for (var i=0;i<me.arr[d].length;i++)
arr[i] = jQuery.extend({}, me.arr[d][i]);			  		 	      
for (var i=0;i<arr.length;i++)
{
arr[i].t1 = arr[i].h1 * 60 + arr[i].m1*1;
arr[i].t2 = arr[i].h2 * 60 + arr[i].m2*1;
if (arr[i].t1>=arr[i].t2)
arr[i].t2 += 24 * 60;
}		
if (me.ignoreUsedSlots)
var data2 = $.merge(data1.slice(0),[]);
else
{    
me.usedSlots[d] = me.usedSlots[d] || [];
var data2 = $.merge(data1.slice(0),me.usedSlots[d]);
var t = $.datepicker.parseDate("yy-mm-dd", d);
t.setDate(t.getDate() - 1);
var bd = $.datepicker.formatDate("yy-mm-dd", t);
me.usedSlots[bd] = me.usedSlots[bd] || [];
for (var i=0;i<me.usedSlots[bd].length;i++)
{
if ((me.usedSlots[bd][i].h1 > me.usedSlots[bd][i].h2 && me.usedSlots[bd][i].h2!=0) || me.usedSlots[bd][i].h2>24)
{
if (me.usedSlots[bd][i].h1>me.usedSlots[bd][i].h2)
me.usedSlots[bd][i].h2 += 24;    
var obj = jQuery.extend({}, me.usedSlots[bd][i]);
obj.h2 = me.usedSlots[bd][i].h2 - 24;
obj.h1 = 0;obj.m1 = 0;
obj.d = d;				        
data2[data2.length] = obj;
}				    
}
}
for (var i=0;i<data2.length;i++)
{
data2[i].t1 = data2[i].h1 * 60 + data2[i].m1*1;// - me.pb;
data2[i].t2 = data2[i].h2 * 60 + data2[i].m2*1;// + me.pa;
if (typeof data2[i].serviceindex !== 'undefined' && typeof data2[i].nopadding === 'undefined' )
{
try{
if (data2[i].t1==data2[i].t2)  data2[i].t2 += 24 * 60;    
data2[i].t1 -= me.services[data2[i].serviceindex].pb;
data2[i].t2 += me.services[data2[i].serviceindex].pa;
} catch (e) {}
}    			    
}
var data = $.merge(data2,part);
for (var i=0;i<data.length;i++)
{
data[i].t1 = data[i].t1 || (data[i].h1 * 60 + data[i].m1*1);
data[i].t2 = data[i].t2 || (data[i].h2 * 60 + data[i].m2*1);
if (data[i].t1>data[i].t2)
data[i].t2 += 24 * 60;
}	    
if (typeof cp_hourbk_cmpublic !== 'undefined')
data = me.getSplittedSlots(data,s);
data = me.getCompatSlots(data);
for (var i=0;i<data.length;i++)
{		
if (me.avoidOverlaping && (data[i].quantity+me.quantity_selected>capacity_service || (data[i].service.length==0 || (data[i].service.length && data[i].service[0]!=s)))
//|| (!me.avoidOverlaping && (data[i].quantity+me.quantity_selected>capacity_service && (typeof data[i].serviceindex === 'undefined' || data[i].serviceindex==s)) ))
|| (!me.avoidOverlaping && ((data[i].quantity+me.quantity_selected>capacity_service && data[i].serviceindex==s) || typeof data[i].serviceindex === 'undefined') )) 
{
for (var j=0;j<arr.length;j++)
{
if ((data[i].t1 > arr[j].t1) && (data[i].t1 < arr[j].t2)   &&  (data[i].t2 > arr[j].t1) && (data[i].t2 < arr[j].t2))
{
var v1 = {t1:arr[j].t1,  t2:data[i].t1,   h1:arr[j].h1,  h2:data[i].h1,   m1:arr[j].m1,  m2:data[i].m1};
var v2 = {t1:data[i].t2, t2:arr[j].t2,    h1:data[i].h2, h2:arr[j].h2,    m1:data[i].m2, m2:arr[j].m2};
arr.splice(j, 1, v1, v2);
j--;
}
else if ((data[i].t1 > arr[j].t1) && (data[i].t1 < arr[j].t2))
{
arr[j].t2 = data[i].t1;
arr[j].h2 = data[i].h1;
arr[j].m2 = data[i].m1;
} 
else if ((data[i].t2 > arr[j].t1) && (data[i].t2 < arr[j].t2))
{
arr[j].t1 = data[i].t2;
arr[j].h1 = data[i].h2;
arr[j].m1 = data[i].m2;
}
else if ((data[i].t1 <= arr[j].t1) && (data[i].t2 >= arr[j].t2))
{
arr.splice(j, 1);
j--;
}
}
}
}
for (var i=0;i<arr.length;i++)
arr[i].day = d;
if (me.minDate!=="" && me.getMinDate!="")
{
var current = me.getMinDate;
var currenttime = current.getTime()-me.tz*60*60*1000;
for (var i=arr.length-1;i>=0;i--)
{
if ($.datepicker.parseDate("yy-mm-dd",arr[i].day).getTime()+arr[i].t2*60*1000 <= currenttime)
arr.splice(i, 1 );
else if ($.datepicker.parseDate("yy-mm-dd",arr[i].day).getTime()+arr[i].t1*60*1000 <= currenttime)
{
var st = arr[i].t1;//var st = arr[i].t1 + duration + me.pb + me.pa;
while ($.datepicker.parseDate("yy-mm-dd",arr[i].day).getTime() + st*60*1000 <= currenttime)
{
if (!me.bSlotsCheckbox)
st += me.bduration;
else    
st += duration + me.pb + me.pa;
//st += duration + me.pb + me.pa;    
}
var m1 = st % 60;
var h1 = (st - m1)/60;
arr[i].t1 = st;
arr[i].h1 = h1;
arr[i].m1 = m1;
}			                
}        
}
if (me.maxDate!=="" && me.getMaxDate!="")
{
var current = me.getMaxDate;
var currenttime = current.getTime()+me.tz*60*60*1000;
for (var i=arr.length-1;i>=0;i--)
{
if ($.datepicker.parseDate("yy-mm-dd",arr[i].day).getTime()+arr[i].t1*60*1000 >= currenttime)
arr.splice(i, 1 );
else if ($.datepicker.parseDate("yy-mm-dd",arr[i].day).getTime()+arr[i].t2*60*1000 >= currenttime)
{    
var et = arr[i].t1;
while ($.datepicker.parseDate("yy-mm-dd",arr[i].day).getTime() + (et + duration)*60*1000 <= currenttime)
et += duration; 
var m2 = et % 60;
var h2 = (et - m2)/60;
arr[i].t2 = et;
arr[i].h2 = h2;
arr[i].m2 = m2;
}			                
}        
}  
for (var i=arr.length-1;i>=0;i--)
if (arr[i].t1+duration > arr[i].t2 || arr[i].t1 > 24*60)
arr.splice(i, 1 );
return arr;		  
},    	
formattime: function(t,mt) {
if (t<0) t+=(24*60);
t = t % (24*60);
var h = Math.floor(t/60);
var m = t%60;
var suffix = "";
if (mt==0)
{
if (h>12)
{
h = h-12;
suffix = " PM";
}
else if (h==12)
suffix = " PM";
else
{   
if (h==0 && mt!=2) h=12;
suffix = " AM";  
}    
}
return (((h<10)?((mt==2)?"0":"0"):"")+h+":"+(m<10?"0":"")+m)+suffix;									
},
formatString: function(obj,showdate,tz)
{
var me = this;
tz = tz * 60;
if (typeof obj.st === 'undefined')
obj.st = obj.h1*60+obj.m1*1;
if (typeof obj.et === 'undefined')
obj.et = obj.h2*60+obj.m2*1;    
var str = "";
if (showdate)
{
var d = $.datepicker.parseDate("yy-mm-dd", obj.d);
if (tz!=0)
{
if (obj.st+tz<0)
d.setDate(d.getDate() - 1);
else if (obj.st+tz>24*60)    
d.setDate(d.getDate() + 1);
}   
str += "<span class=\"d\">"+$.datepicker.formatDate(me.dateFormat, d)+"</span> ";
}
str += (showdate?"<span class=\"t\">":"");
str += me.formattime(obj.st+tz,me.militaryTime)+(me.showEndTime?("-"+me.formattime(obj.et+tz,me.militaryTime)):"");
str += (showdate?"</span>":"");    
return str;      
},
getCurrentSlots: function(arr,d,s)
{
var me = this;
var duration = parseFloat(me.services[s].duration);
var html = "";
var htmlSlots = new Array();
var pb = 0;
var pa = 0;
var v = false;
var capacity_service = me.services[s].capacity;
if (true)
{ 
var compactUsedSlots = me.getCompatSlots(me.htmlUsedSlots[d])             
for (var i=0;i<compactUsedSlots.length;i++)
{ 
//if (compactUsedSlots[i].quantity>=capacity_service && compactUsedSlots[i].serviceindex==s)
if (compactUsedSlots[i].serviceindex==s)
{
compactUsedSlots[i].st = compactUsedSlots[i].h1 * 60 + compactUsedSlots[i].m1;
compactUsedSlots[i].t = $.datepicker.parseDate("yy-mm-dd",compactUsedSlots[i].d).getTime()+compactUsedSlots[i].st*60*1000;
compactUsedSlots[i].html = "";		    	                
var v = false;
if (me.minDate!=="" && me.getMinDate!="") //check with the min date
{
var current = me.getMinDate;
var currenttime = current.getTime()-me.tz*60*60*1000;			                        
if (compactUsedSlots[i].t > currenttime)
{   
v = true;
}
}
else
v = true;
if (v)
{
if (compactUsedSlots[i].quantity>=capacity_service || compactUsedSlots[i].currentSelection)
compactUsedSlots[i].html = '<div s="'+s+'" h1="'+compactUsedSlots[i].h1+'" m1="'+compactUsedSlots[i].m1+'" h2="'+compactUsedSlots[i].h2+'" m2="'+compactUsedSlots[i].m2+'" style="'+(!me.usedSlotsCheckbox?"display:none":"")+'" class="htmlUsed  '+((typeof compactUsedSlots[i].s !== 'undefined')?compactUsedSlots[i].s.replace(/ /g,"").toLowerCase()+" old":" choosen")+'"><a '+((typeof compactUsedSlots[i].e !== 'undefined')?"title=\""+compactUsedSlots[i].e+"\"":"")+'>'+me.formatString(compactUsedSlots[i],false,me.tz)+'</a>'+((typeof compactUsedSlots[i].e !== 'undefined')?"<div class=\"ahbmoreinfo\">"+compactUsedSlots[i].e+"</div>":"")+'</div>';
compactUsedSlots[i].availableslot = false;
htmlSlots[htmlSlots.length] = compactUsedSlots[i];
}       
}
}
}
if ((typeof specialPadding === 'undefined'))
{
pb = me.pb;
pa = me.pa;
}
for (var i=0;i<arr.length;i++)
{
st = arr[i].t1 || (arr[i].h1 * 60+arr[i].m1*1);
et = arr[i].t2 || (arr[i].h2 * 60+arr[i].m2*1);
if (st >= et)
et += 24 * 60;  
st += me.pb;
while (st + duration + me.pa <=et  && st < 24 * 60)
{ 
html = "<div class=\"availableslot\"><a  s=\""+s+"\"  href=\"\" d=\""+arr[i].day+"\" h1=\""+Math.floor((st)/60)+"\" m1=\""+((st)%60)+"\" h2=\""+Math.floor((st+duration)/60)+"\" m2=\""+((st+duration)%60)+"\">"+me.formatString({st:st,et:st+duration},false,me.tz)+((typeof cp_hourbk_cmpublic !== 'undefined')?"<span class=\"ahb_slot_availability\"><span class=\"p\">ahbslotavailabilityP</span><span class=\"t\">ahbslotavailabilityT</span></span>":"")+"</a></div>";
htmlSlots[htmlSlots.length] = {availableslot:true,st:st,serviceindex:s,h1:Math.floor((st)/60),m1:((st)%60),h2:Math.floor((st+duration)/60),m2:((st+duration)%60),html:html,t:$.datepicker.parseDate("yy-mm-dd",arr[i].day).getTime()+st*60*1000};
if (!me.bSlotsCheckbox)
st += me.bduration;
else    
st += me.bduration + pa + pb;
}
}
htmlSlots.sort(function(a, b){
if ((typeof cp_hourbk_cmpublic !== 'undefined') && (a.t == b.t))
{
if ((typeof a.quantity !== 'undefined') && (typeof b.quantity === 'undefined'))
{
b.html = b.html.replace("ahbslotavailabilityP",(capacity_service - a.quantity));
b.quantity = a.quantity;
}    
else if ((typeof b.quantity !== 'undefined') && (typeof a.quantity === 'undefined'))
{
a.html = a.html.replace("ahbslotavailabilityP",(capacity_service - b.quantity));
a.quantity = b.quantity;
}    
}
return a.t - b.t
});
//remove duplicates
htmlSlots = htmlSlots.reduce(function(field, e1){  
var matches = field.filter(function(e2){return e1.html== e2.html}); 
if (matches.length == 0){ 
field.push(e1);  
}return field;
}, []);
htmlSlots = htmlSlots.reduce(function(field, e1){  
var matches = field.filter(function(e2){return e1.t== e2.t}); 
if (matches.length == 0){ 
field.push(e1);  
}
else
{
for (var i=0;i<field.length;i++)
if (field[i].t==e1.t && !field[i].availableslot && (e1.availableslot || e1.currentSelection))
{
field[i]= e1;
break;        
}
}
return field;
}, []);
me.usedSlots[d] = me.usedSlots[d] || [];	
if (me.usedSlots[d].length>0 && htmlSlots.length>0)
for (var i=0;i<me.usedSlots[d].length;i++)
for (var j=0;j<htmlSlots.length;j++)
if (htmlSlots[j].serviceindex==me.usedSlots[d][i].serviceindex && htmlSlots[j].h1==me.usedSlots[d][i].h1 && htmlSlots[j].m1==me.usedSlots[d][i].m1 && htmlSlots[j].h2==me.usedSlots[d][i].h2 && htmlSlots[j].m2==me.usedSlots[d][i].m2 )
{
if (htmlSlots[j].html.indexOf("currentSelection")==-1) htmlSlots[j].html = htmlSlots[j].html.replace("htmlUsed","htmlUsed currentSelection");
if (htmlSlots[j].html.indexOf("currentSelection")==-1) htmlSlots[j].html = htmlSlots[j].html.replace("availableslot","availableslot currentSelection");
}
return htmlSlots;    
},
getAvailableSlotsByService: function(d,s)
{
var me = this;
var c = "s"+s+"q"+me.quantity_selected+"d"+d;
if (me.tz==0 && typeof me.slotsDate[c]!== 'undefined')
return me.slotsDate[c];		    
function setHtmlUsedSlots(d,st,et)
{
st = st * 60;
et = et * 60;
var htmlSlots = new Array();
//if (me.bSlotsCheckbox && me.usedSlotsCheckbox)
if (true)//if (me.usedSlotsCheckbox)
{
me.cacheArr[d] = me.cacheArr[d] || [];
for (var i=0;i<me.cacheArr[d].length;i++)
{    
me.cacheArr[d][i].t1 = me.cacheArr[d][i].t1 || me.cacheArr[d][i].h1*60+me.cacheArr[d][i].m1*1;
me.cacheArr[d][i].t2 = me.cacheArr[d][i].t2 || me.cacheArr[d][i].h2*60+me.cacheArr[d][i].m2*1;
if (me.cacheArr[d][i].t1>=me.cacheArr[d][i].t2)
me.cacheArr[d][i].t2 += 24 * 60;
if (st<=me.cacheArr[d][i].t1 && et>=me.cacheArr[d][i].t1) 
htmlSlots[htmlSlots.length] = jQuery.extend({}, me.cacheArr[d][i]);
}
for (var i=0;me.usedSlots[d] && i<me.usedSlots[d].length;i++) 
{
me.usedSlots[d][i].t1 = me.usedSlots[d][i].t1 || me.usedSlots[d][i].h1*60+me.usedSlots[d][i].m1*1;
me.usedSlots[d][i].t2 = me.usedSlots[d][i].t2 || me.usedSlots[d][i].h2*60+me.usedSlots[d][i].m2*1;
if (me.usedSlots[d][i].t1>=me.usedSlots[d][i].t2)
me.usedSlots[d][i].t2 += 24 * 60;
if (st<=me.usedSlots[d][i].t1 && et>=me.usedSlots[d][i].t1)
htmlSlots[htmlSlots.length] = jQuery.extend({}, me.usedSlots[d][i]);
}
}
return htmlSlots;		        
}
var day = $.datepicker.parseDate("yy-mm-dd", d);
if (this.tz==0)
{
me.htmlUsedSlots[d] = setHtmlUsedSlots(d,0,24);
var arr = this.getAvailablePartialSlots(d,[{h1:0,m1:0,h2:0,m2:0}],s);
}    
else if (this.tz > 0)
{
day.setDate(day.getDate() - 1);
var d1 = $.datepicker.formatDate("yy-mm-dd",day);
var arr = $.merge(this.getAvailablePartialSlots(d1,[{h1:0,m1:0,h2:24-this.tz,m2:0}],s),this.getAvailablePartialSlots(d,[{h1:24-this.tz,m1:0,h2:24,m2:0}],s));
me.htmlUsedSlots[d] = $.merge(setHtmlUsedSlots(d1,24-this.tz,24), setHtmlUsedSlots(d,0,24-this.tz));
}  
else
{
day.setDate(day.getDate() + 1);
var d1 = $.datepicker.formatDate("yy-mm-dd",day);
var arr = $.merge(this.getAvailablePartialSlots(d,[{h1:0,m1:0,h2:this.tz*-1,m2:0}],s),this.getAvailablePartialSlots(d1,[{h1:this.tz*-1,m1:0,h2:24,m2:0}],s));
me.htmlUsedSlots[d] = $.merge(setHtmlUsedSlots(d,this.tz*-1,24), setHtmlUsedSlots(d1,0,this.tz*-1));
}
me.slotsDate[c] = arr;
return arr;
},
getAvailableSlots: function(d)
{     
var me = this;
var c = "s"+(me.showAllServices?"":me.service_selected)+"q"+me.quantity_selected+"d"+d;
if (me.tz==0 && typeof me.slotsDate[c]!== 'undefined')
return me.slotsDate[c];
var a_max = [];
if (!me.showAllServices)
a_max = this.getAvailableSlotsByService(d,me.service_selected);
else
{
me.availableSlotsByService[d] = [];
for (var i=0; i< me.services.length;i++)
{ 
me.availableSlotsByService[d][i] = this.getAvailableSlotsByService(d,i);
if (me.availableSlotsByService[d][i].length > a_max.length)
a_max = me.availableSlotsByService[d][i].slice(0);			                
}
}
me.slotsDate[c] = a_max;
return a_max;    
},
rC: function(d) 
{      
var me = this;
var day = $.datepicker.formatDate('yy-mm-dd', d);
var c =  new Array(day,"d"+day);
if (me.working_dates[d.getDay()]==0  && ($.inArray(day, me.special_days) == -1))
c.push("nonworking","ui-datepicker-unselectable","ui-state-disabled");
for( var i = 0, l = me.invalidDates.length; i < l; i++ )
{
if (d.getTime() === me.invalidDates[i].getTime()   && ($.inArray(day, me.special_days) == -1))
c.push("nonworking","ui-datepicker-unselectable","ui-state-disabled","invalidDate");
}
if (me.minDate!=="" && me.getMinDate!="" && day < $.datepicker.formatDate('yy-mm-dd', me.getMinDate))
c.push("nonworking","ui-datepicker-unselectable","ui-state-disabled","beforemindate");
if (me.maxDate!=="" && me.getMaxDate!="" && day > $.datepicker.formatDate('yy-mm-dd', me.getMaxDate))
c.push("nonworking","ui-datepicker-unselectable","ui-state-disabled","aftermaxdate");    
if (($.inArray("ui-datepicker-unselectable",c)==-1) &&  !me.emptySelectCheckbox || (me.emptySelectCheckbox && $(".fieldCalendarService"+me.name+" select option:selected").index() > 0 ))
{
var arr = me.getAvailableSlots(day);
if (arr.length==0 && me.notShowBookedDate)
c.push("nonworking","ui-datepicker-unselectable","ui-state-disabled","notavailslot");
if (typeof cp_hourbk_cmpublic !== 'undefined')
{   
var used = 0; 
var cclass = c.join(" ");
var q = 0;
var total = 0;
if (!me.showAllServices) 
{      
var htmlSlots = me.getCurrentSlots(arr,day,me.service_selected);
for (var i=0;i<htmlSlots.length;i++)
if (htmlSlots[i].html!="")
{
q++;
used += ((typeof htmlSlots[i].quantity !== 'undefined')?htmlSlots[i].quantity:0) ;
}
total += me.services[me.service_selected].capacity*q;    
}        
else
{
for (var ii=0; ii< me.services.length;ii++)
{    
q = 0;
var htmlSlots = me.getCurrentSlots(arr,day,ii);
for (var i=0;i<htmlSlots.length;i++)
if (htmlSlots[i].html!="")
{
q++;
used += ((typeof htmlSlots[i].quantity !== 'undefined')?htmlSlots[i].quantity:0) ;
}
total += me.services[ii].capacity*q;        
}    
}                        
if (cclass.indexOf("nonworking")==-1)
cclass +=" ahb_booked"+Math.floor(10*used/total);
}    
} 
if (typeof cclass === 'undefined') 
var cclass = c.join(" ");          
return [(cclass.indexOf("nonworking")==-1),cclass];		        
},		
after_show:function()
{
function closeOtherDatepicker(){
$('#ui-datepicker-div').css("display","none");
}
setTimeout(closeOtherDatepicker,100);
try {$.fn.datepicker.noConflict();} catch (e) {}
if (typeof cp_hourbk_timezone !== 'undefined') 
{
var gmt = (parseFloat(cp_hourbk_timezone));
var local = (new Date().getTimezoneOffset()  * -1)/60;			 
this.tz = local - gmt;
}		    		    
var me  = this,
e   = $( '#field' + me.form_identifier + '-' + me.index + ' .fieldCalendar'+me.name ),
d   = $( '#field' + me.form_identifier + '-' + me.index + ' .fieldCalendarService'+me.name ),
str = "",
op = "";
var capacity = "";
for (var i=0; i< me.services.length;i++)
capacity += ((i!=0)?";":"")+me.services[i].capacity;
$('#field' + me.form_identifier + '-' + me.index + ' #'+me.name+'_capacity').val(capacity);
$('#field' + me.form_identifier + '-' + me.index).parents("form").bind('invalid-form.validate', function () {
setTimeout(function(){
if ($('#field' + me.form_identifier + '-' + me.index + ' #'+me.name).hasClass("cpefb_error") && $('#field' + me.form_identifier + '-' + me.index).parents("form").find(".field.cpefb_error").attr("id")==$('#field' + me.form_identifier + '-' + me.index + ' #'+me.name).attr("id"))
{
$("html, body").animate({ 
scrollTop: $('#field' + me.form_identifier + '-' + me.index + ' #'+me.name).parents(".dfield").find(".ahbfield_service").offset().top 
}, 100); 
}
},100);
});  
e.addClass("notranslate")
if (me.openhours.length>0) {
if (!me.openhours[0].name)
{
var obj = {name:"Default",openhours:me.openhours.slice(0)};
me.openhours = new Array();			     
me.openhours[0] = obj;			     
}
me.allOH = new Array();
me.allOH = me.openhours.slice(0);
me.openhours = new Array();
}
var dd = "";
if (me.initialapp!="")
{   
try{
var s = me.initialapp.split(";");
var s2 = "";
var ind = 0;
for (var i=0;i<s.length;i++)
{
if (s[i]!="")
{
s2 = s[i].split(" ");
var tt = s2[1].split("/");
var t1 = tt[0].split(":");
var t2 = tt[1].split(":");
var ind = s2[2]*1;
var q = s2[3]*1; 
dd = s2[0];
me.usedSlots[dd] = me.usedSlots[dd] || [];
obj = {h1:t1[0]*1,m1:t1[1]*1,h2:t2[0]*1,m2:t2[1]*1,d:dd,serviceindex:ind,price:parseFloat(me.services[ind].price)*parseFloat(q),quantity:q};	            	
me.usedSlots[dd][me.usedSlots[dd].length] = obj; 
me.allUsedSlots[me.allUsedSlots.length] = obj;
}
} 
me.initialServiceInd = ind;  
} catch (e) {}
}
for (var i=0; i< me.services.length;i++)
me.services[i].ohindex = me.services[i].ohindex || 0;
if (me.autonum==0)
for (var i=0; i< me.services.length;i++)
{   
me.autonum++; 
me.services[i].idx = me.autonum; 
}
me.initcacheOpenHours();           
function onChangeDateOrService(d)
{
if (!(!me.emptySelectCheckbox || (me.emptySelectCheckbox && $(".fieldCalendarService"+me.name+" select option:selected").index() > 0 )))
{
$( '#field' + me.form_identifier + '-' + me.index + ' .slotsCalendar'+me.name ).html("");
return;
}   
function getSlots(d)
{		
var data1 = me.cacheArr[d];
var duration = me.duration;
me.bduration = me.duration;
if (!me.bSlotsCheckbox)
me.bduration = me.bSlots*1;	
var arr = me.getAvailableSlots(d);
var nextdateAvailable = $.datepicker.parseDate("yy-mm-dd", d);
var c = "s"+(me.showAllServices?"":me.service_selected)+"q"+me.quantity_selected;
var s = $( '#field' + me.form_identifier + '-' + me.index + ' .slotsCalendar'+me.name );
var i =0;
if (me.notShowBookedDate && (me.maxNumberOfApp==0 || me.allUsedSlots.length<me.maxNumberOfApp) && arr.length==0 && (!me.usedSlots[d] || me.usedSlots[d].length==0 || me.service_change))
{
me.service_change = false;
while ((!DisableSpecificDates(nextdateAvailable) || (arr.length==0)) && i<400)
{
i++;
nextdateAvailable.setDate(nextdateAvailable.getDate() + 1);
arr = me.getAvailableSlots($.datepicker.formatDate("yy-mm-dd",nextdateAvailable));
}  
if (arr.length>0 )  
{
e.datepicker("setDate", nextdateAvailable);
me.getD = nextdateAvailable;
onChangeDateOrService($.datepicker.formatDate("yy-mm-dd", nextdateAvailable));  
}
else
{
e.datepicker("setDate", me.getMinDate);
s.html("<div class=\"slots\">"+cp_hourbk_nomore_label+"</div>");                           
}
return;
}
me.service_change = false;
function getStrSlots(arr,d,s)
{	     
var str = "";				
var htmlSlots = me.getCurrentSlots(arr,d,s);
var capacity_service = me.services[s].capacity;
for (var i=0;i<htmlSlots.length;i++)
{
if (typeof cp_hourbk_cmpublic !== 'undefined')
{
htmlSlots[i].html = htmlSlots[i].html.replace("ahbslotavailabilityP",capacity_service);
htmlSlots[i].html = htmlSlots[i].html.replace("ahbslotavailabilityT",capacity_service);
}
str += htmlSlots[i].html;          
}
return str;
}
var str = "";
if (!me.showAllServices)
str = getStrSlots(arr,d,me.service_selected)
else
{
for (var i=0; i< me.services.length;i++)
{    
str_s = getStrSlots(me.availableSlotsByService[d][i],d,i);
if (str_s!="")
str += '<div class="service service'+i+'"><div class="service_title">'+me.services[i].name+'</div>'+str_s+'</div>';
}    
} 
if (str=="") str = cp_hourbk_nomore_label;
var before = "";
if (s.find(".slots").length>0)
{
before = s.find(".slots").attr("d");
}  
s.html("<div class=\"slots\" d=\""+d+"\"><span>"+$.datepicker.formatDate(me.dateFormat, $.datepicker.parseDate("yy-mm-dd", d))+"</span><br />"+str+"</div>");
if (before!="" && before!=d)
{
s.find(".slots span:first").hide().show(200);
}
var str1="",str2="";
me.allUsedSlots = me.allUsedSlots || [];
me.allUsedSlots.sort(function(a, b){ return ($.datepicker.parseDate("yy-mm-dd", a.d).getTime()+(a.h1*60+a.m1)*60*1000) - ($.datepicker.parseDate("yy-mm-dd", b.d).getTime()+(b.h1*60+b.m1)*60*1000)});
j = 0;
var total = 0;
for (var i=0;i<me.allUsedSlots.length;i++)
{
total += me.allUsedSlots[i].price;		  			    
str1 += "<div class=\"ahb_list\" d=\""+me.allUsedSlots[i].d+"\" quantity=\""+me.allUsedSlots[i].quantity+"\" s=\""+me.allUsedSlots[i].serviceindex+"\" h1=\""+me.allUsedSlots[i].h1+"\" m1=\""+me.allUsedSlots[i].m1+"\" h2=\""+me.allUsedSlots[i].h2+"\" m2=\""+me.allUsedSlots[i].m2+"\" ><span class=\"ahb_list_time\">"+me.formatString(me.allUsedSlots[i],true,me.tz)+"</span><span class=\"ahb_list_service\">"+me.services[me.allUsedSlots[i].serviceindex].name+"</span><span class=\"ahb_list_quantity ahb_list_quantity"+me.allUsedSlots[i].quantity+"\">("+me.allUsedSlots[i].quantity+")</span><a href=\"\" class=\"cancel\" d=\""+d+"\" i=\""+j+"\" iall=\""+i+"\">["+(cp_hourbk_cancel_label?cp_hourbk_cancel_label:'cancel')+"]</a>"+(((typeof cp_hourbk_repeat !== 'undefined'))?showrepeat(me,i):"")+"</div>";
str2 += ((str2=="")?"":";")+me.allUsedSlots[i].d+" "+me.formattime(me.allUsedSlots[i].h1*60+me.allUsedSlots[i].m1*1,2)+"/"+me.formattime(me.allUsedSlots[i].h2*60+me.allUsedSlots[i].m2*1,2)+" "+me.allUsedSlots[i].serviceindex+" "+me.allUsedSlots[i].quantity;
if (me.allUsedSlots[i].d==d)
j++;
}
me.sub_cost = total;
total = me.sub_cost + me.extras;
total = total*(1+me.percent/100);
total = total.toFixed(2);
if (me.showTotalCost && (str1!=""))
str1 += '<div class="totalCost"><span>'+cp_hourbk_cost_label+'</span><span class="n"> '+me.showTotalCostFormat.replace("{0}", total)+'</span></div>';
$( '.usedSlots'+me.name ).html(str1);	
$( '#field' + me.form_identifier + '-' + me.index + ' #'+me.name ).val(str2);		  		    
$( '#field' + me.form_identifier + '-' + me.index + ' #tcost'+me.name ).val(total);
$( '#field' + me.form_identifier + '-' + me.index + ' #'+me.name ).change();
try {
$( "#fbuilder .slots div a" ).tooltip({
position: {
my: "left top+10"
},
open: function (event, ui) {
$(this).tooltip( "option", "content", $(this).parent().find(".ahbmoreinfo").html() );
},
tooltipClass: "ahbtooltip"
});
} catch (e) {}
$( '.slotsCalendar' + me.name + ' .slots a').off("click").on("click", function() 
{
var q = parseFloat($(".fieldCalendarService"+me.name+" select.ahbfield_quantity option:selected").val());
if ((me.maxNumberOfApp==1 && me.allUsedSlots.length==me.maxNumberOfApp) || (me.allUsedSlots.length>0 && me.allUsedSlots[0].quantity!=q && !me.allowDifferentQuantities)) //cancel previous slot
{
for (var i = 0; (i<me.allUsedSlots.length); i++)
{
var c = "s"+me.allUsedSlots[i].serviceindex+"q"+me.allUsedSlots[i].quantity+"d"+me.allUsedSlots[i].d;
var c1 = "sq"+me.allUsedSlots[i].quantity+"d"+me.allUsedSlots[i].d;
delete me.slotsDate[c];
delete me.slotsDate[c1];
me.usedSlots[me.allUsedSlots[i].d] = [];		  			            
}
me.allUsedSlots = [];
}
if ($(this).parents("fieldset").hasClass("ahbgutenberg_editor"))
return false;
$( "#field" + me.form_identifier + "-" + me.index + " div.cpefb_error").remove();	
if ($(this).parent().hasClass("htmlUsed"))
return false;
if ($(this).parent().hasClass("currentSelection") && !me.allowSelectSameSlot)
return false;    
me.allUsedSlots = me.allUsedSlots || [];
if (me.maxNumberOfApp==0 || me.allUsedSlots.length<me.maxNumberOfApp)
{	
var d = $(this).attr("d");
me.usedSlots[d] = me.usedSlots[d] || [];	
var ind = $(this).attr("s")*1;  				    
obj = {currentSelection:true,h1:$(this).attr("h1")*1,m1:$(this).attr("m1")*1,h2:$(this).attr("h2")*1,m2:$(this).attr("m2")*1,d:d,serviceindex:ind,price:parseFloat(me.services[ind].price)*q,quantity:q};	            	
me.usedSlots[d][me.usedSlots[d].length] = obj; 
me.allUsedSlots[me.allUsedSlots.length] = obj;
$(document).trigger("beforeClickSlot",{name:me.name, d:d});
var c = "s"+ind+"q"+q+"d"+d;
var c1 = "sq"+q+"d"+d;
delete me.slotsDate[c];
delete me.slotsDate[c1];
onChangeDateOrService($.datepicker.formatDate('yy-mm-dd', me.getD));
}
else
alert($.validator.messages.maxapp.replace("{0}",me.maxNumberOfApp));
return false;
});		  			
$( '.usedSlots'+me.name+ ' a.cancel').off("click").on("click", function() 
{
var d = $(this).parents(".ahb_list").attr("d");
var h1 = $(this).parents(".ahb_list").attr("h1");
var m1 = $(this).parents(".ahb_list").attr("m1");
var h2 = $(this).parents(".ahb_list").attr("h2");
var m2 = $(this).parents(".ahb_list").attr("m2");
var s = $(this).parents(".ahb_list").attr("s");
me.usedSlots[d] = me.usedSlots[d] || [];
var find = false;
for (var i = 0; (i<me.usedSlots[d].length && !find); i++)
if (me.usedSlots[d][i].d==d && me.usedSlots[d][i].h1==h1 && me.usedSlots[d][i].m1==m1 && me.usedSlots[d][i].h2==h2 && me.usedSlots[d][i].m2==m2 && me.usedSlots[d][i].serviceindex==s)
{
find = true;
me.usedSlots[d].splice(i, 1);    
}	
var find = false;
for (var i = 0; (i<me.allUsedSlots.length && !find); i++)
if (me.allUsedSlots[i].d==d && me.allUsedSlots[i].h1==h1 && me.allUsedSlots[i].m1==m1 && me.allUsedSlots[i].h2==h2 && me.allUsedSlots[i].m2==m2 && me.allUsedSlots[i].serviceindex==s)
{
find = true;
me.allUsedSlots.splice(i, 1);    
}
var c = "s"+s+"q"+me.quantity_selected+"d"+d;
var c1 = "sq"+me.quantity_selected+"d"+d;
delete me.slotsDate[c];
delete me.slotsDate[c1];
e.datepicker("setDate", me.getD);
onChangeDateOrService($.datepicker.formatDate('yy-mm-dd', me.getD));
return false;
});
}		  					
getSlots(d);	  
$(document).trigger("afterOnChange",{name:me.name, me:me});			
}		  	
if (typeof cpapphourbk_in_admin !== 'undefined')
{	  	  	      
me.minDate = "";
me.maxDate = "";
me.maxNumberOfApp = 0;
}
if (!me.loadOK)
{  	
me.formId = $(".fieldCalendarService"+me.name).parents("form").find('input[type="hidden"][name$="cp_appbooking_id"]').val();
$.ajax(
{
dataType : 'json',
type: "POST",
url : document.location.href,
cache : true,
data :  { cp_app_action: 'get_slots',
formid: me.formId,
initialID: me.initialID,
formfield: me.name.replace(me.form_identifier, "")   
},
success : function( data ){
for (var i=0;i<data.length;i++)
{
var dd = data[i].d;
if (typeof data[i].sid !== 'undefined')
data[i].serviceindex = me.getServiceInd(data[i].sid);
if (data[i].serviceindex==-1)
delete data[i].serviceindex;
me.cacheArr[dd] = me.cacheArr[dd] || [];
me.cacheArr[dd][me.cacheArr[dd].length] = data[i];
if ((data[i].h1>data[i].h2 && data[i].h2!=0) || data[i].h2>24)
{
if (data[i].h1>data[i].h2)
data[i].h2 += 24;    
var obj = jQuery.extend({}, data[i]);
obj.h2 = data[i].h2 - 24;
obj.h1 = 0;obj.m1 = 0;				                
var d = $.datepicker.parseDate("yy-mm-dd", dd);
d.setDate(d.getDate() + 1);
obj.d = $.datepicker.formatDate("yy-mm-dd", d);				                
data[i].h2 = 24;
me.cacheArr[obj.d] = me.cacheArr[obj.d] || [];
me.cacheArr[obj.d][me.cacheArr[obj.d].length] = obj;    
}				    
}
me.slotsDate = [];
me.loadOK = true;				      			
}
});	
}
this.invalidDates = this.invalidDates.replace( /\s+/g, '' );
try{
var df = "mm/dd/yy";
if (this.invalidDates.indexOf(".")!=-1)
df = me.dateFormat;
if( !/^\s*$/.test( this.invalidDates ) )
{
var counter = 0, dates = this.invalidDates.split( ',' );
this.invalidDates = [];
for( var i = 0, h = dates.length; i < h; i++ )
{
var range = dates[ i ].split( '-' );                    
if( range.length == 2 )
{
var fromD = $.datepicker.parseDate(df,range[ 0 ]),
toD = $.datepicker.parseDate(df,range[ 1 ]);
while( fromD <= toD )
{
if (fromD !== null)
{
this.invalidDates[ counter ] = fromD;
var tmp = new Date( fromD.valueOf() );
tmp.setDate( tmp.getDate() + 1 );
fromD = tmp;
counter++;  
}
}
}
else
{
for( var j = 0, k = range.length; j < k; j++ )
{
if ($.datepicker.parseDate(df,range[ j ]) !== null)
{
this.invalidDates[ counter ] = $.datepicker.parseDate(df,range[ j ]);
counter++;
}
}
}
}
}
} catch (e) {}
if ($.validator.messages.date_format && $.validator.messages.date_format!="")	
me.dateFormat = $.validator.messages.date_format;
var capacity = 1;    
for (var i=0;i<me.services.length;i++)
{    
str += '<option value="'+me.services[i].duration+'">'+me.services[i].name+'</option>';
me.services[i].capacity = (parseFloat(me.services[i].capacity)>0)?me.services[i].capacity:1;
if (capacity<me.services[i].capacity)
capacity = me.services[i].capacity;
}
if (me.emptySelectCheckbox) 
str = '<option value="">'+ me.emptySelect +'</option>'+ str ;
var str2 = "";    
for (var i=1;i<=me.services[0].capacity;i++)
str2 += '<option value="'+i+'">'+i+'</option>';
d.html('<select class="ahbfield_service">'+str+'</select><div class="ahbfield_quantity_div" '+((!me.showQuantity)?"style='display:none'":"")+'><label class="ahbfield_quantity_label">'+((typeof cp_hourbk_quantity_label !== 'undefined')?cp_hourbk_quantity_label:'Quantity')+'</label><br /><select class="ahbfield_quantity" autocomplete="off">'+str2+'</select></div>');
me.service_selected = me.normalizeSelectIndex($(".fieldCalendarService"+me.name+" select.ahbfield_service option:selected").index());
me.quantity_selected = parseFloat($(".fieldCalendarService"+me.name+" select.ahbfield_quantity option:selected").val());
me.duration = parseFloat(me.services[me.service_selected].duration);		  	
me.pa = me.services[me.service_selected].pa * 1 || 0;		  			  	
me.pb = me.services[me.service_selected].pb * 1 || 0;
$(".fieldCalendarService"+me.name+" select.ahbfield_service").bind("change", function() 
{
me.service_change = true;
me.service_selected = me.normalizeSelectIndex($(".fieldCalendarService"+me.name+" select.ahbfield_service option:selected").index());	
me.duration = parseFloat(me.services[me.service_selected].duration);	
me.pa = me.services[me.service_selected].pa * 1 || 0;		  			  	
me.pb = me.services[me.service_selected].pb * 1 || 0;
//me.cacheOpenHours = new Array();
me.special_days = me.getSpecialDays();
var str2 = "";    
for (var i=1;i<=me.services[me.service_selected].capacity;i++)
str2 += '<option value="'+i+'">'+i+'</option>';
$(".fieldCalendarService"+me.name+" select.ahbfield_quantity").html(str2);
me.quantity_selected = parseFloat($(".fieldCalendarService"+me.name+" select.ahbfield_quantity option:selected").val());
if (typeof me.getDMin!='undefined') me.getD = me.getDMin;
$( '#field' + me.form_identifier + '-' + me.index + ' .fieldCalendar'+me.name ).datepicker( "option", "beforeShowDay", function(d){return me.rC(d)} );
onChangeDateOrService($.datepicker.formatDate('yy-mm-dd', me.getD));
});
$(".fieldCalendarService"+me.name+" select.ahbfield_quantity").bind("change", function() 
{
if (!me.allowDifferentQuantities)
{
me.quantity_selected = parseFloat($(".fieldCalendarService"+me.name+" select.ahbfield_quantity option:selected").val());
me.allUsedSlots = me.allUsedSlots || [];
for (var i=0;i<me.allUsedSlots.length;i++)
{
var find = false;
var s = me.allUsedSlots[i];
var arr = me.getAvailableSlotsByService(s.d,s.serviceindex);
for (j=0;j<arr.length && !find;j++)
{
if (s.h1*60+s.m1*1>=arr[j].t1 && s.h2*60+s.m2*1<=arr[j].t2)
find = true;
}		  	         
me.usedSlots[s.d] = me.usedSlots[s.d] || [];
f = false;
for (var j=0;j<me.usedSlots[s.d].length && !f;j++)
{   
if (me.usedSlots[s.d][j].h1==s.h1 && me.usedSlots[s.d][j].m1==s.m1 && me.usedSlots[s.d][j].h2==s.h2 && me.usedSlots[s.d][j].m2==s.m2 && me.usedSlots[s.d][j].serviceindex==s.serviceindex)
{
f = true;
if (find)// change the quantity or remove if not available
{
me.allUsedSlots[i].quantity = me.quantity_selected;
me.usedSlots[s.d][j].quantity = me.quantity_selected;
me.allUsedSlots[i].price = parseFloat(me.services[s.serviceindex].price)*me.quantity_selected;
me.usedSlots[s.d][j].price = me.allUsedSlots[i].price;
}
else
{
me.usedSlots[s.d].splice(j, 1);
me.allUsedSlots.splice(i, 1);
i--;
}    
}
}
}
}
$( '#field' + me.form_identifier + '-' + me.index + ' .fieldCalendar'+me.name ).datepicker( "option", "beforeShowDay", function(d){return me.rC(d)} );
onChangeDateOrService($.datepicker.formatDate('yy-mm-dd', me.getD));
});
$("#"+me.name).bind("change", function() 
{
if ($(this).attr("reload")=="reload")
{              
$(this).attr("reload","");
onChangeDateOrService($.datepicker.formatDate('yy-mm-dd', me.getD));
$( '#field' + me.form_identifier + '-' + me.index + ' .fieldCalendar'+me.name ).datepicker( "option", "beforeShowDay", function(d){return me.rC(d)} );
}
});
try{
me.special_days = me.getSpecialDays();
} catch (e) {} 
var hrs = 0;
var mindatetime = "";
me.getMinDate = "";
if (me.minDate!=="")
{	
if (me.minDate.indexOf("@")!= -1)
{
var a = me.minDate.split("@")
me.minDate = a[0];
mindatetime = a[1];   
}
if ((me.minDate.length < 6) && me.minDate.indexOf("h")!= -1)
{		            
if (me.minDate.indexOf(" ")!= -1)
{
var a = me.minDate.split(" ");
var find = false;
for (var i=0;(i<a.length && !find);i++)
{
if (a[i].indexOf("h")!= -1)
{
find = true;
hrs = parseFloat(a[i].replace("h",""));
me.minDate = me.minDate.replace(a[i],"");
}
}
}
else
{
hrs = parseFloat(me.minDate.replace("h",""));
me.minDate = 0;
}
}
}
if (me.maxDate!=="")
{	
if ((me.maxDate.length < 6) && me.maxDate.indexOf("h")!= -1)
{		            
if (me.maxDate.indexOf(" ")!= -1)
{
var a = me.maxDate.split(" ");
var find = false;
for (var i=0;(i<a.length && !find);i++)
{
if (a[i].indexOf("h")!= -1)
{
find = true;
var hrsMax = parseFloat(a[i].replace("h",""));
me.maxDate = me.maxDate.replace(a[i],"");
}
}
}
else
{
var hrsMax = parseFloat(me.maxDate.replace("h",""));
var htmp = hrsMax % 24;
me.maxDate = (hrsMax-htmp)/24; 
hrsMax = htmp;
}
}
}       
e.datepicker({numberOfMonths:parseFloat(me.numberOfMonths),
//firstDay:parseFloat(me.firstDay),
//minDate:me.minDate,
//maxDate:me.maxDate,
showWeek: me.showWeek,
dateFormat:me.dateFormat,
changeMonth: me.showDropdown, 
changeYear: me.showDropdown,
yearRange: ((me.showDropdown)?me.dropdownRange:""),
onSelect: function(d,inst) {
me.getD = e.datepicker("getDate");
onChangeDateOrService($.datepicker.formatDate("yy-mm-dd", me.getD));
$( "#field" + me.form_identifier + "-" + me.index + " div.cpefb_error").remove();
},
//beforeShowDay: function(d){return me.rC(d)}
});
e.datepicker("option", $.datepicker.regional[$.validator.messages.language]);
$.datepicker.setDefaults($.datepicker.regional[$.validator.messages.language]);
e.datepicker("option", "firstDay", me.firstDay );
e.datepicker("option", "dateFormat", me.dateFormat );
e.datepicker("option", "minDate", me.minDate );
e.datepicker("option", "maxDate", me.maxDate );
if (me.minDate!=="")
{	
me.getMinDate = e.datepicker("getDate");
var t = new Date();
var isRelativeDate = 1;
try{
$.datepicker.parseDate(me.dateFormat,me.minDate);
isRelativeDate = 0;
} catch (e) {}		            
me.getMinDate = new Date((me.getMinDate.getTime() + isRelativeDate * t.getHours() * 60 * 60 * 1000 + isRelativeDate * t.getMinutes() * 60 * 1000 + hrs * 60 * 60 * 1000) );
if (mindatetime!="")
{
var a = mindatetime.split(":")
if (parseFloat(a[0])>=0 && parseFloat(a[0]) < 24 && parseFloat(a[1])>=0 && parseFloat(a[1]) < 60 )
me.getMinDate = new Date(me.getMinDate.getFullYear(),me.getMinDate.getMonth(),me.getMinDate.getDate(),parseFloat(a[0]),parseFloat(a[1]));
}       
e.datepicker("option", "minDate", me.getMinDate );
e.datepicker("setDate", me.getMinDate);
} 
if (me.maxDate!=="")
try{me.getMaxDate = $.datepicker._getMinMaxDate( e.data('datepicker'), 'max' ); me.getMaxDate.setHours(23, 59, 59, 999);} catch (e) {} 
if (typeof hrsMax !== 'undefined')
{
var t = new Date();
me.getMaxDate.setHours(t.getHours(), t.getMinutes(), t.getSeconds());
me.getMaxDate = new Date((me.getMaxDate.getTime() + hrsMax * 60 * 60 * 1000) );
}		    
try{
if (me.defaultDate!=="")
e.datepicker("setDate", me.defaultDate);
} catch (e) {}
e.datepicker("option", "maxDate", me.maxDate );
if (me.getMaxDate!="" && me.tz!=0) 	e.datepicker("option", "maxDate", new Date(me.getMaxDate.getTime()+me.tz*60*60*1000) );
me.tmpinvalidDatestime = new Array();
try {
for (var i=0;i<me.tmpinvalidDates.length;i++)
me.tmpinvalidDatestime[i]=me.invalidDates[i].getTime();              
} catch (e) {}
function DisableSpecificDates(date) {                
var ohindex = me.services[me.normalizeSelectIndex($(".fieldCalendarService"+me.name+" select option:selected").index())].ohindex;
for (var i=0;i<me.allOH[ohindex].openhours.length;i++)
if (me.allOH[ohindex].openhours[i].type=="special" && me.allOH[ohindex].openhours[i].d==$.datepicker.formatDate("yy-mm-dd",date))
return true; 
var currentdate = date.getTime();
if ($.inArray(currentdate, me.tmpinvalidDatestime) > -1 ) 
return false;
if (me.working_dates[date.getDay()]==0)
return false;
return true;
}
var sum = 0;
for (var i=0;i<me.working_dates.length;i++)
sum += me.working_dates[i];
for (var key in me.cacheOpenHours[me.service_selected])
sum ++;
if (sum>0)
{       
var nextdateAvailable = e.datepicker("getDate");
var i = 0;
while (!DisableSpecificDates(nextdateAvailable)  && i<400)
{ 
nextdateAvailable.setDate(nextdateAvailable.getDate() + 1);
i++;
}
e.datepicker("setDate", nextdateAvailable);  
me.getD = nextdateAvailable;
function ifLoadOk()
{
if (!me.loadOK)
setTimeout(ifLoadOk,100);
else
{ 
$( '#field' + me.form_identifier + '-' + me.index + ' .fieldCalendar'+me.name ).datepicker( "option", "beforeShowDay", function(d){return me.rC(d)} );
onChangeDateOrService($.datepicker.formatDate('yy-mm-dd', me.getD));
$( '#field' + me.form_identifier + '-' + me.index + ' .fieldCalendar'+me.name ).datepicker( "option", "beforeShowDay", function(d){return me.rC(d)} );
}    
} 
ifLoadOk();
}
preselect_service = function(v)
{
$(".fieldCalendarService"+me.name+" select.ahbfield_service").children().removeAttr("selected");
if (me.emptySelectCheckbox)		            
$(".fieldCalendarService"+me.name+" select.ahbfield_service").children().eq(v+1).prop('selected', 'selected').change();
else
$(".fieldCalendarService"+me.name+" select.ahbfield_service").children().eq(v).prop('selected', 'selected').change();
}
if (typeof cp_hourbk_preselect !== 'undefined' && cp_hourbk_preselect!="")
preselect_service(cp_hourbk_preselect*1);
else
if (me.initialapp!="" && dd!="")
{   
try{
me.getD = $.datepicker.parseDate("yy-mm-dd",dd);
e.datepicker("setDate", me.getD);
preselect_service(me.initialServiceInd);
onChangeDateOrService(dd);
} catch (e) {}
}
getExtrasVisible = function(f)
{
try{
var p = f.attr("id").split( '_' );
var items = $.fbuilder[ 'forms' ]["_"+p[p.length-1]].getItems();
for (var i=0;i<items.length;i++)
if (items[i].ftype=="fapp" && ($("#"+items[i].name).parent().is(":visible") || $("#"+items[i].name).parents(".fields").hasClass("cp_active") ))
getExtras(items[i],f)
} catch (e) {}        
}    
getExtras=function(me,f)
{
var v = 0;
var find = false;
var filter = ':checked:not(.ignore),[type=text]:not(.ignore)';
var e = f.find(".ahb_service").find(filter);
if( e.length)
{
find = true;
e.each( function(){
if (($(this).parents(".fields").hasClass("cp_active") || $(this).is(":visible") || ($(this).prop("tagName")=="OPTION" && $(this).parent().is(":visible"))) &&  $.isNumeric(this.value))
v += this.value*1;
});
}
me.percent = 0;
var e = f.find(".ahb_service_percent").find(filter);
if( e.length)
{
find = true;
e.each( function(){
if (($(this).parents(".fields").hasClass("cp_active") || $(this).is(":visible") || ($(this).prop("tagName")=="OPTION" && $(this).parent().is(":visible"))) &&  $.isNumeric(this.value))
me.percent += this.value*1;
});
}
e = f.find(".ahb_service_per_slot").find(filter);
me.allUsedSlots = me.allUsedSlots || [];
var s = me.allUsedSlots.length;
if( e.length)
{
find = true;
e.each( function(){
if (($(this).parents(".fields").hasClass("cp_active") || $(this).is(":visible") || ($(this).prop("tagName")=="OPTION" && $(this).parent().is(":visible"))) &&  $.isNumeric(this.value))
v += this.value * s;
} );
}
e = f.find(".ahb_service_per_quantity_selection").find(filter);
var q = f.find(".ahbfield_quantity").val();
if (!parseFloat(q))
q = 1;
if( e.length)
{
find = true;
e.each( function(){
if (($(this).parents(".fields").hasClass("cp_active") || $(this).is(":visible") || ($(this).prop("tagName")=="OPTION" && $(this).parent().is(":visible"))) &&  $.isNumeric(this.value))
v += this.value * q;
} );
}
f.find('#'+me.name+'_services').val(v);
//if (find)
{
me.extras = v;
var total = me.sub_cost + me.extras;
total = total*(1+me.percent/100);
total = total.toFixed(2);
$( '#field' + me.form_identifier + '-' + me.index ).find(".totalCost .n").html(" " +me.showTotalCostFormat.replace("{0}",total));
$( '#field' + me.form_identifier + '-' + me.index + ' #tcost'+me.name ).val(total);
me.changeAutomatic = true;
$( '#field' + me.form_identifier + '-' + me.index + ' #'+me.name ).change();
}
}    
$( '#field' + me.form_identifier + '-' + me.index ).parents( "form" ).find(".ahb_service,.ahb_service_percent,.ahb_service_per_slot,.ahb_service_per_quantity_selection").on("click change keyup", function(){
getExtrasVisible($(this).parents( "form" ));
});
$( '#field' + me.form_identifier + '-' + me.index + ' #'+me.name ).change(function(  ) {
if (!me.changeAutomatic)
getExtrasVisible($(this).parents( "form" ));
me.changeAutomatic = false;     
});
if (typeof cp_hourbk_overlapping_label != "undefined")
$.extend($.validator.messages, {avoid_overlapping: $.validator.format(cp_hourbk_overlapping_label)});        
if(!('avoid_overlapping' in $.validator.methods))
{ 
function avoid_over_function(value, element){
var validator = this,
previous = validator.previousValue( element );
if ( previous.old === value ) {
return previous.valid;
}
previous.old = value;
validator.startRequest( element );
var p = element.id.split( '_' ),
_index = ( p.length > 1 ) ? '_'+p[ 1 ] : '',
me = ( 
typeof $.fbuilder[ 'forms' ] != 'undefined' && 
typeof $.fbuilder[ 'forms' ][ _index ] != 'undefined'  
) ? $.fbuilder[ 'forms' ][ _index ].getItem( p[ 0 ]+'_'+p[ 1 ] ) : null;
if( me != null )  
{
$.ajax({
dataType : 'json',
type: "POST",
url : document.location.href,
data :  { cp_app_action: 'get_slots',
formid: me.formId,
initialID: me.initialID,
formfield: me.name.replace(me.form_identifier, "")   
},
success: function(data) {
var overlapping = false;
var find = false;
me.ignoreUsedSlots = true;
me.cacheArr = new Array(); 
for (var i=0;i<data.length;i++)
{
var dd = data[i].d;
if (typeof data[i].sid !== 'undefined')
data[i].serviceindex = me.getServiceInd(data[i].sid);
me.cacheArr[dd] = me.cacheArr[dd] || [];
me.cacheArr[dd][me.cacheArr[dd].length] = data[i];	
}
me.slotsDate = [];
me.loadOK = true;
var msg = "";
for (var i = 0; (i<me.allUsedSlots.length ); i++)
{
me.service_selected = me.allUsedSlots[i].serviceindex;
me.quantity_selected = me.allUsedSlots[i].quantity;
me.duration = parseFloat(me.services[me.service_selected].duration);
var d = me.allUsedSlots[i].d;
var t1 = me.allUsedSlots[i].h1 * 60 + me.allUsedSlots[i].m1;
var t2 = me.allUsedSlots[i].h2 * 60 + me.allUsedSlots[i].m2;
if (me.tz != 0)
{
var d1 = $.datepicker.parseDate("yy-mm-dd",d);
var d2 = new Date(d1.getTime()+t1*60*1000+me.tz*60*60*1000);
d = $.datepicker.formatDate("yy-mm-dd",d2);
}
var arr = me.getAvailableSlots(d);
if (me.showAllServices)
arr = me.availableSlotsByService[d][me.service_selected];
find = false;
for (var j=0;(j<arr.length  && !find);j++)
{
if (arr[j].t1<=t1 && arr[j].t2>=t2)
find = true; 
}
if (!find)
{
overlapping = true;
if (msg == "") msg = "<div class=\"ahb_overlapping_detail\"><div class=\"ahb_overlapping_title\">Affected times:</div>";
msg += "<div><span class=\"ahb_list_time\">"+me.formatString(me.allUsedSlots[i],true,me.tz)+"</span><span class=\"ahb_list_service\">"+me.services[me.allUsedSlots[i].serviceindex].name+"</span></div>";
}
//overlapping = !find; 
} 
me.ignoreUsedSlots = false;
var isValid = !overlapping;
if (true === isValid) {
var submitted = validator.formSubmitted;
validator.prepareElement( element );
validator.formSubmitted = submitted;
validator.successList.push( element );
delete validator.invalid[ element.name ];
validator.showErrors();
} else {
for (var i=0;i<data.length;i++)
{
var dd = data[i].d;
me.cacheArr[dd] = me.cacheArr[dd] || [];
me.cacheArr[dd][me.cacheArr[dd].length] = data[i];	
}
me.slotsDate = [];
me.loadOK = true;
var errors = {};
if (msg != "") msg += "</div>";
errors[ element.name ] = validator.defaultMessage( element, "avoid_overlapping" )+msg;
validator.invalid[ element.name ] = true;
validator.showErrors( errors );
element.focus();
}
previous.valid = isValid;
validator.stopRequest( element, isValid );
cp_hourbk_avoid_overlapping--;    
}
});
return "pending";
}
return true;    
}
$.validator.addMethod('avoid_overlapping', avoid_over_function);
}                          
},
val:function()
{
return 0;
}
}         
);	$.fbuilder.controls[ 'fcurrencyds' ]=function(){};
$.extend(
$.fbuilder.controls[ 'fcurrencyds' ].prototype,
$.fbuilder.controls[ 'fcurrency' ].prototype,
$.fbuilder.controls[ 'datasource' ].prototype,
{
ftype:"fcurrencyds",
show:function()
{
return $.fbuilder.controls[ 'fcurrency' ].prototype.show.call( this );
},
after_show : function(){
var me = this;
$.fbuilder.controls[ 'fcurrency' ].prototype.after_show.call( this );
$.fbuilder.controls[ 'datasource' ].prototype.getData.call( this, function( data )
{ 
var v = '';
if( typeof data.error != 'undefined' )
{
alert( data.error );
}
else
{
if( data.data.length )
{
v = data.data[ 0 ][ 'value' ];
}
}	
$( '#' + me.name ).val( v ).change();
}
);
}	
});	$.fbuilder.controls[ 'facceptance' ]=function(){};
$.extend(
$.fbuilder.controls[ 'facceptance' ].prototype,
$.fbuilder.controls[ 'ffields' ].prototype,
{
title:"Accept terms and conditions",
ftype:"facceptance",
value:"I accept",
required:true,
url:"",
message:"",
show:function()
{
var me = this,
dlg = '',
label = me.title;
if(!/^\s*$/.test(me.url))
{
label = '<a href="'+$.fbuilder.htmlEncode($.trim(me.url))+'" target="_blank">'+label+'</a>';
}
else if(!/^\s*$/.test(me.message))
{
label = '<a href="javascript:void(0);" class="cff-open-dlg">'+label+'</a>';
dlg += '<div class="cff-dialog hide"><span class="cff-close-dlg"></span><div class="cff-dialog-content">'+me.message+'</div></div>'
}
return '<div class="fields '+me.csslayout+' cff-checkbox-field" id="field'+me.form_identifier+'-'+me.index+'"><div class="dfield">'+
'<div class="one_column"><label><input name="'+me.name+'" id="'+me.name+'" class="field required" value="'+$.fbuilder.htmlEncode(me.value)+'" vt="'+$.fbuilder.htmlEncode((/^\s*$/.test(me.value)) ? me.title : me.value)+'" type="checkbox" /> <span>'+
$.fbuilder.htmlDecode( label )+''+((me.required)?'<span class="r">*</span>':'')+
'</span></label></div>'+
dlg+
'</div><div class="clearer"></div></div>';
},
after_show:function()
{
$(document).on('click','.cff-open-dlg', function(){
var dlg = $(this).closest('.fields').find('.cff-dialog'), w = dlg.data('width'), h=dlg.data('height');
dlg.removeClass('hide');
if('undefined' == typeof w) w = Math.min($(this).closest('form').width(), $(window).width(), dlg.width());
if('undefined' == typeof h) h = Math.min($(this).closest('form').height(), $(window).height(), dlg.height());
dlg.data('width',w);
dlg.data('height',h);
dlg.css({'width': w+'px', 'height': h+'px', 'margin-top': (-1*h/2)+'px', 'margin-left': (-1*w/2)+'px'});
});
$(document).on('click','.cff-close-dlg', function(){$(this).closest('.cff-dialog').addClass('hide');});
},
val:function()
{
var e = $('[id="'+this.name+'"]:checked:not(.ignore)');
if( e.length )
{
var t = $.fbuilder.parseValStr( e[0].value );
if(!$.isNumeric(t)) t = t.replace(/^"/,'').replace(/"$/,'');
}
return (v) ? (($.isNumeric(v)) ? v : '"'+v+'"') : 0;
}
}
);        var fcount = 1;
var fcount_tags = 1;
var fnum = "_"+fcount; 
var cp_avoid_hidden = false;
while (20>fcount || eval("typeof cp_appbooking_fbuilder_config"+fnum+" != 'undefined'"))
{
try {
var cp_appbooking_fbuilder_config = eval("cp_appbooking_fbuilder_config"+fnum);
while (20>fcount_tags && !$("#fbuilder_"+fcount_tags).length)
fcount_tags++;
cp_appbooking_fbuilder_config = $.parseJSON(cp_appbooking_fbuilder_config.obj);
cp_appbooking_fbuilder_config.identifier = "_"+fcount_tags;
if (!$("#fieldlist_"+fcount_tags).html().length)
{
var opt_identifier = $("#fieldlist_"+fcount_tags);
opt_identifier.attr("fcount_tags",fcount_tags); 
opt_identifier.attr("fnum",fnum); 
opt_identifier.addClass("cp_avoid_hidden")
var f = $("#fbuilder_"+fcount_tags).fbuilder(cp_appbooking_fbuilder_config);
f.fBuild.loadData("form_structure_"+fcount_tags);
$.fbuilder.configValidate($("#cp_appbooking_pform_"+fcount_tags));   
if((typeof opt_identifier.attr("fnum") !== 'undefined') && !opt_identifier.is(':hidden'))
$(opt_identifier).addClass("cp_v_v");
else
cp_avoid_hidden = true;
}
} catch (e) {}
fcount++;
fcount_tags++;
fnum = "_"+fcount;
}
if (cp_avoid_hidden)
$( document ).each(
function()
{
(new MutationObserver(
function(mutationsList, observer)
{   
for(let k in mutationsList)
{
var mutation = mutationsList[k];
if (mutation.type === 'childList')
{
if(mutation.addedNodes.length)
{
try{ 
$(".cp_avoid_hidden").each(function(){
var opt_identifier= $("#"+$(this).attr("id"));
if((typeof opt_identifier.attr("fnum") !== 'undefined') && !opt_identifier.is(':hidden') && opt_identifier.find(".avoid_overlapping_before").length>0)
$(opt_identifier).addClass("cp_v_v");
if((typeof opt_identifier.attr("fnum") !== 'undefined') && !opt_identifier.is(':hidden') && !opt_identifier.hasClass("cp_v_v"))
{
$(opt_identifier).addClass("cp_v_v");
var fnum = opt_identifier.attr("fnum");   
var fcount_tags = opt_identifier.attr("fcount_tags");
var cp_appbooking_fbuilder_config = eval("cp_appbooking_fbuilder_config"+fnum);
cp_appbooking_fbuilder_config = $.parseJSON(cp_appbooking_fbuilder_config.obj);
cp_appbooking_fbuilder_config.identifier = "_"+fcount_tags;
var f = $("#fbuilder_"+fcount_tags).fbuilder(cp_appbooking_fbuilder_config);
f.fBuild.loadData("form_structure_"+fcount_tags);
$.fbuilder.configValidate(opt_identifier.closest("form"));
}
})
}catch(err){}
}
}
}
}
)).observe(this, { childList: true, subtree: true });
}
);
})(fbuilderjQuery);
});#fbuilder .ui-datepicker-inline {width: auto ! important;display: inline-block !important;}
#fbuilder .ui-datepicker-inline{width:100%;max-width: 300px;}
#fbuilder .ui-datepicker-inline.ui-datepicker-multi{max-width: 4000px;} #fbuilder .ui-datepicker.ui-datepicker-multi { width:auto; }
#fbuilder .ui-datepicker-multi .ui-datepicker-group { float:left; }
#fbuilder .ui-datepicker-multi .ui-datepicker-group table { width:95%; margin:0 auto .4em; }
#fbuilder .ui-datepicker-multi-2 .ui-datepicker-group { width:50%; }
#fbuilder .ui-datepicker-multi-3 .ui-datepicker-group { width:33.3%; }
#fbuilder .ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header { border-left-width:0; }
#fbuilder .ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { border-left-width:0; }
#fbuilder .ui-datepicker-multi .ui-datepicker-buttonpane { clear:left; }
#fbuilder .ui-datepicker-row-break { clear:both; width:100%; font-size:0em; }
@media screen and (max-width: 640px){
#fbuilder .ui-datepicker-multi-2 .ui-datepicker-group { width:auto; }
#fbuilder .ui-datepicker-multi-3 .ui-datepicker-group { width:auto; }
} #fbuilder table.ui-datepicker-calendar{table-layout: fixed;}
.ui-datepicker {
height: auto;
margin: 5px 0;
font: 9pt Arial, sans-serif;
-webkit-box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, .5);
-moz-box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, .5);
box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, .5);
}
.ui-datepicker a {
text-decoration: none;
} .ui-datepicker table {
width: 100%;
}
.ui-datepicker-header {
background: #000;
color: #e0e0e0;
font-weight: bold;
-webkit-box-shadow: inset 0px 1px 1px 0px rgba(250, 250, 250, 2);
-moz-box-shadow: inset 0px 1px 1px 0px rgba(250, 250, 250, .2);
box-shadow: inset 0px 1px 1px 0px rgba(250, 250, 250, .2);
text-shadow: 1px -1px 0px #000;
filter: dropshadow(color=#000, offx=1, offy=-1);
line-height: 30px;
border-width: 0;
border-style: solid;
border-color: #111;
}
.ui-datepicker-title {
text-align: center;
}
.ui-datepicker-prev, .ui-datepicker-next {
display: inline-block;
width: 30px;
height: 30px;
text-align: center;
cursor: pointer;
background-image: url(https://cocotte-coworking.fr/wp-content/plugins/appointment-hour-booking/css/cupertino/images/arrow.png);
background-repeat: no-repeat;
line-height: 600%;
overflow: hidden;
}
.ui-datepicker-prev {
float: left;
background-position: center -30px;
}
.ui-datepicker-next {
float: right;
background-position: center 0px;
}
.ui-datepicker thead {
background-color: #f7f7f7;
background-image: -moz-linear-gradient(top,  #f7f7f7 0%, #f1f1f1 100%);
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f7f7f7), color-stop(100%,#f1f1f1));
background-image: -webkit-linear-gradient(top,  #f7f7f7 0%,#f1f1f1 100%);
background-image: -o-linear-gradient(top,  #f7f7f7 0%,#f1f1f1 100%);
background-image: -ms-linear-gradient(top,  #f7f7f7 0%,#f1f1f1 100%);
background-image: linear-gradient(top,  #f7f7f7 0%,#f1f1f1 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f7f7f7', endColorstr='#f1f1f1',GradientType=0 );
border-bottom: 1px solid #bbb;
}
.ui-datepicker th {
text-transform: uppercase;
padding: 5px 0;
color: #666666;
text-align:center;
text-shadow: 1px 0px 0px #fff;
filter: dropshadow(color=#fff, offx=1, offy=0);
}
.ui-datepicker tbody td {
padding: 0;
border-right: 1px solid #bbb;
}
.ui-datepicker tbody td:last-child {
border-right: 0px;
}
.ui-datepicker tbody tr {
border-bottom: 1px solid #bbb;
}
.ui-datepicker tbody tr:last-child {
border-bottom: 0px;
}
.ui-datepicker td span, .ui-datepicker td a {
display: inline-block;
font-weight: bold;
text-align: center;
width: 100%;
height: 30px;
line-height: 30px;
color: #666666;
text-shadow: 1px 1px 0px #fff;
filter: dropshadow(color=#fff, offx=1, offy=1);
box-shadow:none;border:0px
}
.ui-datepicker-calendar .ui-state-default {
background: #ededed;
background: -moz-linear-gradient(top,  #ededed 0%, #dedede 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ededed), color-stop(100%,#dedede));
background: -webkit-linear-gradient(top,  #ededed 0%,#dedede 100%);
background: -o-linear-gradient(top,  #ededed 0%,#dedede 100%);
background: -ms-linear-gradient(top,  #ededed 0%,#dedede 100%);
background: linear-gradient(top,  #ededed 0%,#dedede 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ededed', endColorstr='#dedede',GradientType=0 );
-webkit-box-shadow: inset 1px 1px 0px 0px rgba(250, 250, 250, .5);
-moz-box-shadow: inset 1px 1px 0px 0px rgba(250, 250, 250, .5);
box-shadow: inset 1px 1px 0px 0px rgba(250, 250, 250, .5);
}
.ui-datepicker-calendar .ui-state-hover {
background: #f7f7f7;box-shadow:none;border:0px
}
.ui-datepicker-calendar .ui-state-active {
background: #6eafbf;
-webkit-box-shadow: inset 0px 0px 10px 0px rgba(0, 0, 0, .1);
-moz-box-shadow: inset 0px 0px 10px 0px rgba(0, 0, 0, .1);
box-shadow: inset 0px 0px 10px 0px rgba(0, 0, 0, .1);
color: #e0e0e0;
text-shadow: 0px 1px 0px #4d7a85;
filter: dropshadow(color=#4d7a85, offx=0, offy=1);
border: 1px solid #55838f;
position: relative;
}
.ui-datepicker-unselectable .ui-state-default {
background: #f4f4f4;
color: #b4b3b3;
}