fbuilderjQuery = (typeof fbuilderjQuery != 'undefined' ) ? fbuilderjQuery : jQuery; fbuilderjQuery(window).bind( 'pageshow', function( event ){ if( typeof event.originalEvent[ 'persisted' ] != 'undefined' && event.originalEvent[ 'persisted' ] ) location.reload(); } ); fbuilderjQuery.fbuilderjQueryGenerator = function(){ if('fbuilderGeneratorFlag' in fbuilderjQuery) return; (function($) { // Namespace of fbuilder $.fbuilder = $.fbuilder || {}; $.fbuilder[ 'objName' ] = 'fbuilderjQuery'; /* * logical.js v0.1 * By: CALCULATED FIELD PROGRAMMERS * The script allows make logical operations like functions * Copyright 2013 CODEPEOPLE * You may use this project under MIT or GPL licenses. */ ;(function(root){ var lib = {}; lib.cf_logical_version = '0.1'; // IF( logical_test, value_if_true, value_if_false ) lib.IF = function( _if, _then, _else ){ if ( _if ) { return ( typeof _then === 'undefined' ) ? true : _then; } else { return ( typeof _else === 'undefined' ) ? false : _else; } }; // AND( logical1, logical2, ... ) lib.AND = function(){ for (var i = 0, h = arguments.length; i < h; i++) { if (!arguments[i]) { return false; } } return true; }; // OR( logical1, logical2, ... ) lib.OR = function(){ for (var i = 0, h = arguments.length; i < h; i++) { if ( arguments[i] ) { return true; } } return false; }; // NOT( term ) lib.NOT = function( _term ){ return ( typeof _term == 'undefined' ) ? true : !_term; }; // IN( term, values ) values can be a string or an array lib.IN = function( _term, _values ){ function _reduce( str ){ return String(str).replace( /^\s+/, '').replace(/\s+$/, '').replace(/\s+/, ' ').toLowerCase(); }; _term = _reduce( _term ); if( typeof _values == 'string' ) return _reduce( _values ).indexOf( _term ) != -1; else if( typeof _values == 'object' && _values.length ){ for( var i = 0, h = _values.length; i < h; i++) if( _reduce( _values[ i ] ).indexOf( _term ) != -1 ) return true; } return false; }; root.CF_LOGICAL = lib; })(this); fbuilderjQuery = ( typeof fbuilderjQuery != 'undefined' ) ? fbuilderjQuery : jQuery; fbuilderjQuery[ 'fbuilder' ] = fbuilderjQuery[ 'fbuilder' ] || {}; fbuilderjQuery[ 'fbuilder' ][ 'modules' ] = fbuilderjQuery[ 'fbuilder' ][ 'modules' ] || {}; fbuilderjQuery[ 'fbuilder' ][ 'modules' ][ 'default' ] = { 'prefix' : '', 'callback' : function() { function ROUNDx(operation, num, y) { if(y && y != 0) { var r = operation(num/y)*y, p = (new String(y)).split('.'); if(p.length == 2) r = PREC(r,p[1].length); return r; } else { return operation(num); } }; if(window.ROUND == undefined) { window.ROUND = window.round = function(num, y) { if(y) return ROUNDx(Math.round, num, y); return ROUNDx(Math.round, num); } } if(window.FLOOR == undefined) { window.FLOOR = window.floor = function(num, y) { if(y) return ROUNDx(Math.floor, num, y); return ROUNDx(Math.floor, num); } } if(window.CEIL == undefined) { window.CEIL = window.ceil = function(num, y) { if(y) return ROUNDx(Math.ceil, num, y); return ROUNDx(Math.ceil, num); } } if(window.PREC == undefined) { window.PREC = window.prec = function (num, pr) { if('undefined' == typeof pr) pr = 0; if(/^\d+$/.test(pr) && $.isNumeric(num)) { var f = POW(10,pr); num = ROUND(num*f)/f; return num.toFixed(pr); } return num; }; } // End if window.PREC if(window.CDATE == undefined) { window.CDATE = window.cdate = function ( num, format ) { format = ( typeof format != 'undefined' ) ? format : ( ( typeof window.DATETIMEFORMAT != 'undefined' ) ? window.DATETIMEFORMAT : 'dd/mm/yyyy' ); if(isFinite(num*1)) { num = Math.round(num*86400000); var date = new Date(num), d = date.getDate(), m = date.getMonth()+1, y = date.getFullYear(), h = date.getHours(), i = date.getMinutes(), s = date.getSeconds(), a = ''; m = (m < 10) ? '0'+m : m; d = (d < 10) ? '0'+d : d; if( /a/.test( format ) ) { a = ( h >= 12 ) ? 'pm' : 'am'; h = h % 12; h = ( h == 0 ) ? 12: h; } h = (h < 10) ? '0'+h : h; i = (i < 10) ? '0'+i : i; s = (s < 10) ? '0'+s : s; return format.replace( /y+/i, y) .replace( /m+/i, m) .replace( /d+/i, d) .replace( /h+/i, h) .replace( /i+/i, i) .replace( /s+/i, s) .replace( /a+/i, a); } return num; }; } // End if window.CDATE if(window.GCD == undefined) { window.GCD = window.gcd = function( a, b) { if ( ! b) return a; return GCD(b, a % b); }; } // End if window.GCD if(window.LOGAB == undefined) { window.LOGAB = window.logab = function( a, b) { return LOG(a)/LOG(b); }; } // End if window.LOGAB var math_prop = ["LN10", "PI", "E", "LOG10E", "SQRT2", "LOG2E", "SQRT1_2", "LN2", "cos", "pow", "log", "tan", "sqrt", "asin", "abs", "max", "exp", "atan2", "atanh", "random", "acos", "atan", "min", "sin"]; for(var i = 0, h = math_prop.length; i < h; i++) { if( !window[ math_prop[ i ] ] ) { window[ math_prop[ i ] ] = window[ math_prop[ i ].toUpperCase() ] = Math[ math_prop[ i ] ]; } } if(window.RADIANS == undefined) { window.RADIANS = window.radians = function(a){ return a*PI/180;}; } if(window.DEGREES == undefined) { window.DEGREES = window.degrees = function(a){ return a*180/PI;}; } fbuilderjQuery[ 'fbuilder' ][ 'extend_window' ]( fbuilderjQuery[ 'fbuilder' ][ 'modules' ][ 'default' ][ 'prefix' ], CF_LOGICAL ); }, 'validator' : function( v ) { return ( typeof v == 'number' ) ? isFinite( v ) : ( typeof v != 'undefined' ); } };/* * datetime.js v0.1 * By: CALCULATED FIELD PROGRAMMERS * The script allows operations with date and time * Copyright 2013 CODEPEOPLE * You may use this project under MIT or GPL licenses. */ ;(function(root){ var lib = {}, default_format = ( typeof window.DATETIMEFORMAT != 'undefined' ) ? window.DATETIMEFORMAT : 'yyyy-mm-dd hh:ii:ss a', regExp = ''; Date.prototype.valid = function() { return isFinite(this); }; /*** PRIVATE FUNCTIONS ***/ function _getDateObj( date, format ){ var d = new Date(); format = format || default_format; if( typeof date != 'undefined' ){ if( typeof date == 'number' ){ d = new Date( date*86400000 ); }else if( typeof date == 'string' ){ var p; if( null != ( p = /(\d{4})[\/\-\.](\d{1,2})[\/\-\.](\d{1,2})/.exec( date ) ) ){ if( /y{4}[\/\-\.]m{2}[\/\-\.]d{2}/i.test( format ) ){ d = new Date( p[ 1 ], ( p[ 2 ] - 1 ), p[ 3 ] ); }else{ d = new Date( p[ 1 ], ( p[ 3 ] - 1 ), p[ 2 ] ); } date = date.replace( p[ 0 ], '' ); } if( null != ( p = /(\d{1,2})[\/\-\.](\d{1,2})[\/\-\.](\d{4})/.exec( date ) ) ){ if( /d{2}[\/\-\.]m{2}[\/\-\.]y{4}/i.test( format ) ){ d = new Date( p[ 3 ], ( p[ 2 ] - 1 ), p[ 1 ] ); }else{ d = new Date( p[ 3 ], ( p[ 1 ] - 1 ), p[ 2 ] ); } date = date.replace( p[ 0 ], '' ); } if( null != ( p = /(\d{1,2})[:\.](\d{1,2})([:\.](\d{1,2}))?\s*([ap]m)?/i.exec( date ) ) ){ if(/h+/i.test( format ) ){ if( typeof p[ 5 ] != 'undefined' && /pm/i.test( p[ 5 ] ) ) p[ 1 ] = ( p[ 1 ]*1 + 12 ) % 24; d.setHours( p[ 1 ] ); } if(/i+/i.test( format ) ) d.setMinutes( p[ 2 ] ); if(/s+/i.test( format ) && (typeof p[ 4 ] != 'undefined') ) d.setSeconds( p[ 4 ] ); } }else{ d = new Date( date ); } } return d; }; /*** PUBLIC FUNCTIONS ***/ lib.cf_datetime_version = '0.1'; // DATEOBJ( date_string, date_format_string ) lib.DATEOBJ = function( date, format ){ var d = _getDateObj( date, format ); if( d.valid() ) return d; return false; }; // YEAR( date_string, date_format_string ) lib.YEAR = function( date, format ){ var d = _getDateObj( date, format ); if( d.valid() ) return d.getFullYear(); return false; }; // MONTH( date_string, date_format_string ) lib.MONTH = function( date, format ){ var d = _getDateObj( date, format ); if( d.valid() ) return d.getMonth()+1; return false; }; // DAY( date_string, date_format_string ) lib.DAY = function( date, format ){ var d = _getDateObj( date, format ); if( d.valid() ) return d.getDate(); return false; }; // WEEKDAY( date_string, date_format_string ) lib.WEEKDAY = function( date, format ){ var d = _getDateObj( date, format ); if( d.valid() ) return d.getDay()+1; return false; }; // WEEKDAY( date_string, date_format_string ) lib.WEEKNUM = function( date, format ){ var d = _getDateObj( date, format ), tmp = _getDateObj( date, format ); if( d.valid() ){ // ISO week date weeks start on monday var dayNr = ( d.getDay() + 6 ) % 7; // ISO 8601 states that week 1 is the week with the first thursday of that year. tmp.setDate( d.getDate() - dayNr + 3 ); // Store the millisecond value of the tmp date var firstThursday = tmp.valueOf(); // Set the tmp to the first thursday of the year // First set the tmp to january first tmp.setMonth(0, 1); // Not a thursday? Correct the date to the next thursday if (tmp.getDay() != 4) { tmp.setMonth(0, 1 + ((4 - tmp.getDay()) + 7) % 7); } // The weeknumber is the number of weeks between the // first thursday of the year and the thursday in the tmp week return 1 + Math.ceil((firstThursday - tmp) / 604800000); // 604800000 = 7 * 24 * 3600 * 1000 } return false; }; // HOURS( datetime_string, datetime_format_string ) lib.HOURS = function( date, format ){ var d = _getDateObj( date, format ); if( d.valid() ) return d.getHours(); return false; }; // MINUTES( datetime_string, datetime_format_string ) lib.MINUTES = function( date, format ){ var d = _getDateObj( date, format ); if( d.valid() ) return d.getMinutes(); return false; }; // SECONDS( datetime_string, datetime_format_string ) lib.SECONDS = function( date, format ){ var d = _getDateObj( date, format ); if( d.valid() ) return d.getSeconds(); return false; }; // NOW() Return a datetime object lib.NOW = function(){ return _getDateObj(); }; // TODAY() Return a datetime object limited to date only lib.TODAY = function(){ var d = _getDateObj(); d.setHours( 0 ); d.setMinutes( 0 ); d.setSeconds( 0 ); return d; }; /* * DATEDIFF( datetime_string, datetime_string, return_format) * * return_format: * d - number of days, and remaining hours, minutes and seconds * m - number of months, and remaining days, hours, minutes and seconds * y - number of years, and remaining months, days, hours, minutes and seconds * * the function return an object with attributes: years, months and days depending of return_format argument */ lib.DATEDIFF = function( date_one, date_two, date_format, return_format ){ var d1 = _getDateObj( date_one, date_format ), d2 = _getDateObj( date_two, date_format ), diff, r = { 'years' : -1, 'months' : -1, 'days' : -1, 'hours' : -1, 'minutes' : -1, 'seconds' : -1 }; if( d1.valid() && d2.valid() ){ if( d1.valueOf() > d2.valueOf() ){ d2 = _getDateObj( date_one, date_format ); d1 = _getDateObj( date_two, date_format ); } diff = d2.valueOf() - d1.valueOf(); if( typeof return_format == 'undefined' || return_format == 'd' ){ r.days = Math.floor( diff/86400000 ); }else{ var months, days, tmp; months = (d2.getFullYear() - d1.getFullYear()) * 12; months -= d1.getMonth() + 1; months += d2.getMonth() + 1; days = d2.getDate() - d1.getDate(); if( days < 0 ){ months--; tmp = new Date( d1.getFullYear(), d1.getMonth()+1 ); days = ( tmp.valueOf() - d1.valueOf() )/86400000 + d2.getDate() - 1; } r.months = months; r.days = days; if( /y/i.test( return_format ) ){ r.years = Math.floor( months/12 ); r.months = months % 12; } } r.hours = Math.floor( diff%86400000/3600000 ); r.minutes = Math.floor( diff%86400000%3600000/60000 ); r.seconds = Math.floor( diff%86400000%3600000%60000/1000); } return r; }; /* * DATETIMESUM( datetime_string, format, number, to_increase ) * to_increase: * s - seconds * i - minutes * h - hours * d - add the number of days, * m - add the number of months, * y - add the number of years * */ lib.DATETIMESUM = function( date, format, number, to_increase){ var d = _getDateObj( date, format ); if( d.valid() ){ if( typeof number != 'number' || isNaN( parseInt( number ) ) ) number = 0; else number = parseInt( number ); if( typeof to_increase == 'undefined' ) to_increase = 'd'; if( /y+/i.test( to_increase ) ) d.setFullYear( d.getFullYear() + number ); else if( /d+/i.test( to_increase ) ) d.setDate( d.getDate() + number ); else if( /m+/i.test( to_increase ) ) d.setMonth( d.getMonth() + number ); else if( /h+/i.test( to_increase ) ) d.setHours( d.getHours() + number ); else if( /i+/i.test( to_increase ) ) d.setMinutes( d.getMinutes() + number ); else d.setSeconds( d.getSeconds() + number ); return d; } return false; }; // GETDATETIMESTRING( date_object, return_format ) Return the date object as a string representation determined by the return_format argument lib.GETDATETIMESTRING = function( date, format ){ if( typeof format == 'undefined' ) format = default_format; if( date.valid() ){ var m = date.getMonth() + 1, d = date.getDate(), h = date.getHours(), i = date.getMinutes(), s = date.getSeconds(), a = ( h >= 12 ) ? 'pm' : 'am'; m = ( m < 10 ) ? '0'+m : m; d = ( d < 10 ) ? '0'+d : d; if( /a+/.test( format ) ){ h = h % 12; h = ( h ) ? h : 12; } h = ( h < 10 ) ? '0'+h : h; i = ( i < 10 ) ? '0'+i : i; s = ( s < 10 ) ? '0'+s : s; return format.replace( /y+/i, date.getFullYear() ) .replace( /m+/i, m ) .replace( /d+/i, d ) .replace( /h+/i, h ) .replace( /i+/i, i ) .replace( /s+/i, s ) .replace( /a+/i, a ); } return date; }; root.CF_DATETIME = lib; })(this);fbuilderjQuery = ( typeof fbuilderjQuery != 'undefined' ) ? fbuilderjQuery : jQuery; fbuilderjQuery[ 'fbuilder' ] = fbuilderjQuery[ 'fbuilder' ] || {}; fbuilderjQuery[ 'fbuilder' ][ 'modules' ] = fbuilderjQuery[ 'fbuilder' ][ 'modules' ] || {}; fbuilderjQuery[ 'fbuilder' ][ 'modules' ][ 'datetime' ] = { 'prefix' : '', 'callback' : function() { fbuilderjQuery[ 'fbuilder' ][ 'extend_window' ]( fbuilderjQuery[ 'fbuilder' ][ 'modules' ][ 'datetime' ][ 'prefix' ], CF_DATETIME ); }, 'validator' : function( v ) { if( /^\s*((\d{4}[\/\-\.]\d{1,2}[\/\-\.]\d{1,2})|(\d{1,2}[\/\-\.]\d{1,2}[\/\-\.]\d{4}))?\s*(\d{1,2}\s*:\s*\d{1,2}(\s*:\s*\d{1,2})?(\s*[ap]m)?)?\s*$/i.test( v ) ) { return true; } return false; } };/* * finance.js v0.2 * * Based On * * finance.js v0.1 by: Trent Richardson [http://trentrichardson.com] * Copyright 2012 Trent Richardson * * The functions implemented by Ismael Ghalimi [https://gist.github.com/ghalimi] * Copyright (c) 2012 Sutoiku, Inc. (MIT License) * * EGM Mathematical Finance class by Enrique Garcia M. * * CALCULATED FIELD PROGRAMMERS * We've modified the object name and methods to avoid collisions with other libraries */ ;(function(root){ var lib = {}; lib.cf_finance_version = '0.2'; var daysDiff = function(d1, d2) { var oneDay = 24*60*60*1000; d1 = new Date( d1 ); d2 = new Date( d2 ); return Math.round( Math.abs((d1.getTime() - d2.getTime())/oneDay)); }; /* * Defaults */ lib.settings = { format: 'number', formats: { USD: { before: '$', after: '', precision: 2, decimal: '.', thousand: ',', group: 3, negative: '-' }, // $ GBP: { before:'£', after: '', precision: 2, decimal: '.', thousand: ',', group: 3, negative: '-' }, // £ or £ EUR: { before:'€', after: '', precision: 2, decimal: '.', thousand: ',', group: 3, negative: '-' }, // € or € percent: { before: '', after: '%', precision: 0, decimal: '.', thousand: ',', group: 3, negative: '-' }, number: { before: '', after: '', precision: null, decimal: '.', thousand: ',', group: 3, negative: '-'}, defaults: { before: '', after: '', precision: 0, decimal: '.', thousand: ',', group: 3, negative: '-' } } }; lib.defaults = function(object, defs) { var key; object = object || {}; defs = defs || {}; for (key in defs) { if (defs.hasOwnProperty(key)) { if (object[key] == null) object[key] = defs[key]; } } return object; }; /* * Formatting */ // add a currency format to library lib.ADDFORMAT = function(key, options){ this.settings.formats[key] = this.defaults(options, this.settings.formats.defaults); return true; }; // remove a currency format from library lib.REMOVEFORMAT = function(key){ delete this.settings.formats[key]; return true; }; // format a number or currency lib.NUMBERFORMAT = function(num, settings, override){ num = parseFloat(num); if(settings === undefined) settings = this.settings.formats[this.settings.format]; else if(typeof settings == 'string') settings = this.settings.formats[settings]; else settings = settings; settings = this.defaults(settings, this.settings.formats.defaults); if(override !== undefined) settings = this.defaults(override, settings); // set precision var tmp = num; if(settings.precision != null) { tmp = Math.abs(num); tmp = tmp.toFixed(settings.precision); num = num.toFixed(settings.precision); } var isNeg = num < 0, numParts = tmp.toString().split('.'), baseLen = numParts[0].length; // add thousands and group numParts[0] = numParts[0].replace(/(\d)/g, function(str, m1, offset, s){ return (offset > 0 && (baseLen-offset) % settings.group == 0)? settings.thousand + m1 : m1; }); // add decimal num = numParts.join(settings.decimal); // add negative if applicable if(isNeg && settings.negative){ num = settings.negative[0] + num; if(settings.negative.length > 1) num += settings.negative[1]; } return settings.before + num + settings.after; }; /* * Financing */ // present value, calculate the present value of investment lib.PRESENTVALUE = lib.PV = function( rate, nper, pmt ){ return pmt / rate * (1 - Math.pow(1 + rate, -1 * nper)); }; // future value, calculate the future value of an investment // based on an interest rate and a constant payment schedule lib.FUTUREVALUE = lib.FV = function( rate, nper, pmt, pv, type ){ if( typeof pv == 'undefined' ) pv = 0; if( typeof type == 'undefined' ) type = 0; rate = rate/100; var pow = Math.pow(1 + rate, nper); var fv = 0; if (rate) { fv = (pmt * (1 + rate * type) * (1 - pow) / rate) - pv * pow; } else { fv = -1 * (pv + pmt * nper); } return fv; }; // calculate total of principle + interest (yearly) for x months lib.CALCULATEACCRUEDINTEREST = function(principle, months, rate){ var i = rate/1200; return (principle * Math.pow(1+i,months)) - principle; }; // determine the amount financed lib.CALCULATEAMOUNT = function(finMonths, finInterest, finPayment){ var result = 0; if(finInterest == 0){ result = finPayment * finMonths; } else{ var i = ((finInterest/100) / 12), i_to_m = Math.pow((i + 1), finMonths); result = finPayment / ((i * i_to_m) / (i_to_m - 1)); } return result; }; // determine the months financed lib.CALCULATEMONTHS = function(finAmount, finInterest, finPayment){ var result = 0; if(finInterest == 0){ result = Math.ceil(finAmount / finPayment); } else{ result = Math.round(( (-1/12) * (Math.log(1-(finAmount/finPayment)*((finInterest/100)/12))) / Math.log(1+((finInterest/100)/12)) )*12); } return result; }; // determine the interest rate financed http://www.hughchou.org/calc/formula.html lib.CALCULATEINTEREST = function(finAmount, finMonths, finPayment){ var result = 0; var min_rate = 0, max_rate = 100; while(min_rate < max_rate-0.0001){ var mid_rate = (min_rate + max_rate)/2, j = mid_rate / 1200, guessed_pmt = finAmount * ( j / (1-Math.pow(1+j, finMonths*-1))); if(guessed_pmt > finPayment){ max_rate = mid_rate; } else{ min_rate = mid_rate; } } return mid_rate; }; // determine the payment lib.CALCULATEPAYMENT = function(finAmount, finMonths, finInterest){ var result = 0; if(finInterest == 0){ result = finAmount / finMonths; } else{ var i = ((finInterest/100) / 12), i_to_m = Math.pow((i + 1), finMonths); result = finAmount * ((i * i_to_m) / (i_to_m - 1)); } return result; }; // get an amortization schedule [ { principle: 0, interest: 0, payment: 0, paymentToPrinciple: 0, paymentToInterest: 0}, {}, {}...] lib.CALCULATEAMORTIZATION = function(finAmount, finMonths, finInterest, finDate){ var payment = this.CALCULATEPAYMENT(finAmount, finMonths, finInterest), balance = finAmount, interest = 0.0, totalInterest = 0.0, schedule = [], currInterest = null, currPrinciple = null, currDate = (finDate !== undefined && finDate.constructor === Date)? finDate : (new Date()); for(var i=0; i= nper + 1)) return null; var pmt = this.PMT(rate, nper, pv, fv, type); var ipmt = this.IPMT(rate, per, nper, pv, fv, type); return pmt - ipmt; }; // Returns the net present value for a periodic schedule of cash flows lib.NPV = function(rate, vs) { var npv = 0; for (var i in vs ) npv += vs[i] / Math.pow(1+rate/100, i*1+1); return npv; }; // Returns the net present value for a schedule of cash flows that is not necessarily periodic lib.XNPV = function(rate, vs, ds) { var xnpv = 0, fd = ds[0]; for (var i in vs) xnpv += vs[i] / Math.pow(1 + rate/100, daysDiff(fd, ds[i])/365); return xnpv; }; // Calculates the internal rate of return for a list of payments which take place on different dates. lib.XIRR = function (vs, ds, guess) { var fd = ds[ 0 ], irrResult = function(r) { r++; var rs = vs[0]; for (var i = 1; i < vs.length; i++) { rs += vs[i] / Math.pow(r, daysDiff(ds[i], fd) / 365); } return rs; }, irrResultDeriv = function(r) { r++; var rs = 0; for (var i = 1; i < vs.length; i++) { var frac = daysDiff(ds[i],fd) / 365; rs -= frac * vs[i] / Math.pow(r, frac + 1); } return rs; }, p = false, n = false, resultRate = (typeof guess === 'undefined') ? 0.1 : guess/100, epsMax = 1e-10, iterMax = 50, newRate, epsRate, resultValue, iteration = 0, contLoop = true; for (var i = 0; i < vs.length; i++) { if (vs[i] > 0) p = true; if (vs[i] < 0) n = true; } if (!p || !n) return NaN; do { resultValue = irrResult(resultRate); newRate = resultRate - resultValue / irrResultDeriv(resultRate); epsRate = Math.abs(newRate - resultRate); resultRate = newRate; contLoop = (epsRate > epsMax) && (Math.abs(resultValue) > epsMax); } while(contLoop && (++iteration < iterMax)); if(contLoop) return NaN; // Return internal rate of return return resultRate; }; // Returns the modified internal rate of return for a series of periodic cash flows. lib.MIRR = function (v, fr, rr) { var n = v.length, p = [], i = [], num, den; for (var j = 0; j < n; j++) { if (v[j] < 0) p.push(v[j]); else i.push(v[j]); } num = -1*this.NPV(rr, i) * Math.pow(1 + rr/100, n - 1); den = this.NPV(fr, p) * (1 + fr/100); return (Math.pow(num / den, 1 / (n - 1)) - 1)*100; }; root.CF_FINANCE = lib; })(this); fbuilderjQuery = ( typeof fbuilderjQuery != 'undefined' ) ? fbuilderjQuery : jQuery; fbuilderjQuery[ 'fbuilder' ] = fbuilderjQuery[ 'fbuilder' ] || {}; fbuilderjQuery[ 'fbuilder' ][ 'modules' ] = fbuilderjQuery[ 'fbuilder' ][ 'modules' ] || {}; fbuilderjQuery[ 'fbuilder' ][ 'modules' ][ 'financial' ] = { 'prefix' : '', 'callback' : function() { fbuilderjQuery[ 'fbuilder' ][ 'extend_window' ]( fbuilderjQuery[ 'fbuilder' ][ 'modules' ][ 'financial' ][ 'prefix' ], CF_FINANCE ); }, 'validator' : function( v ) { return ( typeof v == 'number' ) ? isFinite( v ) : ( typeof v != 'undefined' ); } };/* * distance.js v0.2 * By: CALCULATED FIELD PROGRAMMERS * The script allows operations with distance * Copyright 2015 CODEPEOPLE * You may use this project under MIT or GPL licenses. */ ;(function(root){ var lib = {}, loadingFlag = false, defaultFormId = 'cp_calculatedfieldsf_pform_1', defaultUnitSystem = 'km', defaultTravelMode = 'driving', defaultAvoidHighways = false, defaultAvoidTolls = false, distanceArr = [], travelTimeArr= [], callbacks = []; /*** PRIVATE FUNCTIONS ***/ /* * Runs all callbacks after loading the Google API */ function _runCallbacks() { var h = callbacks.length; if( h ) { for( var i = 0; i < h; i++ ) { callbacks[i](); } } callbacks = []; }; /* * Inserts the SCRIPT tag for loading the Google API */ function _createScriptTags() { // If Google Maps has not been loaded, and has not been created the script tags for loading the API if( !loadingFlag ) { loadingFlag = true; var script=document.createElement('script'); script.type = "text/javascript"; script.src = '//maps.google.com/maps/api/js?'+( ( typeof google_api_key != 'undefined' ) ? 'key='+google_api_key+'&' : '' )+'callback=CPCFF_DISTANCE_MODULE_RUNCALLBACKS'; document.body.appendChild(script); } }; /* * Check the default value and the attribute and returns the correct value. */ function _getValue( attr, val ) { if( typeof google != 'undefined' && typeof google[ 'maps' ] != 'undefined' ) { val = String(val).toUpperCase(); switch( attr ) { case 'unitSystem': val = ( val == 'MI' ) ? google.maps.UnitSystem.IMPERIAL : google.maps.UnitSystem.METRIC; break; case 'travelMode': switch( val ) { case 'BICYCLING': val = google.maps.TravelMode.BICYCLING; break; case 'TRANSIT' : val = google.maps.TravelMode.TRANSIT; break; case 'WALKING' : val = google.maps.TravelMode.WALKING; break; default : val = google.maps.TravelMode.DRIVING; break; } break; } } return val; }; /* * Evaluate all equations in the form */ function _reCalculate( form_id ) { fbuilderjQuery.fbuilder.calculator.defaultCalc( '#'+form_id, false ); }; /*** PUBLIC FUNCTIONS ***/ lib.cf_distance_version = '0.2'; /* * DISTANCE( address_a_string, address_b_string, unit_system, travel_mode, form_id ) * * unit_system: * km - Kilometters * mi - Miles * * travel_mode: * DRIVING - Indicates standard driving directions using the road network * BICYCLING - Requests bicycling directions via bicycle paths & preferred streets * TRANSIT - Requests directions via public transit routes * WALKING - Requests walking directions via pedestrian paths & sidewalks * * form_id is passed from the _calculate function in the fbuilder.fcalculated.js file, and should not be passed from the equation's edition * * the function returns the distance between address_a and address_b, in the unit_system */ lib.DISTANCE = function( address_a, address_b, unit_system, travel_mode, form_id ){ if( typeof address_a != 'undefined' && typeof address_b != 'undefined' ) { address_a = (new String(address_a)).replace( /^\s+/, '' ).replace( /\s+$/, '' ); address_b = (new String(address_b)).replace( /^\s+/, '' ).replace( /\s+$/, '' ); if( address_a.length > 2 && address_b.length > 2 ) { if( typeof unit_system == 'undefined' ) unit_system = defaultUnitSystem; if( typeof travel_mode == 'undefined' ) travel_mode = defaultTravelMode; form_id = (typeof form_id != 'undefined') ? form_id : ((typeof $.fbuilder['currentFormId'] != 'undefined') ? $.fbuilder['currentFormId'] : defaultFormId); // The pair of address was processed previously for( var i in distanceArr ) { if( distanceArr[ i ][ 'a' ] == address_a && distanceArr[ i ][ 'b' ] == address_b ) return distanceArr[ i ][ 'distance' ]/((/mi/i.test(unit_system)) ? 1609.344 : 1000); } // Google Maps has not been included previously if( typeof google == 'undefined' || google['maps'] == null ) { // List of functions to be called after complete the Google Maps loading callbacks.push( ( function( address_a, address_b, unit_system, travel_mode, form_id ) { return function(){ DISTANCE( address_a, address_b, unit_system, travel_mode, form_id ) }; } )( address_a, address_b, unit_system, travel_mode, form_id ) ); _createScriptTags(); return; } var service = new google.maps.DistanceMatrixService(), request = { origins : [ address_a ], destinations: [ address_b ], travelMode : _getValue( 'travelMode', travel_mode ), unitSystem : _getValue( 'unitSystem', unit_system ), avoidHighways : defaultAvoidHighways, avoidTolls : defaultAvoidTolls }; service.getDistanceMatrix( request, ( function( form_id, request ) { return function (response, status) { var r; if (status == google.maps.DistanceMatrixStatus.OK) { try{ if( response.rows[ 0 ].elements[ 0 ].status == google.maps.DistanceMatrixElementStatus.OK) { r = response.rows[ 0 ].elements[ 0 ].distance[ 'value' ]; } else { if(typeof console != 'undefined') console.log('DistanceMatrixElementStatus:'+response.rows[ 0 ].elements[ 0 ].status); r = 'FAIL'; } }catch( err ){ r = 'FAIL'; } } else { if(typeof console != 'undefined') console.log('DistanceMatrixStatus:'+status); r = 'FAIL'; } distanceArr.push({'a':request.origins[ 0 ], 'b':request.destinations[ 0 ], 'distance':r}); _reCalculate( form_id ); }; } )( form_id, request ) ); } } return 0; }; /* * TRAVELTIME( address_a_string, address_b_string, as_text, travel_mode, avoid_highways, avoid_tolls ) * * as_text: * true or 1 - Returns a textual representation of travel time * false or 0 - Returns the travel time in seconds * * travel_mode: * DRIVING - Indicates standard driving directions using the road network * BICYCLING - Requests bicycling directions via bicycle paths & preferred streets * TRANSIT - Requests directions via public transit routes * WALKING - Requests walking directions via pedestrian paths & sidewalks * * avoid_highways: true, false * avoid_tolls: true, false * * form_id is passed from the _calculate function in the fbuilder.fcalculated.js file, and should not be passed from * the equation's edition * * the function returns the time between address_a and address_b */ lib.TRAVELTIME = function( address_a, address_b, as_text, travel_mode, avoid_highways, avoid_tolls, form_id ){ if( typeof address_a != 'undefined' && typeof address_b != 'undefined' ) { address_a = (new String(address_a)).replace( /^\s+/, '' ).replace( /\s+$/, '' ); address_b = (new String(address_b)).replace( /^\s+/, '' ).replace( /\s+$/, '' ); if( address_a.length > 2 && address_b.length > 2 ) { if( typeof as_text == 'undefined' ) as_text = false; if( typeof travel_mode == 'undefined' ) travel_mode = defaultTravelMode; if( typeof avoid_highways != 'boolean' ) avoid_highways = defaultAvoidHighways; if( typeof avoid_tolls != 'boolean' ) avoid_tolls = defaultAvoidTolls; form_id = (typeof form_id != 'undefined') ? form_id : ((typeof $.fbuilder['currentFormId'] != 'undefined') ? $.fbuilder['currentFormId'] : defaultFormId); // The pair of address was processed previously for( var i in travelTimeArr ) { if( travelTimeArr[ i ][ 'a' ] == address_a && travelTimeArr[ i ][ 'b' ] == address_b ) return travelTimeArr[ i ][ 'time' ]; } // Google Maps has not been included previously if( typeof google == 'undefined' || google['maps'] == null ) { // List of functions to be called after complete the Google Maps loading callbacks.push( ( function( address_a, address_b, as_text, travel_mode, avoid_highways, avoid_tolls, form_id ) { return function(){ TRAVELTIME( address_a, address_b, as_text, travel_mode, avoid_highways, avoid_tolls, form_id ) }; } )( address_a, address_b, as_text, travel_mode, avoid_highways, avoid_tolls, form_id ) ); _createScriptTags(); return; } var service = new google.maps.DistanceMatrixService(), request = { origins : [ address_a ], destinations: [ address_b ], travelMode : _getValue( 'travelMode', travel_mode ), avoidHighways : avoid_highways, avoidTolls : avoid_tolls }; service.getDistanceMatrix( request, ( function( form_id, as_text, request ) { return function (response, status) { var r; if (status == google.maps.DistanceMatrixStatus.OK) { try{ r = response.rows[ 0 ].elements[ 0 ].duration[ ( as_text ) ? 'text' : 'value' ]; }catch( err ){ r = 'FAIL'; } } else r = 'FAIL'; travelTimeArr.push({'a':request.origins[ 0 ], 'b':request.destinations[ 0 ], 'time':r}); _reCalculate( form_id ); }; } )( form_id, as_text, request ) ); } } return 0; }; lib.CPCFF_DISTANCE_MODULE_RUNCALLBACKS = function(){ _runCallbacks(); }; root.CF_DISTANCE = lib; })(this);fbuilderjQuery = ( typeof fbuilderjQuery != 'undefined' ) ? fbuilderjQuery : jQuery; fbuilderjQuery[ 'fbuilder' ] = fbuilderjQuery[ 'fbuilder' ] || {}; fbuilderjQuery[ 'fbuilder' ][ 'modules' ] = fbuilderjQuery[ 'fbuilder' ][ 'modules' ] || {}; fbuilderjQuery[ 'fbuilder' ][ 'modules' ][ 'distance' ] = { 'prefix' : '', 'callback' : function() { fbuilderjQuery[ 'fbuilder' ][ 'extend_window' ]( fbuilderjQuery[ 'fbuilder' ][ 'modules' ][ 'distance' ][ 'prefix' ], CF_DISTANCE ); } }; $.fbuilder[ 'controls' ] = ( typeof $.fbuilder[ 'controls' ] != 'undefined' ) ? $.fbuilder[ 'controls' ]: {}; $.fbuilder[ 'forms' ] = ( typeof $.fbuilder[ 'forms' ] != 'undefined' ) ? $.fbuilder[ 'forms' ]: {}; $.fbuilder[ 'htmlEncode' ] = function(value) { value = $('
').text(value).html() value = value.replace(/"/g, """) .replace(/&lt;/g, '<') .replace(/&gt;/g, '>'); return value; }; $.fbuilder[ 'htmlDecode' ] = function(value) { if( /&(?:#x[a-f0-9]+|#[0-9]+|[a-z0-9]+);?/ig.test( value ) ) value = $( '
' ).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, raw ) { raw = raw || false; if( typeof value == 'undefined' || value == null ) value = ''; /* value = $.trim( value.replace(/'/g, "\\'").replace( /\$/g, '\\$').replace(/"/g, '\\"') ); */ value = $.trim( value.replace(/\\/g, "\\\\") ).replace(/'/g, "\\'").replace(/"/g, '\\"'); return ($.isNumeric(value)) ? ((raw) ? value : value*1) : '"' + value + '"'; }; $.fbuilder[ 'parseVal' ] = function( value, thousandSeparator, decimalSymbol ) { if( typeof value == 'undefined' || value == null || value == '' ) return 0; value = $.trim(value); /* Check if date */ if(/(\d{1,2}[\/\.\-]\d{1,2}[\/\.\-]\d{4})|(\d{4}[\/\.\-]\d{1,2}[\/\.\-]\d{1,2})/.test(value)) return $.fbuilder[ 'parseValStr' ]( value ); /* Managing the value basically as number */ thousandSeparator = $.fbuilder.escape_symbol( ( typeof thousandSeparator == 'undefined' ) ? ',' : thousandSeparator ); decimalSymbol = ( typeof decimalSymbol == 'undefined' || /^\s*$/.test( decimalSymbol ) ) ? '.' : decimalSymbol; var correction = new RegExp( ( ( /^\s*$/.test( thousandSeparator ) ) ? ',' : thousandSeparator )+('\(\\d{1,2}\)$') ), correctionReplacement = decimalSymbol+'$1'; thousandSeparator = new RegExp( thousandSeparator, 'g' ); decimalSymbol = new RegExp( $.fbuilder.escape_symbol( decimalSymbol ), 'g' ); var t = value.replace( correction, correctionReplacement ) .replace( thousandSeparator, '' ) .replace( decimalSymbol, '.' ) .replace( /\s/g, '' ), p = /[+\-]?((\d+(\.\d+)?)|(\.\d+))(?:[eE][+\-]?\d+)?/.exec( t ); return ( p ) ? ((/^0\d/.test(p[0])) ? p[0].substr(1) : 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}", discount: "Discount: {0}, Final Price: {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}."), currency: "Please enter a valid currency value." },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 = [], reloadItemsPublic = function() { var form_tag = $("#fieldlist"+opt.identifier).closest( 'form' ); form_tag.addClass( theForm.formtemplate ); if( !opt.cached ) { $("#fieldlist"+opt.identifier).html("").addClass(theForm.formlayout); $("#formheader"+opt.identifier).html(theForm.show()); var page = 0; $("#fieldlist"+opt.identifier).append('
'); for (var i=0;i
'); } 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_t,uh = $("#fieldlist"+opt.identifier+" .pb"+page).find('[id*="'+items[i].name+'"]').closest(".dfield"); if( uh.length == 0 ) { uh = $("#fieldlist"+opt.identifier+" .pb"+page).find('[id*="'+items[i].name+'"]').closest(".fields"); } uh_t = uh.find(".uh"); if(uh_t.length && uh_t.html()!="") { uh.attr("uh",uh_t.html()); uh_t.html(""); } } } } } else { var page = form_tag.find( '.pbreak' ).length, i = items.length; } if (page>0) { if( !opt.cached ) // Check if the form is cached { $("#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 += '
'+$("#cpcaptchalayer"+opt.identifier).html()+'
'; $("#cpcaptchalayer"+opt.identifier).html(""); } if ($("#cp_subbtn"+opt.identifier).html()) { bSubmit = '
'+$("#cp_subbtn"+opt.identifier).html()+'
'; } } $(this).html('
'+opt.messages.pageof.replace( /\{\s*\d+\s*\}/, (index+1) ).replace( /\{\s*\d+\s*\}/, (page+1) )+''+code+'
'+opt.messages.previous+'
'+opt.messages.next+'
'+bSubmit+'
'); }); } $( '#fieldlist'+opt.identifier).find(".pbPrevious,.pbNext").bind("keyup", function(evt){ if(evt.which == 13 || evt.which == 32) $(this).click(); }).bind("click", {'identifier' : opt.identifier}, function(evt){ var _from = $(this).closest('.pbreak').attr('page')*1, _to = _from+(($(this).hasClass("pbPrevious")) ? -1 : 1), _p; _p = $.fbuilder['goToPage']( { 'formIdentifier' : evt.data.identifier, 'from' : _from, 'to' : _to } ); if(_p == _to) $.fbuilder.setBrowserHistory(); return false; }); } else { if( !opt.cached ) { if ( $( "#cpcaptchalayer"+opt.identifier ).length && !/^\s*$/.test( $( "#cpcaptchalayer"+opt.identifier ).html() ) ) { $("#fieldlist"+opt.identifier+" .pb"+page).append('
'+$("#cpcaptchalayer"+opt.identifier).html()+'
'); $("#cpcaptchalayer"+opt.identifier).html(""); } if ($("#cp_subbtn"+opt.identifier).html()) { $("#fieldlist"+opt.identifier+" .pb"+page).append('
'+$("#cp_subbtn"+opt.identifier).html()+'
'); } } } if( !opt.cached && opt.setCache) { var cloned_form = form_tag.clone(); cloned_form.find('[name="_wpnonce"],[name="_wp_http_referer"]').remove(); // Set Cache var url = document.location.href, data = { 'cffaction' : 'cff_cache', 'cache' : cloned_form.html().replace( /\n+/g, '' ), 'form' : cloned_form.find( '[name="cp_calculatedfieldsf_id"]').val() }; $.post( url, data, function( data ){ if(typeof console != 'undefined' )console.log( data ); } ); } // 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 ) ); } ); $( form_tag ).find( '.captcha img' ).click(); $( '#fieldlist'+opt.identifier).find(".pbSubmit").bind("keyup", function(evt){ if(evt.which == 13 || evt.which == 32) $(this).click(); }).bind("click", { 'identifier' : opt.identifier }, function(evt){ $(this).closest("form").submit(); }); if (i>0) { theForm.after_show( opt.identifier ); for (var i=0;i

'+this.title+'

'+this.description+'
'; }, after_show:function( id ){ var form = $( '#cp_calculatedfieldsf_pform'+id ); if(typeof $.fn.fbuilder_localstorage != 'undefined' && form.hasClass('persist-form')) { form.fbuilder_localstorage(); } form.attr( 'data-evalequations', this.evalequations ) .attr( 'data-evalequationsevent', this.evalequationsevent ) .attr( 'autocomplete', ( ( this.autocomplete ) ? 'on' : 'off' ) ) .find( 'input,select' ) .blur( function(){ try{ $(this).valid(); }catch(e){};} ); form.find( '[name="couponcode"]' ) .on('keyup',{'form':this.request_cost+id}, function(){ var e = $(this), v = e.val(); if(v.length) { if(e.next('.apply-coupon').length == 0) e.after('
'); } else { e.next('.apply-coupon').remove(); } e.closest('form').find('.discount-container').hide(); }); $(document).on('click', '#cp_calculatedfieldsf_pform'+id+' .apply-coupon', {'field':this.request_cost, 'sequence':id}, function(evt){ var me = $(this), c = me.prev('[name="couponcode"]'), v, r, f = me.closest('form'), s = evt.data.sequence, l = evt.data.field, fid = f.find('[name="cp_calculatedfieldsf_id"]'); if(c.length && f.length) { v = c.val(); r = $.getJSON( document.location.href, { "formid" : fid.val(), "formsequence" : s, "couponcode" : v, "action" : "checkcoupon", "_cpcff_public_nonce" : f.find('[id="_cpcff_public_nonce"]').val() }, function(data) { try{ var sequence = s, field = l+s, item = $.fbuilder.forms[sequence].getItem(field), price = item.val(), discount, final_price, dc = f.find('.discount-container'); if(dc.length == 0) { dc = $('
'); dc.appendTo(c.closest('div')); } dc.html('').hide(); if(!$.isEmptyObject(data)) { if('error' in data) { dc.html(data.error).show(); return; } data.availability *= 1; if(data.availability) { final_price = data.discount*1; discount = (!isNaN(discount = ABS(price-final_price))) ? discount : ' - '; } else{ final_price = price*(100-data.discount)/100; discount = data.discount+"%"; } if(item.ftype == 'fCalculated') { var format = { "prefix" : item.prefix, "suffix" : item.suffix, "groupingsymbol" : item.groupingsymbol, "decimalsymbol" : item.decimalsymbol }; final_price = $.fbuilder.calculator.format( PREC(final_price,2), format ); if(!isNaN(discount)) { discount = $.fbuilder.calculator.format( PREC(discount,2), format ); } } dc.html( opt.messages .discount .replace( /\{\s*\d+\s*\}/, discount ).replace( /\{\s*\d+\s*\}/, final_price ) ).show(); } }catch(err){} } ); } }); } }); //var theForm = new fform(), var theForm, ffunct = { toShow : {}, toHide : {}, hiddenByContainer : {}, getItem: function( name ) { var regExp = new RegExp((parseInt(name,10) == name) ? 'fieldname'+name+'_' : name+'_', i); for( var i in items ) { if( items[ i ].name == name || regExp.test(items[ i ].name)) { return items[ i ]; } } return false; }, getItems: function() { return items; }, loadData:function(f) { var d = window[ f ]; if ( typeof d != 'undefined' ) { if( typeof d == 'object' && ( typeof d.nodeType !== 'undefined' || d instanceof jQuery ) ){ d = jQuery.parseJSON( jQuery(d).val() ); } else if( typeof d == 'string' ){ d = jQuery.parseJSON( d ); } if (d.length == 2) { this.formId = d[ 1 ][ 'formid' ]; items = []; for (var i=0;i 1) ? document.URL.split('#')[1] : null, _match, _form, _to, setHistoryEntry = false, _goToPage = function(config){ }; if(bookmark) { while(_match = bookmark.match(/f(\d+)p(\d+)\|?/)) { _form = '_'+_match[1]; _to = _match[2]*1; if( !(_form in $.fbuilder.forms) || // Form exists !('currentPage' in $.fbuilder.forms[_form]) || // Next/Prev buttons has been pressed previously _to != $.fbuilder['goToPage']( { 'formIdentifier' : _form, 'from' : 0, 'to' : _to } ) ) setHistoryEntry = true; bookmark = bookmark.replace(_match[0],''); } } else { for(_form in $.fbuilder.forms) { if('currentPage' in $.fbuilder.forms[_form]) $.fbuilder['goToPage']( { 'formIdentifier' : _form,'from' : 0, 'to' : 0 } ); } } if(setHistoryEntry) $.fbuilder.setBrowserHistory(true); }; // End manageHistory $.fbuilder[ 'goToPage' ] = function( configObj ) { if( 'formIdentifier' in configObj && 'from' in configObj && 'to' in configObj ) { var identifier = configObj['formIdentifier'], _from = configObj['from']*1, _to = configObj['to']*1, direction = (_from < _to) ? 1 : -1, formObj = $('[id="'+$.fbuilder.forms[identifier].formId+'"]'), pageObj, i = _from; while(i != _to) { $(".pbreak:not(.pb"+i+")",formObj).find(".field").addClass("ignorepb"); $(".pb"+i,formObj).find(".field").removeClass("ignorepb"); if(direction == 1 && !formObj.valid()) break; i += direction; } $.fbuilder.forms[identifier]['currentPage'] = i; $(".pbreak:not(.pb"+i+")",formObj).hide().find(".field").addClass("ignorepb"); pageObj = $(".pbreak.pb"+i,formObj); pageObj.show().find(".field").removeClass("ignorepb"); if(i == _to) { if ($(".fields",pageObj).length>0) { try { var ffocusable = pageObj.find(":focusable"), _wScrollTop = $(window).scrollTop(), _viewportHeight = $(window).height(), _scrollTop = formObj.offset().top; if( ffocusable.length && !ffocusable.first().hasClass('hasDatepicker')) { ffocusable[0].focus(); } if(_scrollTop < _wScrollTop || (_wScrollTop+_viewportHeight)<_scrollTop ) { $( 'html, body' ).animate({scrollTop: _scrollTop}, 50); } } catch(e){} } } else { formObj.validate().focusInvalid(); } return i; } }; // End goToPage $.fbuilder[ 'showHideDep' ] = function( configObj ) { /** * If isNotFirstTime is defined, the equations associated to the fields should be inserted in the queue of equations */ var process_items = function( items, isNotFirstTime ) { for( var i = 0, h = items.length; i < h; i++ ) { if( typeof items[ i ] == 'string' ) items[i] = $.fbuilder[ 'forms' ][ identifier ].getItem( items[i] ); if( isNotFirstTime && items[i] && items[i].usedInEquations ) $.fbuilder[ 'calculator' ].enqueueEquation( identifier, items[i].usedInEquations ); if( typeof items[ i ][ 'showHideDep' ] != 'undefined' ) { var list = items[ i ][ 'showHideDep' ]( toShow, toHide, hiddenByContainer ); if( typeof list != 'undefined' && list.length ) process_items( list, true ); } } }; if( typeof configObj[ 'formIdentifier' ] !== 'undefined' ) { var identifier = configObj[ 'formIdentifier' ]; if( typeof $.fbuilder[ 'forms' ][ identifier ] != 'undefined' ) { var toShow = $.fbuilder[ 'forms' ][ identifier ][ 'toShow' ], toHide = $.fbuilder[ 'forms' ][ identifier ][ 'toHide' ], hiddenByContainer = $.fbuilder[ 'forms' ][ identifier ][ 'hiddenByContainer' ], items = (typeof configObj[ 'fieldItentifier' ] != 'undefined' ) ? [ $.fbuilder[ 'forms' ][ identifier ].getItem(configObj[ 'fieldItentifier' ].replace(/_[cr]b\d+$/i, '')) ] : $.fbuilder[ 'forms' ][ identifier ].getItems(); process_items( items ); if( typeof configObj[ 'throwEvent' ] == 'undefined' || configObj[ 'throwEvent' ] ) { $( document ).trigger( 'showHideDepEvent', $.fbuilder[ 'forms' ][ identifier ][ 'formId' ] ); } } } }; // End showHideDep // Load default values $.fbuilder[ 'cpcff_load_defaults' ] = function( o ) { var $ = fbuilderjQuery, id, item, form_data, form_obj; if( typeof cpcff_default != 'undefined' ) { id = o.identifier.replace( /[^\d]/g, '' ); if( typeof cpcff_default[ id ] != 'undefined' ) { form_data = cpcff_default[ id ]; id = '_'+id; form_obj = $.fbuilder[ 'forms' ][ id ]; for( var field_id in form_data ) { item = form_obj.getItem( field_id+id ); if( typeof item[ 'setVal' ] != 'undefined' ) item.setVal( form_data[ field_id ] ); } $.fbuilder.showHideDep( { 'formIdentifier' : o.identifier, 'throwEvent' : true } ); } } }; // Read history window.addEventListener('popstate', function(){ try { // Solves an issue with the datepicker if it is opened and back/next buttons in browser are pressed $(".ui-datepicker").hide(); $.fbuilder.manageHistory(); } catch(err){} }); $(window).on('load', function(){ $.fbuilder.manageHistory(); }); $.fbuilder.controls[ 'ftext' ]=function(){}; $.extend( $.fbuilder.controls[ 'ftext' ].prototype, $.fbuilder.controls[ 'ffields' ].prototype, { title:"Untitled", ftype:"ftext", predefined:"", predefinedClick:false, required:false, readonly:false, size:"medium", minlength:"", maxlength:"", equalTo:"", regExp:"", regExpMssg:"", show:function() { this.minlength = $.fbuilder.htmlEncode($.trim(this.minlength)); this.maxlength = $.fbuilder.htmlEncode($.trim(this.maxlength)); this.equalTo = $.fbuilder.htmlEncode($.trim(this.equalTo)); return '
'+this.userhelp+'
'; }, after_show:function() { if( this.regExp != "" && typeof $[ 'validator' ] != 'undefined' ) { var parts = this.regExp.match(/(\/)(.*)(\/)([gimy]{0,4})$/i); this.regExp = ( parts === null ) ? new RegExp(this.regExp) : new RegExp(parts[2],parts[4].toLowerCase()); if(!('pattern' in $.validator.methods)) $.validator.addMethod( 'pattern', function( value, element, param ) { try{ return this.optional(element) || param.test( value ); } catch(err){return true;} } ); $('#'+this.name).rules('add',{'pattern':this.regExp, messages:{'pattern':this.regExpMssg}}); } }, val:function(raw) { raw = raw || false; var e = $( '[id="' + this.name + '"]:not(.ignore)' ); if( e.length ) return $.fbuilder.parseValStr( e.val(), raw ); return 0; } } ); $.fbuilder.controls[ 'fcurrency' ] = function(){}; $.extend( $.fbuilder.controls[ 'fcurrency' ].prototype, $.fbuilder.controls[ 'ffields' ].prototype, { title:"Currency", ftype:"fcurrency", predefined:"", predefinedClick:false, required:false, readonly:false, size:"small", currencySymbol:"$", currencyText:"USD", thousandSeparator:",", centSeparator:".", noCents: false, min:"", max:"", formatDynamically:false, getFormattedValue:function( value ) { if(value == '') return value; var me = this, ts = me.thousandSeparator, cs = ((cs = $.trim(me.centSeparator)) !== '') ? cs : '.', v = $.fbuilder.parseVal(value, ts, cs), parts = [], counter = 0, str = '', sign = ''; if( !isNaN( v ) ) { if(v < 0) sign = '-'; v = ABS(v); parts = v.toString().split("."); for( var i = parts[0].length-1; i >= 0; i--) { counter++; str = parts[0][i] + str; if( counter%3 == 0 && i != 0 ) str = ts + str; } parts[0] = str; if(parts[1]) { if(parts[1].length == 1) parts[1] += '0'; } else parts[ 1 ] = '00'; return me.currencySymbol+sign+((me.noCents)?parts[0]:parts.join(cs))+me.currencyText; } else { return value; } }, show:function() { return '
'+this.userhelp+'
'; }, after_show:function() { var me = this; if( this.formatDynamically ) { $( document ).on( 'change', '[name="' + me.name + '"]', function(){ this.value = me.getFormattedValue( this.value ); } ); } if( typeof $[ 'validator' ] != 'undefined' ) { if(!('cffcurrency' in $.validator.methods)) $.validator.addMethod( 'cffcurrency', function(v, el) { var f = el.id.match( /_\d+$/), esc = $.fbuilder.escape_symbol, r; e = $.fbuilder['forms'][f[0]].getItem( el.name ); r = new RegExp('^\\s*('+esc(e.currencySymbol)+')?\\s*\\-?\\d+('+esc(e.thousandSeparator)+'\\d{3})*'+((e.noCents) ? '': '('+e.centSeparator+'\\d+)?')+'\\s*('+esc(e.currencyText)+')?\\s*$','i'); return this.optional(el) || r.test(v) || ($.isNumeric(v) && (!e.noCents || v === FLOOR(v))); }, $.validator.messages['currency'] ); $.validator.methods.min = function(v, el, p) { var f = el.id.match( /_\d+$/), e; if(f) e = $.fbuilder['forms'][f[0]].getItem(el.name); if(e) v = e.val(); return this.optional(el) || v >= p; }; $.validator.methods.max = function(v, el, p) { var f = el.id.match( /_\d+$/), e; if(f) e = $.fbuilder['forms'][f[0]].getItem(el.name); if(e) v = e.val(); return this.optional(el) || v <= p; }; } }, val:function(raw) { raw = raw || false; var e = $( '[id="' + this.name + '"]:not(.ignore)' ); if( e.length ) { var v = e.val(); if(raw) return ($.isNumeric(v)) ? v : $.fbuilder.parseValStr(v, raw); v = $.trim(v); 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, readonly:false, size:"small", thousandSeparator:"", decimalSymbol:".", min:"", max:"", formatDynamically:false, dformat:"digits", formats:new Array("digits","number"), getFormattedValue:function( value ) { if(value == '') return value; var ts = this.thousandSeparator, ds = ((ds=$.trim(this.decimalSymbol)) !== '') ? ds : '.', v = $.fbuilder.parseVal(value, ts, ds), s = '', counter = 0, str = '', parts = []; if(!isNaN(v)) { if(v < 0) s = '-'; v = ABS(v); parts = v.toString().split("."); for(var i = parts[0].length-1; i >= 0; i--){ counter++; str = parts[0][i] + str; if(counter%3 == 0 && i != 0) str = ts + str; } parts[0] = str; return s+parts.join(ds); } else { return value; } }, show:function() { var _type = ( this.dformat == 'digits' || ( /^\s*$/.test( this.thousandSeparator ) && /^\s*\.\s*$/.test( this.decimalSymbol ) ) ) ? 'number' : 'text'; return '
'+this.userhelp+'
'; }, after_show:function() { var me = this; if( this.formatDynamically && this.dformat != 'digits' ) { $( document ).on( 'change', '[name="' + me.name + '"]', function(){ this.value = me.getFormattedValue( this.value ); } ); } if( typeof $[ 'validator' ] != 'undefined' ) { $.validator.methods.number = function(v, el) { var f = el.id.match(/_\d+$/), esc = $.fbuilder.escape_symbol, e, r; if(f) e = $.fbuilder['forms'][f[0]].getItem(el.name); if(!e) e = {thousandSeparator: ',', decimalSymbol: '.'}; r = new RegExp('^\\s*\\-?\\d+('+esc(e.thousandSeparator)+'\\d{3})*('+esc(e.decimalSymbol)+'\\d+)?\\s*$','i'); return this.optional(el) || r.test(v) || $.isNumeric(v); }; $.validator.methods.min = function(v, el, p) { var f = el.id.match( /_\d+$/), e; if(f) e = $.fbuilder['forms'][f[0]].getItem(el.name); if(e) v = e.val(); return this.optional(el) || v >= p; }; $.validator.methods.max = function(v, el, p) { var f = el.id.match( /_\d+$/), e; if(f) e = $.fbuilder['forms'][f[0]].getItem(el.name); if(e) v = e.val(); return this.optional(el) || v <= p; }; } }, val:function(raw) { raw = raw || false; var e = $( '[id="' + this.name + '"]:not(.ignore)' ); if( e.length ) { var v = $.trim( e.val() ); if(raw) return ($.isNumeric(v) && this.thousandSeparator != '.') ? v : $.fbuilder.parseValStr(v, raw); return $.fbuilder.parseVal(v, this.thousandSeparator, this.decimalSymbol); } return 0; } } ); $.fbuilder.controls[ 'fslider' ] = function(){}; $.extend( $.fbuilder.controls[ 'fslider' ].prototype, $.fbuilder.controls[ 'ffields' ].prototype, { title:"Slider", ftype:"fslider", predefined:"", predefinedMin:"", predefinedMax:"", predefinedClick:false, size:"small", thousandSeparator:",", centSeparator:".", min:0, max:100, step:1, range:false, minCaption:"", maxCaption:"", caption:"{0}", _getAttr:function(attr) { if($.isNumeric(this[attr])) return parseFloat(this[attr]); var f = this.getField(this[attr]); if(f) return parseFloat(f.val()); return 0; }, _setHndl:function(attr, one) { if($.isNumeric(this[attr])) return; let s = (/^fieldname\d+$/i) ? '[id*="'+this[attr]+this.form_identifier+'"]' : this[attr], i = (one) ? 'one' : 'on'; var me = this; $(document)[i]('change', s, function(){ if(me['set_'+attr]) me['set_'+attr](me._getAttr(attr));}); }, _setThousandsSeparator : function(v) { 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'; } return parts.join( this.centSeparator ); } else { return v; } }, _setFieldValue:function() { var me = this; if( me.range ) { var values = $( '#'+me.name+'_slider' ).slider( 'values' ); $( '#'+me.name ).val( '[' + values[ 0 ] + ',' + values[ 1 ] + ']' ); $( '#'+me.name+'_caption' ).html( me.caption .replace( /\{\s*0\s*\}/, me._setThousandsSeparator( values[ 0 ] ) ) .replace( /\{\s*0\s*\}/, me._setThousandsSeparator( values[ 1 ] ) ) ); } else { var value = $( '#'+me.name+'_slider' ).slider( 'value' ); $( '#'+me.name ).val( value ); $( '#'+me.name+'_caption' ).html( me.caption .replace( /\{\s*0\s*\}/, me._setThousandsSeparator( value ) ) ); } $( '#'+me.name ).change(); }, init:function() { this.min = (/^\s*$/.test(this.min)) ? 0 : $.trim(this.min); this.max = (/^\s*$/.test(this.max)) ? 100 : $.trim(this.max); this.step = (/^\s*$/.test(this.step)) ? 1 : $.trim(this.step); this.predefined = (/^\s*$/.test(this.predefined)) ? this.min : $.trim(this.predefined); this.predefinedMin = (/^\s*$/.test(this.predefinedMin))? this.min : $.trim(this.predefinedMin); this.predefinedMax = (/^\s*$/.test(this.predefinedMax))? this.max : $.trim(this.predefinedMax); this._setHndl('min'); this._setHndl('max'); this._setHndl('step'); this.centSeparator = ( /^\s*$/.test( this.centSeparator )) ? '.' : $.trim( this.centSeparator ); this.thousandSeparator = $.trim( this.thousandSeparator ); }, show:function() { return '
'+this.minCaption+''+this.maxCaption+'
'+this.userhelp+'
'; }, set_min : function(v) { var e = $('[id="'+this.name+'_slider"]'), c = this.val(), r = false; e.slider( 'option', 'min', v ); if($.isArray(c)){if(c[0] < v){c[0] = v; r = true;}} else if(c < v){c = v; r = true;} if(r) this.setVal(c); }, set_max : function(v) { var e = $('[id="'+this.name+'_slider"]'), c = this.val(), r = false; e.slider( 'option', 'max', v ); if($.isArray(c)){if(v < c[1]){c[1] = v; r = true;}} else if(v < c){c = v; r = true;} if(r) this.setVal(c); }, set_step : function(v) { $('[id="'+this.name+'_slider"]').slider( "option", "step", v ); }, after_show:function() { var me = this, opt = { range: (me.range != false) ? me.range : "min", min : me._getAttr('min'), max : me._getAttr('max'), step : me._getAttr('step') }; if( me.range ) { var _min = Math.min( Math.max( me._getAttr('predefinedMin'), opt.min ), opt.max ), _max = Math.min( Math.max( me._getAttr('predefinedMax'), opt.min ), opt.max ); opt[ 'values' ] = [ _min, _max ]; } else opt[ 'value' ] = Math.min( Math.max( me._getAttr('predefined'), opt.min ), opt.max ); opt[ 'slide' ] = opt[ 'stop' ] = ( function( e ){ return function( event, ui ) { if( typeof ui.value != 'undefined' ) $(this).slider('value', ui.value); if( typeof ui.values != 'undefined' ) $(this).slider('values', ui.values); e._setFieldValue(); } } )( me ); $( '#'+this.name+'_slider' ).slider( opt ); me._setFieldValue(); $( '#cp_calculatedfieldsf_pform'+me.form_identifier ).bind( 'reset', function(){ $( '#'+me.name+'_slider' ).slider( opt ); me._setFieldValue(); } ); }, val:function(raw) { raw = raw || false; var e = $( '[id="' + this.name + '"]:not(.ignore)' ); return ( e.length ) ? ((raw) ? e.val() : JSON.parse(e.val())) : 0; }, setVal:function( v ) { try{ v = JSON.parse(v); }catch(err){} try{ $( '[name="'+this.name+'"]' ).val( v ); $(this.name+'_slider').slider((($.isArray(v)) ? 'values' : 'value'), v); this._setFieldValue(); }catch( err ){} } }); $.fbuilder.controls[ 'femail' ] = function(){}; $.extend( $.fbuilder.controls[ 'femail' ].prototype, $.fbuilder.controls[ 'ffields' ].prototype, { title:"Email", ftype:"femail", predefined:"", predefinedClick:false, required:false, readonly:false, size:"medium", equalTo:"", show:function() { return '
'+this.userhelp+'
'; }, val:function(raw) { raw = raw || false; var e = $( '[id="' + this.name + '"]:not(.ignore)' ); if( e.length ) return $.fbuilder.parseValStr( e.val() , raw); return 0; } } ); $.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, defaultDate:"", defaultTime:"", working_dates:[true,true,true,true,true,true,true], init:function() { var me = this; function checkValue( v, min, max ) { v = parseInt( v ); v = ( isNaN( v ) ) ? max : v; return Math.min(Math.max(v,min),max); } 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 ) ); me.dformat = me.dformat.replace(/\//g, me.dseparator); me.invalidDates = me.invalidDates.replace( /\s+/g, '' ); 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++; } } } } } }, 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 += ''; i++; } return ':'; }, 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 += ''; i++; } return ''; }, get_ampm:function() { var str = ''; if( this.tformat == 12 ) { return ''; } return str; }, set_date_time:function() { var me = this, str = $( '#'+me.name+'_date' ).val(); if( me.showTimepicker ) { var h = $( '#'+me.name+'_hours' ).val()*1; str += ' '; if( me.tformat == 12 ) { h = (h==12) ? 0 : h; if( $( '#'+me.name+'_ampm' ).val() == 'pm' ) str += ( h + 12 ); else str += h; } else str += h; str += ':'+$( '#'+me.name+'_minutes' ).val(); } $( '#'+me.name ).val( str ).change(); }, 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)?' 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 '
'+( ( me.showTimepicker ) ? ' '+me.get_hours()+me.get_minutes()+' '+me.get_ampm() : '' )+''+me.userhelp+'
'; }, setDefaultDate : function() { var me = this, p = { dateFormat: me.dformat.replace(/yyyy/g,"yy"), minDate: me.minDate, maxDate: me.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 ) { if( me.dropdownRange.indexOf( ':' ) == -1 ) me.dropdownRange = '-10:+10'; 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", ''); } }, setDefaultTime : function() { var me = this; function setValue( 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; if( ( parts = /(\d{1,2}):(\d{1,2})/g.exec( me.defaultTime ) ) != null ) { time[ 'hour' ] = parts[ 1 ]; time[ 'minute' ] = parts[ 2 ]; } else { var d = new Date(); time[ 'hour' ] = Math.min(Math.max(d.getHours(), me.minHour), me.maxHour); time[ 'minute' ] = d.getMinutes(); if(time[ 'hour' ] == me.minHour) time[ 'minute' ] = Math.max(time['minute'],me.minMinute); if(time[ 'hour' ] == me.maxHour) 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' ], me.maxMinute ); $( '#'+me.name+'_ampm'+' [value="' + ( ( time[ 'hour' ] < 12 ) ? 'am' : 'pm' ) + '"]' ).prop( 'selected', true ); } }, setEvents : function() { var me = this, f = function(){ $( '#'+me.name+'_date' ).valid(); me.set_date_time(); }; $( 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.setDefaultDate(); me.setDefaultTime(); me.set_date_time(); }, 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; }, after_show:function() { 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.setDefaultDate(); me.setDefaultTime(); me.setEvents(); me.set_date_time(); }, val:function(raw) { raw = raw || false; var me = this, e = $( '[id="' + me.name + '"]:not(.ignore)' ), dformat = me.dformat.replace(new RegExp('\\'+me.dseparator, 'g'), 'https://www.moneyunder30.com/'); 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}))?' ), d = re.exec( v ), h = 0, m = 0, date; if( d ) { if( typeof d[ 5 ] != 'undefined' ) h = d[ 5 ]; if( typeof d[ 6 ] != 'undefined' ) m = d[ 6 ]; 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( ' ' ); this.defaultDate = v[ 0 ]; this.setDefaultDate(); if( v.length == 2 ) { this.defaultTime = v[ 1 ]; this.setDefaultTime(); } this.set_date_time(); } catch( err ) {} } } ); $.fbuilder.controls[ 'ftextarea' ] = function(){}; $.extend( $.fbuilder.controls[ 'ftextarea' ].prototype, $.fbuilder.controls[ 'ffields' ].prototype, { title:"Untitled", ftype:"ftextarea", predefined:"", predefinedClick:false, required:false, readonly:false, size:"medium", minlength:"", maxlength:"", rows:4, show:function() { return '
'+this.userhelp+'
'; }, val:function(raw) { raw = raw || false; var e = $( '[id="' + this.name + '"]:not(.ignore)' ); if( e.length ) return $.fbuilder.parseValStr(e.val().replace(/[\n\r]+/g, ' '), raw); return 0; } } ); $.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, merge:1, max:-1, maxError:"Check no more than {0} boxes", toSubmit:"text", showDep:false, show:function() { this.choicesVal = ((typeof(this.choicesVal) != "undefined" && this.choicesVal !== null)?this.choicesVal:this.choices); var str = "", classDep; if ( typeof this.choicesDep == "undefined" || this.choicesDep == null ) this.choicesDep = new Array(); for (var i=0, h=this.choices.length; i'; } return '
'+str+''+this.userhelp+'
'; }, after_show:function() { var m = this; $(document).on('click','[id*="'+m.name+'"]', function(){ if(0 < m.max) { var d = true; if($('[id*="'+m.name+'"]:checked').length < m.max) d = false; $('[id*="'+m.name+'"]:not(:checked)').prop('disabled', d); } }); if(0 < m.max) $('[id*="'+m.name+'"]').rules('add',{maxlength:m.max, messages:{maxlength:m.maxError}}); }, showHideDep:function( toShow, toHide, hiddenByContainer ) { var me = this, item = $( '[id*="'+me.name+'"]' ), form_identifier = me.form_identifier, isHidden = (typeof toHide[ me.name ] != 'undefined' || typeof hiddenByContainer[ me.name ] != 'undefined' ), result = []; try { item.each(function(i,e){ if( typeof me.choicesDep[i] != 'undefined' && me.choicesDep[ i ].length ) { var checked = e.checked; for( var j = 0, k = me.choicesDep[ i ].length; j < k; j++) { var dep = me.choicesDep[i][j]+form_identifier; if( isHidden || !checked) { if( typeof toShow[ dep ] != 'undefined' ) { delete toShow[ dep ][ 'ref' ][ me.name+'_'+i ]; if( $.isEmptyObject(toShow[ dep ][ 'ref' ]) ) delete toShow[ dep ]; } if( typeof toShow[ dep ] == 'undefined' ) { $( '[id*="'+dep+'"],.'+dep ).closest( '.fields' ).hide(); $( '[id*="'+dep+'"]:not(.ignore)' ).addClass( 'ignore' ); toHide[ dep ] = {}; } } else { delete toHide[ dep ]; if( typeof toShow[ dep ] == 'undefined' ) toShow[ dep ] = { 'ref': {}}; toShow[ dep ][ 'ref' ][ me.name+'_'+i ] = 1; if(!(dep in hiddenByContainer)) { $( '[id*="'+dep+'"],.'+dep ).closest( '.fields' ).show(); $( '[id*="'+dep+'"].ignore' ).removeClass( 'ignore' ); } } if($.inArray(dep,result) == -1) result.push( dep ); } } }); } catch( e ){ } return result; }, val:function(raw) { raw = raw || false; var v, me = this, m = me.merge && !raw, e = $('[id*="' + me.name + '"]:checked:not(.ignore)'); if(!m) v = []; if( e.length ) { e.each( function(){ var t = (m) ? $.fbuilder.parseVal(this.value) : $.fbuilder.parseValStr(this.value, raw); if(!$.isNumeric(t)) t = t.replace(/^"/,'').replace(/"$/,''); if(m) v = (v)?v+t:t; else v.push(t); }); } return (typeof v == 'object' && typeof v['length'] !== 'undefined') ? v : ((v) ? (($.isNumeric(v)) ? v : '"'+v+'"') : 0); }, setVal:function( v ) { var t, n = this.name; if( !$.isArray( v ) ) v = [v]; $( '[id*="'+n+'"]' ).prop( 'checked', false ); for( var i in v ) { t = (new String(v[i])).replace(/(['"])/g, "\\$1"); $( '[id*="'+n+'"][vt="'+t+'"],[id*="'+n+'"][value="'+t+'"]' ).prop( 'checked', true ); } $( '[id*="'+n+'"]' ).change(); } } ); $.fbuilder.controls[ 'fradio' ]=function(){}; $.extend( $.fbuilder.controls[ 'fradio' ].prototype, $.fbuilder.controls[ 'ffields' ].prototype, { title:"Select a Choice", ftype:"fradio", layout:"one_column", required:false, toSubmit:"text", choiceSelected:"", showDep:false, untickAccepted:true, show:function() { this.choicesVal = ((typeof(this.choicesVal) != "undefined" && this.choicesVal !== null)?this.choicesVal:this.choices); var l = this.choices.length, str = "", classDep = ""; if ( typeof this.choicesDep == "undefined" || this.choicesDep == null ) this.choicesDep = new Array(); for (var i=0;i'; } return '
'+str+''+this.userhelp+'
'; }, after_show: function() { var me = this, n = me.name; if(me.untickAccepted) { $(document).off('click', '[id*="'+n+'"]').on('click', '[id*="'+n+'"]', function(){ var m = this, e = $(m); $('[id*="'+n+'"]').each(function(){if(m !== this) $(this).data('previous-status', false);}); if(e.data('previous-status')){ m.checked = false; e.change();} e.data('previous-status', m.checked); }); } }, showHideDep:function( toShow, toHide, hiddenByContainer ) { var me = this, item = $( '[id*="'+me.name+'"]' ), form_identifier = me.form_identifier, isHidden = ( typeof toHide[ me.name ] != 'undefined' || typeof hiddenByContainer[ me.name ] != 'undefined' ), result = []; try { item.each(function(i,e){ if( typeof me.choicesDep[i] != 'undefined' && me.choicesDep[ i ].length ) { var checked = e.checked; for( var j = 0, k = me.choicesDep[ i ].length; j < k; j++) { var dep = me.choicesDep[i][j]+form_identifier; if(isHidden || !checked) { if(typeof toShow[ dep ] != 'undefined') { delete toShow[ dep ][ 'ref' ][ me.name+'_'+i ]; if( $.isEmptyObject(toShow[ dep ][ 'ref' ]) ) delete toShow[ dep ]; } if( typeof toShow[ dep ] == 'undefined' ) { $( '[id*="'+dep+'"],.'+dep ).closest( '.fields' ).hide(); $( '[id*="'+dep+'"]:not(.ignore)' ).addClass( 'ignore' ); toHide[ dep ] = {}; } } else { delete toHide[ dep ]; if( typeof toShow[ dep ] == 'undefined' ) toShow[ dep ] = { 'ref': {}}; toShow[ dep ][ 'ref' ][ me.name+'_'+i ] = 1; if(!(dep in hiddenByContainer)) { $( '[id*="'+dep+'"],.'+dep ).closest( '.fields' ).show(); $( '[id*="'+dep+'"].ignore' ).removeClass( 'ignore' ); } } if($.inArray(dep,result) == -1) result.push( dep ); } } }); } catch( e ){ } return result; }, val:function(raw) { raw = raw || false; var e = $( '[id*="' + this.name + '"]:not(.ignore):checked' ); if( e.length ) return $.fbuilder.parseValStr( e.val(), raw ); return 0; }, setVal:function( v ) { var t = (new String(v)).replace(/(['"])/g, "\\$1"), n = this.name; $( '[id*="'+n+'"]' ).prop( 'checked', false ); $( '[id*="'+n+'"][vt="'+t+'"],[id*="'+n+'"][value="'+t+'"]' ).prop( 'checked', true ); $( '[id*="'+n+'"]' ).change(); } } ); $.fbuilder.controls[ 'fdropdown' ]=function(){}; $.extend( $.fbuilder.controls[ 'fdropdown' ].prototype, $.fbuilder.controls[ 'ffields' ].prototype, { title:"Select a Choice", ftype:"fdropdown", size:"medium", required:false, toSubmit:"text", merge:0, choiceSelected:"", multiple:false, vChoices:1, showDep:false, show:function() { this.choicesVal = ((typeof(this.choicesVal) != "undefined" && this.choicesVal !== null)?this.choicesVal:this.choices) var c = this.choices, cv = this.choicesVal, og = (typeof this.optgroup == 'undefined') ? new Array() : this.optgroup, op_o = false, l = c.length, classDep = '', str = ''; if ( typeof this.choicesDep == "undefined" || this.choicesDep == null ) this.choicesDep = new Array(); for (var i=0;i'; op_o = true; } else { str += ''; } } if(op_o) str += ''; return '
'+ '
'+this.userhelp+'
'; }, showHideDep:function( toShow, toHide, hiddenByContainer ) { var me = this, item = $( '#'+me.name+'.depItemSel' ), form_identifier = me.form_identifier, isHidden = ( typeof toHide[ me.name ] != 'undefined' || typeof hiddenByContainer[ me.name ] != 'undefined' ), result = []; try { if( item.length ) { var selected = []; $(item).find(':selected').each(function(){selected.push($(this).data('i'));}); for( var i = 0, h = me.choices.length; i < h; i++ ) { if( typeof me.choicesDep[i] != 'undefined' && me.choicesDep[ i ].length ) { for( var j = 0, k = me.choicesDep[ i ].length; j < k; j++) { var dep = me.choicesDep[i][j]+form_identifier; if( isHidden || $.inArray(i,selected) == -1) { if( typeof toShow[ dep ] != 'undefined' ) { delete toShow[ dep ][ 'ref' ][ me.name+'_'+i ]; if( $.isEmptyObject(toShow[ dep ][ 'ref' ]) ) delete toShow[ dep ]; } if( typeof toShow[ dep ] == 'undefined' ) { $( '[id*="'+dep+'"],.'+dep ).closest( '.fields' ).hide(); $( '[id*="'+dep+'"]:not(.ignore)' ).addClass( 'ignore' ); toHide[ dep ] = {}; } } else { delete toHide[ dep ]; if( typeof toShow[ dep ] == 'undefined' ) toShow[ dep ] = { 'ref': {}}; toShow[ dep ][ 'ref' ][ me.name+'_'+i ] = 1; if(!(dep in hiddenByContainer)) { $( '[id*="'+dep+'"],.'+dep ).closest( '.fields' ).show(); $( '[id*="'+dep+'"].ignore' ).removeClass( 'ignore' ); } } if($.inArray(dep,result) == -1) result.push( dep ); } } } } } catch( e ){} return result; }, val:function(raw) { raw = raw || false; var e = $( '[id="' + this.name + '"]:not(.ignore) option:selected' ), v, m = this.multiple, g = this.merge && !raw; if(m && !g) v = []; if(e.length) { e.each(function(){ var t = $.fbuilder.parseValStr( this.value, raw ); if(!$.isNumeric(t)) t = t.replace(/^"/,'').replace(/"$/,''); if(!m || g) v = (v)?v+t:t; else v.push(t); }); } return (typeof v == 'object' && typeof v['length'] !== 'undefined') ? v : ((v) ? (($.isNumeric(v)) ? v : '"'+v+'"') : 0); }, setVal:function( v ) { if( !$.isArray( v ) ) v = [v]; var t, n = this.name; for(var i in v) { t = (new String(v[i])).replace(/(['"])/g, "\\$1"); $( '[id="'+n+'"] OPTION[vt="'+t+'"],[id="'+n+'"] OPTION[value="'+t+'"]' ).prop( 'selected', true ); } $( '[id="'+n+'"]' ).change(); } } ); $.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, show:function() { this.accept = $.fbuilder.htmlEncode($.trim(this.accept)); this.upload_size = $.fbuilder.htmlEncode($.trim(this.upload_size)); return '
'+this.userhelp+'
'; }, after_show:function() { var me = this; 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(!('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(){ $( this ).siblings( 'span.files-list' ).remove(); if( this.files.length > 1 ) { var filesList = []; for( var i = 0, h = this.files.length; i < h; i++ ) filesList.push( this.files[ i ].name ) $( this ).after( ''+filesList.join( ', ' )+'' ); } }); } } ); $.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 '
'+this.userhelp+'
'; }, val:function(raw) { raw = raw || false; var e = $( '[id="' + this.name + '"]:not(.ignore)' ); if( e.length ) return $.fbuilder.parseValStr( e.val(), raw ); return 0; } } ); $.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", 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
'+$.trim(tmp[i])+'
'; } } return '
'+str+''+this.userhelp+'
'; }, after_show: function() { var me = this, tmp = me.dformat.split(' '); 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 '
'+this.userhelp+'
'; } } ); $.fbuilder.controls[ 'fhidden' ]=function(){}; $.extend( $.fbuilder.controls[ 'fhidden' ].prototype, $.fbuilder.controls[ 'ffields' ].prototype, { ftype:"fhidden", title:"", predefined:"", show:function() { return '
'; } } ); $.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 '
'+this.userhelp+'
'; } } ); $.fbuilder.controls[ 'fPageBreak' ]=function(){}; $.extend( $.fbuilder.controls[ 'fPageBreak' ].prototype, $.fbuilder.controls[ 'ffields' ].prototype, { title:"Page Break", ftype:"fPageBreak", show:function() { return '
'+this.userhelp+'
'; } } ); $.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; if('string' != typeof me.fields) return; var p = $.trim( me.fields.replace( /\,+/g, ',') ).split( ',' ), l = p.length; if( l ) { var str = '
'+( ( !/^\s*$/.test( me.title ) ) ? '

'+me.title+'

': '' )+'
'; for( var i = 0; i < l; i++ ) { if( !/^\s*$/.test( p[ i ] ) ) { p[ i ] = $.trim( p[ i ] ); str += '
'; } } str += '
'; return str; } }, after_show: function(){ var me = this; if('string' != typeof me.fields) return; var 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', '[id*="' + 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 + '"],[id^="' + i + '_rb"],[id^="' + i + '_cb"]'), tt = $( '[ref="' + i + '"]'); if( e.length && tt.length ) { var l = $( '[id="'+i+'"],[id^="'+i+'_rb"],[id^="'+i+'_cb"]' ) .closest( '.fields' ) .find( 'label:first' ) .clone() .find('.r,.dformat') .remove() .end(), t = $.trim(l.text()) .replace(/\:$/,''), 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 { var c = $( '[id="'+i+'_caption"]' ); v.push( ( c.length && !/^\s*$/.test( c.html() ) ) ? c.html() : e.val() ); } } } ); tt.find( '.cff-summary-title' )[(/^\s*$/.test(t)) ? 'hide' : 'show']().html(t); tt.find( '.cff-summary-value' ).html( v.join( ', ' ) ); if( e.hasClass( 'ignore' ) ) { tt.hide(); } else { tt.show(); } } } } }); $.fbuilder.controls[ 'datasource' ] = function(){}; $.fbuilder.controls[ 'datasource' ].prototype = { isDataSource:true, active : '', list : { 'database' : { cffaction : 'get_data_from_database' }, 'posttype' : { cffaction : 'get_posts' }, 'taxonomy' : { cffaction : 'get_taxonomies' }, 'user' : { cffaction : 'get_users' }, 'recordset' : { recordsetData: { recordset : '', value : '', text : '', where : '' }, getData : function( callback, parentObj ) { var obj = { data : [] }, d = this.recordsetData, fi = parentObj[ 'form_identifier' ], rs = $.trim(d.recordset), r, // For records w = $.trim( d.where ), t = $.trim( d.text ), v = $.trim( d.value ), tmp; if( rs != '' ) { r = $.fbuilder[ 'forms' ][ fi ].getItem( rs+fi ).val(); if( w != '' ) w = parentObj.parseVars(w); parentObj.replaceVariables( [rs], {} ) for( var i in r ) { if( w == '' || (function(o,w){ w = w.replace(/\brecord\s*\[/gi, 'o['); return eval(w); })(r[i],w)) { tmp = {}; if(t != '' && typeof r[i][t] != 'undefined' ) tmp['text' ] = r[i][t]; if(v != '' && typeof r[i][v] != 'undefined' ) tmp['value'] = r[i][v]; obj.data.push( tmp ); } } callback( obj ); } } }, 'csv' : { cffaction : 'get_csv_rows', csvData : { text : 0, value : 0, fields : [], rows : [], where : '' }, getData : function( callback, parentObj ) { var isRS= parentObj.ftype == 'frecordsetds',// is recordset obj = { data : [] }, d = this.csvData, w = $.trim( d.where ), v, t, r; if( w != '' ) w = parentObj.parseVars(w); for( var i in d.rows ) { v = d.value; t = ( typeof d.text == 'object' ) ? d.text : [d.text]; if( !$.isArray( d.rows[ i ] ) ) { for( var j = 0, h = t.length; j < h; j++ ) t[ j ] = d.fields[j]; v = d.fields[ v ]; } if( w == '' || w == d.rows[ i ][ v ] ) { r = {}; if( !isRS ) r['value'] = d.rows[i][v]; for( var j = 0, h = t.length; j < h; j++ ) r[ (isRS) ? t[j] : 'text' ] = d.rows[i][t[j]]; obj.data.push( r ); } } callback( obj ); } } }, getData : function( callback ) { var me = this, obj = me.list[ me.active ]; if( me.active == 'csv' && typeof obj.csvData[ 'rows' ] != 'undefined' && obj.csvData[ 'rows' ].length ) { if( typeof obj[ 'getData' ] != 'undefined' ) obj.getData( callback, me ); if( $( '[id*="'+me.name+'"]' ).closest( '.pbreak:hidden' ).length ) $( '[id*="'+me.name+'"]' ).addClass( 'ignorepb' ); } else if( me.active == 'recordset') { obj.getData(callback, me); } else { var url = document.location.href, data = { cffaction : obj.cffaction, form : obj.form, field : me.name.replace( me.form_identifier, '' ), vars : {} }, _form = $('[id*="'+me.name+'"]').closest('form'), _page; if(_form.length) { _page = _form.find('[name="cp_ref_page"]'); url = (_page.length) ? _page.val() : url; } if( typeof obj.vars != 'undefined' ) { if ( !me.replaceVariables( obj.vars, data[ 'vars' ] ) ) return; } if( typeof me.ajaxConnect != 'undefined' ) me.ajaxConnect.abort(); me.ajaxConnect = $.ajax( { dataType : 'json', url : url, cache : false, data : data, success : (function( me ){ return function( data ){ if( $( '[id*="'+me.name+'"]' ).closest( '.pbreak:hidden' ).length ) { $( '[id*="'+me.name+'"]' ).addClass( 'ignorepb' ); } callback( data ); }; })(me) } ); } }, parseVars : function( p ) { var o = {}, v; p = p.replace( /^\s*/, '' ).replace( /\s*$/, '' ); if( p != '' ) { if( ( v = p.match( /<\s{0}%[^%]*%\s{0}>/g ) ) != null ) { v = v.map(function(x){return x.replace(/(<\s{0}%|%\s{0}>)/g, '');}); this.replaceVariables( v, o ); for( var i in v ) { var index = encodeURI( v[ i ] ); if( typeof o[ index ] != 'undefined' ) { p = p.replace( new RegExp('<\s{0}%'+v[ i ].replace(/[\-\[\]\{\}\(\)\*\+\?\.\,\\\^\$\|\#\s]/g, "\\$&")+'%\s{0}>', 'g'), o[ index ] ); } } } } return p; }, replaceVariables : function( vars, _rtn ) { var me = this, field, formId = form_identifier = me.form_identifier, id, isValid = true, val = ''; // Prevents duplicate handles if(!('ds_filtering_fields' in me)) me.ds_filtering_fields = {}; for( var i = 0, h = vars.length; i < h; i++ ) { id = vars[ i ]+formId; field = $.fbuilder[ 'forms' ][ formId ].getItem( id ); // It is a field in the form if( typeof field != 'undefined' && field != false ) { val = field.val(); if( $( '[id*="'+id+'"]' ).val() == '' ) isValid = false; if( !(id in me.ds_filtering_fields)) { me.ds_filtering_fields[id] = 1; $( document ).on( 'change', '[id="'+id+'"],[id^="'+id+'_cb"],[id^="'+id+'_rb"]', function(){ me.after_show(); } ); } } else // It is a javascript variable { try{ if( typeof window[ vars[ i ] ] != 'undefined' ) val = window[ vars[ i ] ]; else val = eval( vars[ i ] ); }catch( err ){ val = ''; } } _rtn[ encodeURI( vars[ i ] ) ] = (val+'').replace( /^['"]+/, '' ).replace( /['"]+$/, ''); } return isValid; }, setDefault : function() // Used by the DS fields: DropDown, Checkbox, and Radio Buttons { var d = this.defaultSelection, l,e,t,n = this.name; if($.isArray(d)) { for(var i in d) d[i] = this.parseVars($.trim(d[i])); } else { d = this.parseVars($.trim(d)); } if( !/^\s*$/.test(d.toString())) { l = ($.isArray(d)) ? d : $.fbuilder.htmlEncode(d).split('|'); for(var i in l) { t = $.trim(l[i]); if(!/^\s*$/.test(t)) { e = $('[name*="'+n+'"][value="'+t+'"],[name*="'+n+'"][vt="'+t+'"]'); if( e.length ) e.prop('checked', true); else { e = $('[name*="'+n+'"]').find( 'option[value="'+t+'"],option[vt="'+t+'"]'); if(e.length) e.prop( 'selected', true ); } } } } } }; $.fbuilder.controls[ 'frecordsetds' ]=function(){}; $.extend( $.fbuilder.controls[ 'frecordsetds' ].prototype, $.fbuilder.controls[ 'ffields' ].prototype, $.fbuilder.controls[ 'datasource' ].prototype, { ftype:"frecordsetds", records : [], show:function(){ return ''; }, 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 { me.records = []; if( data.data.length ) { me.records = data.data.slice(0); } } $( '#' + me.name ).trigger( 'change' ); } ); }, val: function(){ var e = $( '[id="' + this.name + '"]:not(.ignore)' ); if( e.length ) { return this.records; } return []; } }); $.fbuilder.controls[ 'ftextds' ]=function(){}; $.extend( $.fbuilder.controls[ 'ftextds' ].prototype, $.fbuilder.controls[ 'ftext' ].prototype, $.fbuilder.controls[ 'datasource' ].prototype, { ftype:"ftextds", first_time: true, 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 ) { var v = ''; if( typeof data['error'] != 'undefined' ) { alert( data.error ); } else { if( data.data.length ) { v = data.data[ 0 ][ 'value' ]; } } if( me.first_time ) { me.first_time = false; if( typeof me.defaultSelection != 'undefined') v = me.defaultSelection; } $( '#' + me.name ).val( v ).change(); } ); }, setVal : function( v ) { this.defaultSelection = v; $.fbuilder.controls[ 'ftext' ].prototype.setVal.call( this, v ); } }); $.fbuilder.controls[ 'femailds' ]=function(){}; $.extend( $.fbuilder.controls[ 'femailds' ].prototype, $.fbuilder.controls[ 'femail' ].prototype, $.fbuilder.controls[ 'datasource' ].prototype, { ftype:"femailds", first_time:true, 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 ) { var v = ''; if( typeof data['error'] != 'undefined' ) { alert( data.error ); } else { if( data.data.length ) { v = data.data[ 0 ][ 'value' ]; } } if( me.first_time ) { me.first_time = false; if( typeof me.defaultSelection != 'undefined') v = me.defaultSelection; } $( '#' + me.name ).val( v ).change(); } ); }, setVal : function( v ) { this.defaultSelection = v; $.fbuilder.controls[ 'femail' ].prototype.setVal.call( this, v ); } }); $.fbuilder.controls[ 'ftextareads' ]=function(){}; $.extend( $.fbuilder.controls[ 'ftextareads' ].prototype, $.fbuilder.controls[ 'ftextarea' ].prototype, $.fbuilder.controls[ 'datasource' ].prototype, { ftype:"ftextareads", first_time:true, 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 ) { var v = ''; if( typeof data['error'] != 'undefined' ) { alert( data.error ); } else { if( data.data.length ) { v = data.data[ 0 ][ 'value' ]; } } if( me.first_time ) { me.first_time = false; if( typeof me.defaultSelection != 'undefined') v = me.defaultSelection; } $( '#' + me.name ).val( v ).change(); } ); }, setVal : function( v ) { this.defaultSelection = v; $.fbuilder.controls[ 'ftextarea' ].prototype.setVal.call( this, v ); } }); $.fbuilder.controls[ 'fcheckds' ] = function(){}; $.extend( $.fbuilder.controls[ 'fcheckds' ].prototype, $.fbuilder.controls[ 'fcheck' ].prototype, $.fbuilder.controls[ 'datasource' ].prototype, { ftype:"fcheckds", defaultSelection:"", first_time:true, show:function() { return '
'+this.userhelp+'
'; }, after_show : function() { var me = this, ignorepb = ($('[id="field'+me.form_identifier+'-'+me.index+'"]').closest('.pbreak').is(':visible')) ? '' : ' ignorepb '; $.fbuilder.controls[ 'fcheck' ].prototype.after_show.call(this); $.fbuilder.controls[ 'datasource' ].prototype.getData.call( this, function( data ) { var str = ''; if( typeof data['error'] != 'undefined' ) { alert( data.error ); } else { var used = [], i = 0; while(data.data.length) { var e = data.data.shift(), s = JSON.stringify(e); if($.inArray(s,used) == -1) { str += '
'; used.push(s); i++; } } } $( '#field' + me.form_identifier + '-' + me.index + ' .dfield' ).html( str ); if( str.length && me.first_time ) { me.first_time = false; $.fbuilder.controls[ 'datasource' ].prototype.setDefault.call( me ); } $( '[id*="' + me.name+'"]' ).change(); } ); }, setVal : function( v ) { this.defaultSelection = v; $.fbuilder.controls[ 'fcheck' ].prototype.setVal.call( this, v ); } }); $.fbuilder.controls[ 'fradiods' ]=function(){}; $.extend( $.fbuilder.controls[ 'fradiods' ].prototype, $.fbuilder.controls[ 'fradio' ].prototype, $.fbuilder.controls[ 'datasource' ].prototype, { ftype:"fradiods", defaultSelection:"", first_time:true, show:function() { return '
'+this.userhelp+'
'; }, after_show : function() { var me = this, ignorepb = ($('[id="field'+me.form_identifier+'-'+me.index+'"]').closest('.pbreak').is(':visible')) ? '' : ' ignorepb '; $.fbuilder.controls[ 'fradio' ].prototype.after_show.call(this); $.fbuilder.controls[ 'datasource' ].prototype.getData.call( this, function( data ) { var str = ''; if( typeof data['error'] != 'undefined' ) { alert( data.error ); } else { var used = [], i = 0; while(data.data.length) { var e = data.data.shift(), s = JSON.stringify(e); if($.inArray(s,used) == -1) { str += '
'; i++; used.push(s); } } } $( '#field' + me.form_identifier + '-' + me.index + ' .dfield' ).html( str ); if( str.length && me.first_time ) { me.first_time = false; $.fbuilder.controls[ 'datasource' ].prototype.setDefault.call( me ); } $( '[id*="' + me.name +'"]').change(); } ); }, setVal : function( v ) { this.defaultSelection = v; $.fbuilder.controls[ 'fradio' ].prototype.setVal.call( this, v ); } } ); $.fbuilder.controls[ 'fPhoneds' ]=function(){}; $.extend( $.fbuilder.controls[ 'fPhoneds' ].prototype, $.fbuilder.controls[ 'fPhone' ].prototype, $.fbuilder.controls[ 'datasource' ].prototype, { ftype:"fPhoneds", first_time:true, 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 ) { var p = $.trim( me.dformat.replace(/[^\s#]/g, '' ).replace( /\s+/g, ' ' ) ).split( ' ' ), h = p.length, e = [], v = '', r = '', vArr; if( typeof data['error'] != 'undefined' ) { alert( data.error ); } else { if( data.data.length ) v = data.data[ 0 ].value; } if( me.first_time ) { me.first_time = false; if( typeof me.defaultSelection != 'undefined') v = me.defaultSelection; } v = v.replace( /\s+/, '' ); for( var i = 0; i' + t + ''; used.push(s); } } } e.html( str ); if( str.length && me.first_time ) { me.first_time = false; $.fbuilder.controls[ 'datasource' ].prototype.setDefault.call( me ); } e.change(); } ); }, setVal : function( v ) { this.defaultSelection = v; $.fbuilder.controls[ 'fdropdown' ].prototype.setVal.call( this, v ); } }); $.fbuilder.controls[ 'fhiddends' ]=function(){}; $.extend( $.fbuilder.controls[ 'fhiddends' ].prototype, $.fbuilder.controls[ 'fhidden' ].prototype, $.fbuilder.controls[ 'datasource' ].prototype, { ftype:"fhiddends", first_time:true, 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 ) { var v = ''; if( typeof data['error'] != 'undefined' ) { alert( data.error ); } else { if( data.data.length ) { v = data.data[ 0 ][ 'value' ]; } } if( me.first_time ) { me.first_time = false; if( typeof me.defaultSelection != 'undefined') v = me.defaultSelection; } $( '#' + me.name ).val( v ).change(); } ); }, setVal : function( v ) { this.defaultSelection = v; $.fbuilder.controls[ 'fhidden' ].prototype.setVal.call( this, v ); } } ); $.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 = $( '[id*="'+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, hiddenByContainer ) { var me = this, isHidden = ( typeof toHide[ me.name ] != 'undefined' || typeof hiddenByContainer[ me.name ] != 'undefined' ), fId, result = []; for( var i = 0, h = me.fields.length; i < h; i++ ) { fId = me.fields[ i ]+me.form_identifier; if( isHidden ) { if( typeof hiddenByContainer[ fId ] == 'undefined' ) hiddenByContainer[ fId ] = {}; if( typeof hiddenByContainer[ fId ][ me.name ] == 'undefined' ) { hiddenByContainer[ fId ][ me.name ] = {}; if( typeof toHide[ fId ] == 'undefined' ) { $( '[id*="'+fId+'"],.'+fId ).closest( '.fields' ).hide(); $( '[id*="'+fId+'"]:not(.ignore)' ).addClass( 'ignore' ); result.push( fId ); } } } else { if( typeof hiddenByContainer[ fId ] != 'undefined' ) { delete hiddenByContainer[ fId ][ me.name ]; if( $.isEmptyObject( hiddenByContainer[ fId ] ) ) { delete hiddenByContainer[ fId ]; if( typeof toHide[ fId ] == 'undefined' ) { $( '[id*="'+fId+'"],.'+fId ).closest( '.fields' ).show(); $( '[id*="'+fId+'"].ignore' ).removeClass( 'ignore' ); result.push( fId ); } } } } } return result; } }; $.fbuilder.controls[ 'ffieldset' ]=function(){}; $.extend( $.fbuilder.controls[ 'ffieldset' ].prototype, $.fbuilder.controls[ 'ffields' ].prototype, { title:"Untitled", ftype:"ffieldset", fields:[], columns:1, show:function() { return '
'+( ( !/^\s*$/.test( this.title ) ) ? ''+this.title+'' : '' )+'
'; }, after_show: function() { $.fbuilder.controls[ 'fcontainer' ].prototype.after_show.call(this); }, showHideDep:function( toShow, toHide, hiddenByContainer ) { return $.fbuilder.controls[ 'fcontainer' ].prototype.showHideDep.call( this, toShow, toHide, hiddenByContainer ); } } ); $.fbuilder.controls[ 'fdiv' ]=function(){}; $.extend( $.fbuilder.controls[ 'fdiv' ].prototype, $.fbuilder.controls[ 'ffields' ].prototype, { ftype:"fdiv", fields:[], columns:1, show:function() { return '
'; }, after_show: function() { $.fbuilder.controls[ 'fcontainer' ].prototype.after_show.call(this); }, showHideDep:function( toShow, toHide, hiddenByContainer ) { return $.fbuilder.controls[ 'fcontainer' ].prototype.showHideDep.call( this, toShow, toHide, hiddenByContainer ); } } ); $.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 = ''; } else { r = ''; } 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 ) ) ? '' : '' )+'

'+d.sFallback+'

'; }, _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 '
'+this[ '_show_'+this.sMediaType]()+'
'+this.data[ this.sMediaType].sFigcaption+'
'; } } ); $.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( /</g, '&').replace(/"/g, """).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 '
'+this.userhelp+'
'; }, 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", first_time:true, 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.first_time ) { me.first_time = false; if( typeof me.defaultSelection != 'undefined') v = me.defaultSelection; } $( '#' + me.name ).val( v ).change(); } ); }, setVal : function( v ) { this.defaultSelection = v; $.fbuilder.controls[ 'fnumber' ].prototype.setVal.call( this, v ); } }); $.fbuilder.controls[ 'fhtml' ]=function(){}; $.extend( $.fbuilder.controls[ 'fhtml' ].prototype, $.fbuilder.controls[ 'ffields' ].prototype, { ftype:"fhtml", fcontent:"", show:function() { return '
'+$( '
' ).html( this.fcontent ).html()+'
'; } } ); $.fbuilder.controls[ 'fcurrencyds' ]=function(){}; $.extend( $.fbuilder.controls[ 'fcurrencyds' ].prototype, $.fbuilder.controls[ 'fcurrency' ].prototype, $.fbuilder.controls[ 'datasource' ].prototype, { ftype:"fcurrencyds", first_time:true, 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' ]; } } if( me.first_time ) { me.first_time = false; if( typeof me.defaultSelection != 'undefined') v = me.defaultSelection; } $( '#' + me.name ).val( v ).change(); } ); }, setVal : function( v ) { this.defaultSelection = v; $.fbuilder.controls[ 'fcurrency' ].prototype.setVal.call( this, v ); } }); $.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 = ''+label+''; } else if(!/^\s*$/.test(me.message)) { label = ''+label+''; dlg += '
'+me.message+'
' } return '
'+ '
'+ dlg+ '
'; }, 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 = MIN($(this).closest('form').width(), $(window).width(), dlg.width()); if('undefined' == typeof h) h = 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(raw) { raw = raw || false; var e = $('[id="'+this.name+'"]:checked:not(.ignore)'); if( e.length ) { var t = $.fbuilder.parseValStr( e[0].value, raw ); if(!$.isNumeric(t)) t = t.replace(/^"/,'').replace(/"$/,''); } return (t) ? (($.isNumeric(t)) ? t : '"'+t+'"') : 0; } } ); $.fbuilder.controls[ 'fCalculated' ] = function(){}; $.extend( $.fbuilder.controls[ 'fCalculated' ].prototype, $.fbuilder.controls[ 'ffields' ].prototype, { title:"Untitled", ftype:"fCalculated", predefined:"", required:false, size:"medium", eq:"", suffix:"", prefix:"", decimalsymbol:".", groupingsymbol:"", dependencies:[ {'rule' : '', 'complex' : false, 'fields' : [ '' ] } ], readonly:true, hidefield:false, show:function() { return '
'+( ( !this.hidefield ) ? ''+this.userhelp+'' : '' )+'
'; }, after_show:function() { // Add equations var me = this, configuration = { "suffix" : me.suffix, "prefix" : me.prefix, "groupingsymbol" : me.groupingsymbol, "decimalsymbol" : me.decimalsymbol }, dependencies = []; $.each( me.dependencies, function( i, d ) { d.rule = d.rule.replace( /^\s+/, '').replace( /\s+$/, ''); if( d.rule != '' && d.fields.length ){ var fields = []; $.each( d.fields, function( j, f ){ if( f != '' ) { fields.push( f ); } }); if( fields.length ){ dependencies.push( { 'rule' : d.rule, 'fields' : fields } ); } } }); me.dependencies = dependencies; var eq = me.eq; eq = eq.replace(/\n/g, ' ').replace(/fieldname(\d+)/g, "fieldname$1"+me.form_identifier).replace( /form_identifier/g, '\''+this[ 'form_identifier' ]+'\'').replace( /;\s*\)/g, ')').replace(/;\s*$/, ''); if( !/^\s*$/.test(eq) ) { $.fbuilder.calculator.addEquation( me.name, eq, configuration, dependencies, me.form_identifier ); } // Events var e = $( '[id="'+me.name+'"]' ); e.bind( 'calcualtedfield_changed', {obj: me}, function( evt ){ if( $.fbuilder[ 'calculator' ].getDepList( evt.data.obj.name, evt.data.obj.val(), evt.data.obj.dependencies ) ) { $.fbuilder.showHideDep( { 'formIdentifier' : evt.data.obj.form_identifier, 'fieldIdentifier': evt.data.obj.name, 'throwEvent' : false } ); } } ); }, showHideDep: function( toShow, toHide, hiddenByContainer ) { var me = this, result = []; if($.fbuilder[ 'calculator' ].getDepList(me.name, me.val(), me.dependencies)) { var item = $( '#'+me.name ), identifier = me.form_identifier, isHidden= ( typeof toHide[ me.name ] != 'undefined' || typeof hiddenByContainer[ me.name ] != 'undefined' ), d, n, dep, clearRef = function(id){ if( typeof toShow[ id ] != 'undefined' ) { delete toShow[ id ][ 'ref' ][ me.name ]; if( $.isEmptyObject(toShow[ id ][ 'ref' ]) ) delete toShow[ id ]; } }, hideField = function(id){ $( '[id*="'+id+'"],.'+id ).closest( '.fields' ).hide(); $( '[id*="'+id+'"]:not(.ignore)' ).addClass( 'ignore' ); toHide[ id ] = {}; }; try { d = item.attr( 'dep' ); if( typeof d != 'undefined' && !/^\s*$/.test( d ) ) d = d.split( ',' ); else d = []; n = item.attr( 'notdep' ); if( typeof n != 'undefined' && !/^\s*$/.test( n ) ) n = n.split( ',' ); else n = []; if(isHidden) { n = n.concat(d); d = []; } for ( i=0; i= 0; i--){ counter++; str = parts[0][i] + str; if( counter%3 == 0 && i != 0 ) str = config.groupingsymbol + str; } parts[0] = str; } value = symbol+parts.join( config.decimalsymbol ); } if( config.prefix ) { value = config.prefix + value; } if( config.suffix ) { value += config.suffix; } } return value; }, unformat : function( field ) { var escape_symbol = $.fbuilder.escape_symbol; var eq = field[0].form.equations, v = field.val(); for(var i = 0, h = eq.length; i < h; i++) { if(eq[i].result == field[0].id) { var c = eq[i].conf; // Configuration object if( c.prefix && !/^\s*$/.test( c.prefix ) ) { v = v.replace( new RegExp( "^" + escape_symbol( c.prefix ) ), '' ); } if( c.suffix && !/^\s*$/.test( c.suffix ) ) { v = v.replace( new RegExp( escape_symbol( c.suffix ) + "$" ), '' ); } if( !/[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)/.test( v ) ) { if( c.groupingsymbol && !/^\s*$/.test( c.groupingsymbol ) ) { v = v.replace( new RegExp( escape_symbol( c.groupingsymbol ), 'g' ), '' ); } if( c.decimalsymbol && !/^\s*$/.test( c.decimalsymbol ) ) { v = v.replace( new RegExp( escape_symbol( c.decimalsymbol ), 'g' ), '.' ); } } } } return v; } }; var obj = new CalcFieldClss(); // Associate events to the document for throw the corresponding equations $( document ).bind('keyup change blur', function(evt) { // If evalequations = 0 the equations shouldn't be evaluated dynamically var t = $( evt.target ), f = t.closest( 'form' ), evalequations = f.attr( 'data-evalequations' ), evalequationsevent = f.attr( 'data-evalequationsevent' ); if( typeof evalequations != 'undefined' && evalequations*1 == 0 && !( t.hasClass( 'codepeoplecalculatedfield' ) && evt.type == 'change' ) ) { return; } if( evt.type == 'keyup' ) { if('undefined' != typeof evalequationsevent && evalequationsevent*1 == 1) { return; } // The key out of range if(evt.keyCode && (evt.keyCode >= 33 && evt.keyCode <= 40)) return; _checkValueThrowingEquation( t ); } else { if( t.hasClass( 'depItem' ) || ( t.prop( 'tagName' ) == 'INPUT' && t.attr( 'type' ).toLowerCase() == 'text' && evt.type != 'change' ) ) { return; } obj.Calculate( t[0] ); } }); //Associate an event to the document waiting for the showHideDepEvent and recalculate all equations $(document).bind( 'showHideDepEvent', function( evt, form_identifier ) { // If evalequations = 0 the equations shouldn't be evaluated dynamically var fId = '#'+form_identifier, evalequations = $( fId ).attr( 'data-evalequations' ); if( typeof evalequations == 'undefined' || evalequations*1 == 1 ) obj.defaultCalc( fId ); }); return obj; // Return the public object } )();try{ !function(a){function f(a,b){if(!(a.originalEvent.touches.length>1)){a.preventDefault();var c=a.originalEvent.changedTouches[0],d=document.createEvent("MouseEvents");d.initMouseEvent(b,!0,!0,window,1,c.screenX,c.screenY,c.clientX,c.clientY,!1,!1,!1,!1,0,null),a.target.dispatchEvent(d)}}if(a.support.touch="ontouchend"in document,a.support.touch){var e,b=a.ui.mouse.prototype,c=b._mouseInit,d=b._mouseDestroy;b._touchStart=function(a){var b=this;!e&&b._mouseCapture(a.originalEvent.changedTouches[0])&&(e=!0,b._touchMoved=!1,f(a,"mouseover"),f(a,"mousemove"),f(a,"mousedown"))},b._touchMove=function(a){e&&(this._touchMoved=!0,f(a,"mousemove"))},b._touchEnd=function(a){e&&(f(a,"mouseup"),f(a,"mouseout"),this._touchMoved||f(a,"click"),e=!1)},b._mouseInit=function(){var b=this;b.element.bind({touchstart:a.proxy(b,"_touchStart"),touchmove:a.proxy(b,"_touchMove"),touchend:a.proxy(b,"_touchEnd")}),c.call(b)},b._mouseDestroy=function(){var b=this;b.element.unbind({touchstart:a.proxy(b,"_touchStart"),touchmove:a.proxy(b,"_touchMove"),touchend:a.proxy(b,"_touchEnd")}),d.call(b)}}}(jQuery); }catch( err ){}if(typeof $.fn['fbuilder_serializeObject'] == 'undefined') { $.fn.fbuilder_serializeObject = function() { var o = {}, a = this.serializeArray(); $.each(a, function() { if(/^fieldname\d+_\d+(\[\])?$/.test(this.name)) this.name = this.name.match(/fieldname\d+/)[0]; else return; if (o[this.name]) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; }; } $.fn.fbuilder_localstorage = function(){ var form = this, id = form.attr('id'), sq = (typeof id == 'undefined') ? 1 : id.replace(/[^\d]/g,''), localStore_obj, fields; if(sq == '') sq = 1; localStore_obj = new $.fbuilder_localstorage(form, true); $(document).on('change', '#'+id+' *', function(evt){ if( typeof this['id'] != 'undefined' && /^fieldname\d+_\d+$/i.test(this.id) && typeof this['value'] != 'undefined' ) { localStore_obj.set_fields(); } }); form.on('submit', function(){localStore_obj.clear_fields();}); fields = localStore_obj.get_fields(); if(!$.isEmptyObject(fields)) { if(typeof cpcff_default == 'undefined') cpcff_default = {}; if(typeof cpcff_default[sq] == 'undefined') cpcff_default[sq] = {}; cpcff_default[sq] = $.extend(cpcff_default[sq], fields); } return this; } $.fbuilder_localstorage = function(form, debug){ this.form = form; this.id = form.attr('id')+'_'+form.find('[name="cp_calculatedfieldsf_id"]').val(); this.debug = (typeof debug != 'undefined' && debug) ? true : false; }; $.fbuilder_localstorage.prototype = (function(){ /** Private variables **/ var is_available; /** Private functions **/ function _log(mssg) { if(typeof console != 'undefined') console.log(mssg); }; return { is_available : function() { if(typeof is_available != 'undefined') return is_available; try { var storage = window['localStorage'], x = '__storage_test__'; storage.setItem(x, x); storage.removeItem(x); is_available = true; return true; } catch(e) { if(this.debug) _log( 'localStorage object is not available' ); is_available = false; return e instanceof DOMException && ( e.code === 22 || e.code === 1014 || e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') && storage.length !== 0; } }, get_fields : function(){ try{ if(typeof this.fields == 'undefined') this.fields = JSON.parse(localStorage.getItem(this.id)); return this.fields; } catch(err) { _log( 'Error reading the fields.' ); _log( err ); } }, set_fields : function(){ try{ this.fields = this.form.fbuilder_serializeObject(); localStorage.setItem(this.id, JSON.stringify(this.fields)); } catch(err) { _log( 'Error saving the fields.' ); _log( err ); } }, clear_fields : function(){ try{ localStorage.removeItem(this.id); } catch(err) { _log( 'Error deleting the fields.' ); _log( err ); } } }; })(); var fcount = 1; var fnum = "_"+fcount; while(typeof window["cp_calculatedfieldsf_fbuilder_config"+fnum] != 'undefined' || fcount < 10 ) { try { var cp_calculatedfieldsf_fbuilder_config = window["cp_calculatedfieldsf_fbuilder_config"+fnum]; var f = $("#fbuilder"+fnum).fbuilder(( typeof cp_calculatedfieldsf_fbuilder_config.obj == 'string' ) ? $.parseJSON(cp_calculatedfieldsf_fbuilder_config.obj) : cp_calculatedfieldsf_fbuilder_config.obj ); $("#cp_calculatedfieldsf_pform"+fnum).validate({ ignore:".ignore,.ignorepb", errorElement: "div", errorPlacement: function(e, element) { var _parent = element.closest( '.dfield' ), _uh = _parent.find( 'span.uh:visible' ); if( _uh.length ) e.appendTo( _uh ); else e.insertAfter( _parent ); e.addClass( 'message' ) .css( 'position', 'absolute' ); } }); f.fBuild.loadData("form_structure"+fnum); } catch (e) {} fcount++; fnum = "_"+fcount; } })(fbuilderjQuery); fbuilderjQuery.fbuilderGeneratorFlag = 1; }; fbuilderjQuery(fbuilderjQuery.fbuilderjQueryGenerator); fbuilderjQuery(window).on('load',fbuilderjQuery.fbuilderjQueryGenerator);