").html(l).appendTo(this.liveRegion),this.options.track&&t&&/^mouse/.test(t.type)?(this._on(this.document,{mousemove:n}),n(t)):o.position(e.extend({of:i},this.options.position)),o.hide(),this._show(o,this.options.show),this.options.show&&this.options.show.delay&&(h=this.delayedShow=setInterval(function(){o.is(":visible")&&(n(u.of),clearInterval(h))},e.fx.interval)),this._trigger("open",t,{tooltip:o}),r={keyup:function(t){if(t.keyCode===e.ui.keyCode.ESCAPE){var s=e.Event(t);s.currentTarget=i[0],this.close(s,!0)}}},i[0]!==this.element[0]&&(r.remove=function(){this._removeTooltip(o)}),t&&"mouseover"!==t.type||(r.mouseleave="close"),t&&"focusin"!==t.type||(r.focusout="close"),this._on(!0,i,r)}},close:function(t){var i,s=this,n=e(t?t.currentTarget:this.element),a=this._find(n);a&&(i=a.tooltip,a.closing||(clearInterval(this.delayedShow),n.data("ui-tooltip-title")&&!n.attr("title")&&n.attr("title",n.data("ui-tooltip-title")),this._removeDescribedBy(n),a.hiding=!0,i.stop(!0),this._hide(i,this.options.hide,function(){s._removeTooltip(e(this))}),n.removeData("ui-tooltip-open"),this._off(n,"mouseleave focusout keyup"),n[0]!==this.element[0]&&this._off(n,"remove"),this._off(this.document,"mousemove"),t&&"mouseleave"===t.type&&e.each(this.parents,function(t,i){e(i.element).attr("title",i.title),delete s.parents[t]}),a.closing=!0,this._trigger("close",t,{tooltip:i}),a.hiding||(a.closing=!1)))},_tooltip:function(t){var i=e("
").attr("role","tooltip").addClass("ui-tooltip ui-widget ui-corner-all ui-widget-content "+(this.options.tooltipClass||"")),s=i.uniqueId().attr("id");return e("
").addClass("ui-tooltip-content").appendTo(i),i.appendTo(this.document[0].body),this.tooltips[s]={element:t,tooltip:i}},_find:function(e){var t=e.data("ui-tooltip-id");return t?this.tooltips[t]:null},_removeTooltip:function(e){e.remove(),delete this.tooltips[e.attr("id")]},_destroy:function(){var t=this;e.each(this.tooltips,function(i,s){var n=e.Event("blur"),a=s.element;n.target=n.currentTarget=a[0],t.close(n,!0),e("#"+i).remove(),a.data("ui-tooltip-title")&&(a.attr("title")||a.attr("title",a.data("ui-tooltip-title")),a.removeData("ui-tooltip-title"))}),this.liveRegion.remove()}})});
/* Minification failed. Returning unminified contents.
(1862,5-6): run-time warning JS1004: Expected ';': u
(1863,5-6): run-time warning JS1004: Expected ';': g
(1868,9-10): run-time warning JS1004: Expected ';': u
(1869,9-10): run-time warning JS1004: Expected ';': a
(1873,9-10): run-time warning JS1004: Expected ';': l
(1875,9-10): run-time warning JS1004: Expected ';': r
(1876,9-10): run-time warning JS1004: Expected ';': u
(1891,5-6): run-time warning JS1195: Expected expression: )
(1891,8-9): run-time warning JS1195: Expected expression: >
(1891,46-47): run-time warning JS1002: Syntax error: }
(1893,91-92): run-time warning JS1004: Expected ';': :
(1898,75-76): run-time warning JS1004: Expected ';': {
(1905,2-3): run-time warning JS1195: Expected expression: ,
(1907,64-65): run-time warning JS1002: Syntax error: }
(1913,73-74): run-time warning JS1004: Expected ';': {
(1919,2-3): run-time warning JS1195: Expected expression: ,
(1921,7-8): run-time warning JS1197: Too many errors. The file might not be a JScript .NET file: .
(1891,12-45): run-time warning JS1018: 'return' statement outside of function: return getUserNameErrorMessage();
(1899,5,1904,28): run-time warning JS1018: 'return' statement outside of function: return !value ||
value
.replaceOne($.constants.currencySymbol, "")
.replaceOne($.constants.numberDecimal, "")
.replaceAll($.constants.numberGroup, "")
.match(/^\d+$/g);
(1914,5,1918,28): run-time warning JS1018: 'return' statement outside of function: return !value ||
value
.replaceOne($.constants.numberDecimal, "")
.replaceAll($.constants.numberGroup, "")
.match(/^\d+$/g);
*/
/*!
* jQuery UI Touch Punch 0.2.3
*
* Copyright 2011–2014, Dave Furfero
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Depends:
* jquery.ui.widget.js
* jquery.ui.mouse.js
*/
(function ($) {
// Detect touch support
$.support.touch = 'ontouchend' in document;
// Ignore browsers without touch support
if (!$.support.touch) {
return;
}
var mouseProto = $.ui.mouse.prototype,
_mouseInit = mouseProto._mouseInit,
_mouseDestroy = mouseProto._mouseDestroy,
touchHandled;
/**
* Simulate a mouse event based on a corresponding touch event
* @param {Object} event A touch event
* @param {String} simulatedType The corresponding mouse event
*/
function simulateMouseEvent(event, simulatedType) {
// Ignore multi-touch events
if (event.originalEvent.touches.length > 1) {
return;
}
event.preventDefault();
var touch = event.originalEvent.changedTouches[0],
simulatedEvent = document.createEvent('MouseEvents');
// Initialize the simulated mouse event using the touch event's coordinates
simulatedEvent.initMouseEvent(
simulatedType, // type
true, // bubbles
true, // cancelable
window, // view
1, // detail
touch.screenX, // screenX
touch.screenY, // screenY
touch.clientX, // clientX
touch.clientY, // clientY
false, // ctrlKey
false, // altKey
false, // shiftKey
false, // metaKey
0, // button
null // relatedTarget
);
// Dispatch the simulated event to the target element
event.target.dispatchEvent(simulatedEvent);
}
/**
* Handle the jQuery UI widget's touchstart events
* @param {Object} event The widget element's touchstart event
*/
mouseProto._touchStart = function (event) {
var self = this;
// Ignore the event if another widget is already being handled
if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0])) {
return;
}
// Set the flag to prevent other widgets from inheriting the touch event
touchHandled = true;
// Track movement to determine if interaction was a click
self._touchMoved = false;
// Simulate the mouseover event
simulateMouseEvent(event, 'mouseover');
// Simulate the mousemove event
simulateMouseEvent(event, 'mousemove');
// Simulate the mousedown event
simulateMouseEvent(event, 'mousedown');
};
/**
* Handle the jQuery UI widget's touchmove events
* @param {Object} event The document's touchmove event
*/
mouseProto._touchMove = function (event) {
// Ignore event if not handled
if (!touchHandled) {
return;
}
// Interaction was not a click
this._touchMoved = true;
// Simulate the mousemove event
simulateMouseEvent(event, 'mousemove');
};
/**
* Handle the jQuery UI widget's touchend events
* @param {Object} event The document's touchend event
*/
mouseProto._touchEnd = function (event) {
// Ignore event if not handled
if (!touchHandled) {
return;
}
// Simulate the mouseup event
simulateMouseEvent(event, 'mouseup');
// Simulate the mouseout event
simulateMouseEvent(event, 'mouseout');
// If the touch interaction did not move, it should trigger a click
if (!this._touchMoved) {
// Simulate the click event
simulateMouseEvent(event, 'click');
}
// Unset the flag to allow other widgets to inherit the touch event
touchHandled = false;
};
/**
* A duck punch of the $.ui.mouse _mouseInit method to support touch events.
* This method extends the widget with bound touch event handlers that
* translate touch events to mouse events and pass them to the widget's
* original mouse event handling methods.
*/
mouseProto._mouseInit = function () {
var self = this;
// Delegate the touch handlers to the widget's element
self.element.bind({
touchstart: $.proxy(self, '_touchStart'),
touchmove: $.proxy(self, '_touchMove'),
touchend: $.proxy(self, '_touchEnd')
});
// Call the original $.ui.mouse init method
_mouseInit.call(self);
};
/**
* Remove the touch event handlers
*/
mouseProto._mouseDestroy = function () {
var self = this;
// Delegate the touch handlers to the widget's element
self.element.unbind({
touchstart: $.proxy(self, '_touchStart'),
touchmove: $.proxy(self, '_touchMove'),
touchend: $.proxy(self, '_touchEnd')
});
// Call the original $.ui.mouse destroy method
_mouseDestroy.call(self);
};
})(jQuery);
/*!
* jQuery Validation Plugin v1.13.0
*
* http://jqueryvalidation.org/
*
* Copyright (c) 2014 Jörn Zaefferer
* Released under the MIT license
*/
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
define( ["jquery"], factory );
} else {
factory( jQuery );
}
}(function( $ ) {
$.extend($.fn, {
// http://jqueryvalidation.org/validate/
validate: function( options ) {
// if nothing is selected, return nothing; can't chain anyway
if ( !this.length ) {
if ( options && options.debug && window.console ) {
console.warn( "Nothing selected, can't validate, returning nothing." );
}
return;
}
// check if a validator for this form was already created
var validator = $.data( this[ 0 ], "validator" );
if ( validator ) {
return validator;
}
// Add novalidate tag if HTML5.
this.attr( "novalidate", "novalidate" );
validator = new $.validator( options, this[ 0 ] );
$.data( this[ 0 ], "validator", validator );
if ( validator.settings.onsubmit ) {
this.validateDelegate( ":submit", "click", function( event ) {
if ( validator.settings.submitHandler ) {
validator.submitButton = event.target;
}
// allow suppressing validation by adding a cancel class to the submit button
if ( $( event.target ).hasClass( "cancel" ) ) {
validator.cancelSubmit = true;
}
// allow suppressing validation by adding the html5 formnovalidate attribute to the submit button
if ( $( event.target ).attr( "formnovalidate" ) !== undefined ) {
validator.cancelSubmit = true;
}
});
// validate the form on submit
this.submit( function( event ) {
if ( validator.settings.debug ) {
// prevent form submit to be able to see console output
event.preventDefault();
}
function handle() {
var hidden;
if ( validator.settings.submitHandler ) {
if ( validator.submitButton ) {
// insert a hidden input as a replacement for the missing submit button
hidden = $( "" )
.attr( "name", validator.submitButton.name )
.val( $( validator.submitButton ).val() )
.appendTo( validator.currentForm );
}
validator.settings.submitHandler.call( validator, validator.currentForm, event );
if ( validator.submitButton ) {
// and clean up afterwards; thanks to no-block-scope, hidden can be referenced
hidden.remove();
}
return false;
}
return true;
}
// prevent submit for invalid forms or custom submit handlers
if ( validator.cancelSubmit ) {
validator.cancelSubmit = false;
return handle();
}
if ( validator.form() ) {
if ( validator.pendingRequest ) {
validator.formSubmitted = true;
return false;
}
return handle();
} else {
validator.focusInvalid();
return false;
}
});
}
return validator;
},
// http://jqueryvalidation.org/valid/
valid: function() {
var valid, validator;
if ( $( this[ 0 ] ).is( "form" ) ) {
valid = this.validate().form();
} else {
valid = true;
validator = $( this[ 0 ].form ).validate();
this.each( function() {
valid = validator.element( this ) && valid;
});
}
return valid;
},
// attributes: space separated list of attributes to retrieve and remove
removeAttrs: function( attributes ) {
var result = {},
$element = this;
$.each( attributes.split( /\s/ ), function( index, value ) {
result[ value ] = $element.attr( value );
$element.removeAttr( value );
});
return result;
},
// http://jqueryvalidation.org/rules/
rules: function( command, argument ) {
var element = this[ 0 ],
settings, staticRules, existingRules, data, param, filtered;
if ( command ) {
settings = $.data( element.form, "validator" ).settings;
staticRules = settings.rules;
existingRules = $.validator.staticRules( element );
switch ( command ) {
case "add":
$.extend( existingRules, $.validator.normalizeRule( argument ) );
// remove messages from rules, but allow them to be set separately
delete existingRules.messages;
staticRules[ element.name ] = existingRules;
if ( argument.messages ) {
settings.messages[ element.name ] = $.extend( settings.messages[ element.name ], argument.messages );
}
break;
case "remove":
if ( !argument ) {
delete staticRules[ element.name ];
return existingRules;
}
filtered = {};
$.each( argument.split( /\s/ ), function( index, method ) {
filtered[ method ] = existingRules[ method ];
delete existingRules[ method ];
if ( method === "required" ) {
$( element ).removeAttr( "aria-required" );
}
});
return filtered;
}
}
data = $.validator.normalizeRules(
$.extend(
{},
$.validator.classRules( element ),
$.validator.attributeRules( element ),
$.validator.dataRules( element ),
$.validator.staticRules( element )
), element );
// make sure required is at front
if ( data.required ) {
param = data.required;
delete data.required;
data = $.extend( { required: param }, data );
$( element ).attr( "aria-required", "true" );
}
// make sure remote is at back
if ( data.remote ) {
param = data.remote;
delete data.remote;
data = $.extend( data, { remote: param });
}
return data;
}
});
// Custom selectors
$.extend( $.expr[ ":" ], {
// http://jqueryvalidation.org/blank-selector/
blank: function( a ) {
return !$.trim( "" + $( a ).val() );
},
// http://jqueryvalidation.org/filled-selector/
filled: function( a ) {
return !!$.trim( "" + $( a ).val() );
},
// http://jqueryvalidation.org/unchecked-selector/
unchecked: function( a ) {
return !$( a ).prop( "checked" );
}
});
// constructor for validator
$.validator = function( options, form ) {
this.settings = $.extend( true, {}, $.validator.defaults, options );
this.currentForm = form;
this.init();
};
// http://jqueryvalidation.org/jQuery.validator.format/
$.validator.format = function( source, params ) {
if ( arguments.length === 1 ) {
return function() {
var args = $.makeArray( arguments );
args.unshift( source );
return $.validator.format.apply( this, args );
};
}
if ( arguments.length > 2 && params.constructor !== Array ) {
params = $.makeArray( arguments ).slice( 1 );
}
if ( params.constructor !== Array ) {
params = [ params ];
}
$.each( params, function( i, n ) {
source = source.replace( new RegExp( "\\{" + i + "\\}", "g" ), function() {
return n;
});
});
return source;
};
$.extend( $.validator, {
defaults: {
messages: {},
groups: {},
rules: {},
errorClass: "error",
validClass: "valid",
errorElement: "label",
focusInvalid: true,
errorContainer: $( [] ),
errorLabelContainer: $( [] ),
onsubmit: true,
ignore: ":hidden",
ignoreTitle: false,
onfocusin: function( element ) {
this.lastActive = element;
// hide error label and remove error class on focus if enabled
if ( this.settings.focusCleanup && !this.blockFocusCleanup ) {
if ( this.settings.unhighlight ) {
this.settings.unhighlight.call( this, element, this.settings.errorClass, this.settings.validClass );
}
this.hideThese( this.errorsFor( element ) );
}
},
onfocusout: function( element ) {
if ( !this.checkable( element ) && ( element.name in this.submitted || !this.optional( element ) ) ) {
this.element( element );
}
},
onkeyup: function( element, event ) {
if ( event.which === 9 && this.elementValue( element ) === "" ) {
return;
} else if ( element.name in this.submitted || element === this.lastElement ) {
this.element( element );
}
},
onclick: function( element ) {
// click on selects, radiobuttons and checkboxes
if ( element.name in this.submitted ) {
this.element( element );
// or option elements, check parent select in that case
} else if ( element.parentNode.name in this.submitted ) {
this.element( element.parentNode );
}
},
highlight: function( element, errorClass, validClass ) {
if ( element.type === "radio" ) {
this.findByName( element.name ).addClass( errorClass ).removeClass( validClass );
} else {
$( element ).addClass( errorClass ).removeClass( validClass );
}
},
unhighlight: function( element, errorClass, validClass ) {
if ( element.type === "radio" ) {
this.findByName( element.name ).removeClass( errorClass ).addClass( validClass );
} else {
$( element ).removeClass( errorClass ).addClass( validClass );
}
}
},
// http://jqueryvalidation.org/jQuery.validator.setDefaults/
setDefaults: function( settings ) {
$.extend( $.validator.defaults, settings );
},
messages: {
required: "This field is required.",
remote: "Please fix this field.",
email: "Please enter a valid email address.",
url: "Please enter a valid URL.",
date: "Please enter a valid date.",
dateISO: "Please enter a valid date ( ISO ).",
number: "Please enter a valid number.",
digits: "Please enter only digits.",
creditcard: "Please enter a valid credit card number.",
equalTo: "Please enter the same value again.",
maxlength: $.validator.format( "Please enter no more than {0} characters." ),
minlength: $.validator.format( "Please enter at least {0} characters." ),
rangelength: $.validator.format( "Please enter a value between {0} and {1} characters long." ),
range: $.validator.format( "Please enter a value between {0} and {1}." ),
max: $.validator.format( "Please enter a value less than or equal to {0}." ),
min: $.validator.format( "Please enter a value greater than or equal to {0}." )
},
autoCreateRanges: false,
prototype: {
init: function() {
this.labelContainer = $( this.settings.errorLabelContainer );
this.errorContext = this.labelContainer.length && this.labelContainer || $( this.currentForm );
this.containers = $( this.settings.errorContainer ).add( this.settings.errorLabelContainer );
this.submitted = {};
this.valueCache = {};
this.pendingRequest = 0;
this.pending = {};
this.invalid = {};
this.reset();
var groups = ( this.groups = {} ),
rules;
$.each( this.settings.groups, function( key, value ) {
if ( typeof value === "string" ) {
value = value.split( /\s/ );
}
$.each( value, function( index, name ) {
groups[ name ] = key;
});
});
rules = this.settings.rules;
$.each( rules, function( key, value ) {
rules[ key ] = $.validator.normalizeRule( value );
});
function delegate( event ) {
var validator = $.data( this[ 0 ].form, "validator" ),
eventType = "on" + event.type.replace( /^validate/, "" ),
settings = validator.settings;
if ( settings[ eventType ] && !this.is( settings.ignore ) ) {
settings[ eventType ].call( validator, this[ 0 ], event );
}
}
$( this.currentForm )
.validateDelegate( ":text, [type='password'], [type='file'], select, textarea, " +
"[type='number'], [type='search'] ,[type='tel'], [type='url'], " +
"[type='email'], [type='datetime'], [type='date'], [type='month'], " +
"[type='week'], [type='time'], [type='datetime-local'], " +
"[type='range'], [type='color'], [type='radio'], [type='checkbox']",
"focusin focusout keyup", delegate)
// Support: Chrome, oldIE
// "select" is provided as event.target when clicking a option
.validateDelegate("select, option, [type='radio'], [type='checkbox']", "click", delegate);
if ( this.settings.invalidHandler ) {
$( this.currentForm ).bind( "invalid-form.validate", this.settings.invalidHandler );
}
// Add aria-required to any Static/Data/Class required fields before first validation
// Screen readers require this attribute to be present before the initial submission http://www.w3.org/TR/WCAG-TECHS/ARIA2.html
$( this.currentForm ).find( "[required], [data-rule-required], .required" ).attr( "aria-required", "true" );
},
// http://jqueryvalidation.org/Validator.form/
form: function() {
this.checkForm();
$.extend( this.submitted, this.errorMap );
this.invalid = $.extend({}, this.errorMap );
if ( !this.valid() ) {
$( this.currentForm ).triggerHandler( "invalid-form", [ this ]);
}
this.showErrors();
return this.valid();
},
checkForm: function() {
this.prepareForm();
for ( var i = 0, elements = ( this.currentElements = this.elements() ); elements[ i ]; i++ ) {
this.check( elements[ i ] );
}
return this.valid();
},
// http://jqueryvalidation.org/Validator.element/
element: function( element ) {
var cleanElement = this.clean( element ),
checkElement = this.validationTargetFor( cleanElement ),
result = true;
this.lastElement = checkElement;
if ( checkElement === undefined ) {
delete this.invalid[ cleanElement.name ];
} else {
this.prepareElement( checkElement );
this.currentElements = $( checkElement );
result = this.check( checkElement ) !== false;
if ( result ) {
delete this.invalid[ checkElement.name ];
} else {
this.invalid[ checkElement.name ] = true;
}
}
// Add aria-invalid status for screen readers
$( element ).attr( "aria-invalid", !result );
if ( !this.numberOfInvalids() ) {
// Hide error containers on last error
this.toHide = this.toHide.add( this.containers );
}
this.showErrors();
return result;
},
// http://jqueryvalidation.org/Validator.showErrors/
showErrors: function( errors ) {
if ( errors ) {
// add items to error list and map
$.extend( this.errorMap, errors );
this.errorList = [];
for ( var name in errors ) {
this.errorList.push({
message: errors[ name ],
element: this.findByName( name )[ 0 ]
});
}
// remove items from success list
this.successList = $.grep( this.successList, function( element ) {
return !( element.name in errors );
});
}
if ( this.settings.showErrors ) {
this.settings.showErrors.call( this, this.errorMap, this.errorList );
} else {
this.defaultShowErrors();
}
},
// http://jqueryvalidation.org/Validator.resetForm/
resetForm: function() {
if ( $.fn.resetForm ) {
$( this.currentForm ).resetForm();
}
this.submitted = {};
this.lastElement = null;
this.prepareForm();
this.hideErrors();
this.elements()
.removeClass( this.settings.errorClass )
.removeData( "previousValue" )
.removeAttr( "aria-invalid" );
},
numberOfInvalids: function() {
return this.objectLength( this.invalid );
},
objectLength: function( obj ) {
/* jshint unused: false */
var count = 0,
i;
for ( i in obj ) {
count++;
}
return count;
},
hideErrors: function() {
this.hideThese( this.toHide );
},
hideThese: function( errors ) {
errors.not( this.containers ).text( "" );
this.addWrapper( errors ).hide();
},
valid: function() {
return this.size() === 0;
},
size: function() {
return this.errorList.length;
},
focusInvalid: function() {
if ( this.settings.focusInvalid ) {
try {
$( this.findLastActive() || this.errorList.length && this.errorList[ 0 ].element || [])
.filter( ":visible" )
.focus()
// manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find
.trigger( "focusin" );
} catch ( e ) {
// ignore IE throwing errors when focusing hidden elements
}
}
},
findLastActive: function() {
var lastActive = this.lastActive;
return lastActive && $.grep( this.errorList, function( n ) {
return n.element.name === lastActive.name;
}).length === 1 && lastActive;
},
elements: function() {
var validator = this,
rulesCache = {};
// select all valid inputs inside the form (no submit or reset buttons)
return $( this.currentForm )
.find( "input, select, textarea" )
.not( ":submit, :reset, :image, [disabled]" )
.not( this.settings.ignore )
.filter( function() {
if ( !this.name && validator.settings.debug && window.console ) {
console.error( "%o has no name assigned", this );
}
// select only the first element for each name, and only those with rules specified
if ( this.name in rulesCache || !validator.objectLength( $( this ).rules() ) ) {
return false;
}
rulesCache[ this.name ] = true;
return true;
});
},
clean: function( selector ) {
return $( selector )[ 0 ];
},
errors: function() {
var errorClass = this.settings.errorClass.split( " " ).join( "." );
return $( this.settings.errorElement + "." + errorClass, this.errorContext );
},
reset: function() {
this.successList = [];
this.errorList = [];
this.errorMap = {};
this.toShow = $( [] );
this.toHide = $( [] );
this.currentElements = $( [] );
},
prepareForm: function() {
this.reset();
this.toHide = this.errors().add( this.containers );
},
prepareElement: function( element ) {
this.reset();
this.toHide = this.errorsFor( element );
},
elementValue: function( element ) {
var val,
$element = $( element ),
type = element.type;
if ( type === "radio" || type === "checkbox" ) {
return $( "input[name='" + element.name + "']:checked" ).val();
} else if ( type === "number" && typeof element.validity !== "undefined" ) {
return element.validity.badInput ? false : $element.val();
}
val = $element.val();
if ( typeof val === "string" ) {
return val.replace(/\r/g, "" );
}
return val;
},
check: function( element ) {
element = this.validationTargetFor( this.clean( element ) );
var rules = $( element ).rules(),
rulesCount = $.map( rules, function( n, i ) {
return i;
}).length,
dependencyMismatch = false,
val = this.elementValue( element ),
result, method, rule;
for ( method in rules ) {
rule = { method: method, parameters: rules[ method ] };
try {
result = $.validator.methods[ method ].call( this, val, element, rule.parameters );
// if a method indicates that the field is optional and therefore valid,
// don't mark it as valid when there are no other rules
if ( result === "dependency-mismatch" && rulesCount === 1 ) {
dependencyMismatch = true;
continue;
}
dependencyMismatch = false;
if ( result === "pending" ) {
this.toHide = this.toHide.not( this.errorsFor( element ) );
return;
}
if ( !result ) {
this.formatAndAdd( element, rule );
return false;
}
} catch ( e ) {
if ( this.settings.debug && window.console ) {
console.log( "Exception occurred when checking element " + element.id + ", check the '" + rule.method + "' method.", e );
}
throw e;
}
}
if ( dependencyMismatch ) {
return;
}
if ( this.objectLength( rules ) ) {
this.successList.push( element );
}
return true;
},
// return the custom message for the given element and validation method
// specified in the element's HTML5 data attribute
// return the generic message if present and no method specific message is present
customDataMessage: function( element, method ) {
return $( element ).data( "msg" + method.charAt( 0 ).toUpperCase() +
method.substring( 1 ).toLowerCase() ) || $( element ).data( "msg" );
},
// return the custom message for the given element name and validation method
customMessage: function( name, method ) {
var m = this.settings.messages[ name ];
return m && ( m.constructor === String ? m : m[ method ]);
},
// return the first defined argument, allowing empty strings
findDefined: function() {
for ( var i = 0; i < arguments.length; i++) {
if ( arguments[ i ] !== undefined ) {
return arguments[ i ];
}
}
return undefined;
},
defaultMessage: function( element, method ) {
return this.findDefined(
this.customMessage( element.name, method ),
this.customDataMessage( element, method ),
// title is never undefined, so handle empty string as undefined
!this.settings.ignoreTitle && element.title || undefined,
$.validator.messages[ method ],
"Warning: No message defined for " + element.name + ""
);
},
formatAndAdd: function( element, rule ) {
var message = this.defaultMessage( element, rule.method ),
theregex = /\$?\{(\d+)\}/g;
if ( typeof message === "function" ) {
message = message.call( this, rule.parameters, element );
} else if ( theregex.test( message ) ) {
message = $.validator.format( message.replace( theregex, "{$1}" ), rule.parameters );
}
this.errorList.push({
message: message,
element: element,
method: rule.method
});
this.errorMap[ element.name ] = message;
this.submitted[ element.name ] = message;
},
addWrapper: function( toToggle ) {
if ( this.settings.wrapper ) {
toToggle = toToggle.add( toToggle.parent( this.settings.wrapper ) );
}
return toToggle;
},
defaultShowErrors: function() {
var i, elements, error;
for ( i = 0; this.errorList[ i ]; i++ ) {
error = this.errorList[ i ];
if ( this.settings.highlight ) {
this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass );
}
this.showLabel( error.element, error.message );
}
if ( this.errorList.length ) {
this.toShow = this.toShow.add( this.containers );
}
if ( this.settings.success ) {
for ( i = 0; this.successList[ i ]; i++ ) {
this.showLabel( this.successList[ i ] );
}
}
if ( this.settings.unhighlight ) {
for ( i = 0, elements = this.validElements(); elements[ i ]; i++ ) {
this.settings.unhighlight.call( this, elements[ i ], this.settings.errorClass, this.settings.validClass );
}
}
this.toHide = this.toHide.not( this.toShow );
this.hideErrors();
this.addWrapper( this.toShow ).show();
},
validElements: function() {
return this.currentElements.not( this.invalidElements() );
},
invalidElements: function() {
return $( this.errorList ).map(function() {
return this.element;
});
},
showLabel: function( element, message ) {
var place, group, errorID,
error = this.errorsFor( element ),
elementID = this.idOrName( element ),
describedBy = $( element ).attr( "aria-describedby" );
if ( error.length ) {
// refresh error/success class
error.removeClass( this.settings.validClass ).addClass( this.settings.errorClass );
// replace message on existing label
error.html( message );
} else {
// create error element
error = $( "<" + this.settings.errorElement + ">" )
.attr( "id", elementID + "-error" )
.addClass( this.settings.errorClass )
.html( message || "" );
// Maintain reference to the element to be placed into the DOM
place = error;
if ( this.settings.wrapper ) {
// make sure the element is visible, even in IE
// actually showing the wrapped element is handled elsewhere
place = error.hide().show().wrap( "<" + this.settings.wrapper + "/>" ).parent();
}
if ( this.labelContainer.length ) {
this.labelContainer.append( place );
} else if ( this.settings.errorPlacement ) {
this.settings.errorPlacement( place, $( element ) );
} else {
place.insertAfter( element );
}
// Link error back to the element
if ( error.is( "label" ) ) {
// If the error is a label, then associate using 'for'
error.attr( "for", elementID );
} else if ( error.parents( "label[for='" + elementID + "']" ).length === 0 ) {
// If the element is not a child of an associated label, then it's necessary
// to explicitly apply aria-describedby
errorID = error.attr( "id" );
// Respect existing non-error aria-describedby
if ( !describedBy ) {
describedBy = errorID;
} else if ( !describedBy.match( new RegExp( "\b" + errorID + "\b" ) ) ) {
// Add to end of list if not already present
describedBy += " " + errorID;
}
$( element ).attr( "aria-describedby", describedBy );
// If this element is grouped, then assign to all elements in the same group
group = this.groups[ element.name ];
if ( group ) {
$.each( this.groups, function( name, testgroup ) {
if ( testgroup === group ) {
$( "[name='" + name + "']", this.currentForm )
.attr( "aria-describedby", error.attr( "id" ) );
}
});
}
}
}
if ( !message && this.settings.success ) {
error.text( "" );
if ( typeof this.settings.success === "string" ) {
error.addClass( this.settings.success );
} else {
this.settings.success( error, element );
}
}
this.toShow = this.toShow.add( error );
},
errorsFor: function( element ) {
var name = this.idOrName( element ),
describer = $( element ).attr( "aria-describedby" ),
selector = "label[for='" + name + "'], label[for='" + name + "'] *";
// aria-describedby should directly reference the error element
if ( describer ) {
selector = selector + ", #" + describer.replace( /\s+/g, ", #" );
}
return this
.errors()
.filter( selector );
},
idOrName: function( element ) {
return this.groups[ element.name ] || ( this.checkable( element ) ? element.name : element.id || element.name );
},
validationTargetFor: function( element ) {
// if radio/checkbox, validate first element in group instead
if ( this.checkable( element ) ) {
element = this.findByName( element.name ).not( this.settings.ignore )[ 0 ];
}
return element;
},
checkable: function( element ) {
return ( /radio|checkbox/i ).test( element.type );
},
findByName: function( name ) {
return $( this.currentForm ).find( "[name='" + name + "']" );
},
getLength: function( value, element ) {
switch ( element.nodeName.toLowerCase() ) {
case "select":
return $( "option:selected", element ).length;
case "input":
if ( this.checkable( element ) ) {
return this.findByName( element.name ).filter( ":checked" ).length;
}
}
return value.length;
},
depend: function( param, element ) {
return this.dependTypes[typeof param] ? this.dependTypes[typeof param]( param, element ) : true;
},
dependTypes: {
"boolean": function( param ) {
return param;
},
"string": function( param, element ) {
return !!$( param, element.form ).length;
},
"function": function( param, element ) {
return param( element );
}
},
optional: function( element ) {
var val = this.elementValue( element );
return !$.validator.methods.required.call( this, val, element ) && "dependency-mismatch";
},
startRequest: function( element ) {
if ( !this.pending[ element.name ] ) {
this.pendingRequest++;
this.pending[ element.name ] = true;
}
},
stopRequest: function( element, valid ) {
this.pendingRequest--;
// sometimes synchronization fails, make sure pendingRequest is never < 0
if ( this.pendingRequest < 0 ) {
this.pendingRequest = 0;
}
delete this.pending[ element.name ];
if ( valid && this.pendingRequest === 0 && this.formSubmitted && this.form() ) {
$( this.currentForm ).submit();
this.formSubmitted = false;
} else if (!valid && this.pendingRequest === 0 && this.formSubmitted ) {
$( this.currentForm ).triggerHandler( "invalid-form", [ this ]);
this.formSubmitted = false;
}
},
previousValue: function( element ) {
return $.data( element, "previousValue" ) || $.data( element, "previousValue", {
old: null,
valid: true,
message: this.defaultMessage( element, "remote" )
});
}
},
classRuleSettings: {
required: { required: true },
email: { email: true },
url: { url: true },
date: { date: true },
dateISO: { dateISO: true },
number: { number: true },
digits: { digits: true },
creditcard: { creditcard: true }
},
addClassRules: function( className, rules ) {
if ( className.constructor === String ) {
this.classRuleSettings[ className ] = rules;
} else {
$.extend( this.classRuleSettings, className );
}
},
classRules: function( element ) {
var rules = {},
classes = $( element ).attr( "class" );
if ( classes ) {
$.each( classes.split( " " ), function() {
if ( this in $.validator.classRuleSettings ) {
$.extend( rules, $.validator.classRuleSettings[ this ]);
}
});
}
return rules;
},
attributeRules: function( element ) {
var rules = {},
$element = $( element ),
type = element.getAttribute( "type" ),
method, value;
for ( method in $.validator.methods ) {
// support for in both html5 and older browsers
if ( method === "required" ) {
value = element.getAttribute( method );
// Some browsers return an empty string for the required attribute
// and non-HTML5 browsers might have required="" markup
if ( value === "" ) {
value = true;
}
// force non-HTML5 browsers to return bool
value = !!value;
} else {
value = $element.attr( method );
}
// convert the value to a number for number inputs, and for text for backwards compability
// allows type="date" and others to be compared as strings
if ( /min|max/.test( method ) && ( type === null || /number|range|text/.test( type ) ) ) {
value = Number( value );
}
if ( value || value === 0 ) {
rules[ method ] = value;
} else if ( type === method && type !== "range" ) {
// exception: the jquery validate 'range' method
// does not test for the html5 'range' type
rules[ method ] = true;
}
}
// maxlength may be returned as -1, 2147483647 ( IE ) and 524288 ( safari ) for text inputs
if ( rules.maxlength && /-1|2147483647|524288/.test( rules.maxlength ) ) {
delete rules.maxlength;
}
return rules;
},
dataRules: function( element ) {
var method, value,
rules = {}, $element = $( element );
for ( method in $.validator.methods ) {
value = $element.data( "rule" + method.charAt( 0 ).toUpperCase() + method.substring( 1 ).toLowerCase() );
if ( value !== undefined ) {
rules[ method ] = value;
}
}
return rules;
},
staticRules: function( element ) {
var rules = {},
validator = $.data( element.form, "validator" );
if ( validator.settings.rules ) {
rules = $.validator.normalizeRule( validator.settings.rules[ element.name ] ) || {};
}
return rules;
},
normalizeRules: function( rules, element ) {
// handle dependency check
$.each( rules, function( prop, val ) {
// ignore rule when param is explicitly false, eg. required:false
if ( val === false ) {
delete rules[ prop ];
return;
}
if ( val.param || val.depends ) {
var keepRule = true;
switch ( typeof val.depends ) {
case "string":
keepRule = !!$( val.depends, element.form ).length;
break;
case "function":
keepRule = val.depends.call( element, element );
break;
}
if ( keepRule ) {
rules[ prop ] = val.param !== undefined ? val.param : true;
} else {
delete rules[ prop ];
}
}
});
// evaluate parameters
$.each( rules, function( rule, parameter ) {
rules[ rule ] = $.isFunction( parameter ) ? parameter( element ) : parameter;
});
// clean number parameters
$.each([ "minlength", "maxlength" ], function() {
if ( rules[ this ] ) {
rules[ this ] = Number( rules[ this ] );
}
});
$.each([ "rangelength", "range" ], function() {
var parts;
if ( rules[ this ] ) {
if ( $.isArray( rules[ this ] ) ) {
rules[ this ] = [ Number( rules[ this ][ 0 ]), Number( rules[ this ][ 1 ] ) ];
} else if ( typeof rules[ this ] === "string" ) {
parts = rules[ this ].replace(/[\[\]]/g, "" ).split( /[\s,]+/ );
rules[ this ] = [ Number( parts[ 0 ]), Number( parts[ 1 ] ) ];
}
}
});
if ( $.validator.autoCreateRanges ) {
// auto-create ranges
if ( rules.min && rules.max ) {
rules.range = [ rules.min, rules.max ];
delete rules.min;
delete rules.max;
}
if ( rules.minlength && rules.maxlength ) {
rules.rangelength = [ rules.minlength, rules.maxlength ];
delete rules.minlength;
delete rules.maxlength;
}
}
return rules;
},
// Converts a simple string to a {string: true} rule, e.g., "required" to {required:true}
normalizeRule: function( data ) {
if ( typeof data === "string" ) {
var transformed = {};
$.each( data.split( /\s/ ), function() {
transformed[ this ] = true;
});
data = transformed;
}
return data;
},
// http://jqueryvalidation.org/jQuery.validator.addMethod/
addMethod: function( name, method, message ) {
$.validator.methods[ name ] = method;
$.validator.messages[ name ] = message !== undefined ? message : $.validator.messages[ name ];
if ( method.length < 3 ) {
$.validator.addClassRules( name, $.validator.normalizeRule( name ) );
}
},
methods: {
// http://jqueryvalidation.org/required-method/
required: function( value, element, param ) {
// check if dependency is met
if ( !this.depend( param, element ) ) {
return "dependency-mismatch";
}
if ( element.nodeName.toLowerCase() === "select" ) {
// could be an array for select-multiple or a string, both are fine this way
var val = $( element ).val();
return val && val.length > 0;
}
if ( this.checkable( element ) ) {
return this.getLength( value, element ) > 0;
}
return $.trim( value ).length > 0;
},
// http://jqueryvalidation.org/email-method/
email: function( value, element ) {
// From http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#e-mail-state-%28type=email%29
// Retrieved 2014-01-14
// If you have a problem with this implementation, report a bug against the above spec
// Or use custom methods to implement your own email validation
return this.optional( element ) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test( value );
},
// http://jqueryvalidation.org/url-method/
url: function( value, element ) {
// contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
return this.optional( element ) || /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test( value );
},
// http://jqueryvalidation.org/date-method/
date: function( value, element ) {
return this.optional( element ) || !/Invalid|NaN/.test( new Date( value ).toString() );
},
// http://jqueryvalidation.org/dateISO-method/
dateISO: function( value, element ) {
return this.optional( element ) || /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test( value );
},
// http://jqueryvalidation.org/number-method/
number: function( value, element ) {
return this.optional( element ) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test( value );
},
// http://jqueryvalidation.org/digits-method/
digits: function( value, element ) {
return this.optional( element ) || /^\d+$/.test( value );
},
// http://jqueryvalidation.org/creditcard-method/
// based on http://en.wikipedia.org/wiki/Luhn/
creditcard: function( value, element ) {
if ( this.optional( element ) ) {
return "dependency-mismatch";
}
// accept only spaces, digits and dashes
if ( /[^0-9 \-]+/.test( value ) ) {
return false;
}
var nCheck = 0,
nDigit = 0,
bEven = false,
n, cDigit;
value = value.replace( /\D/g, "" );
// Basing min and max length on
// http://developer.ean.com/general_info/Valid_Credit_Card_Types
if ( value.length < 13 || value.length > 19 ) {
return false;
}
for ( n = value.length - 1; n >= 0; n--) {
cDigit = value.charAt( n );
nDigit = parseInt( cDigit, 10 );
if ( bEven ) {
if ( ( nDigit *= 2 ) > 9 ) {
nDigit -= 9;
}
}
nCheck += nDigit;
bEven = !bEven;
}
return ( nCheck % 10 ) === 0;
},
// http://jqueryvalidation.org/minlength-method/
minlength: function( value, element, param ) {
var length = $.isArray( value ) ? value.length : this.getLength( $.trim( value ), element );
return this.optional( element ) || length >= param;
},
// http://jqueryvalidation.org/maxlength-method/
maxlength: function( value, element, param ) {
var length = $.isArray( value ) ? value.length : this.getLength( $.trim( value ), element );
return this.optional( element ) || length <= param;
},
// http://jqueryvalidation.org/rangelength-method/
rangelength: function( value, element, param ) {
var length = $.isArray( value ) ? value.length : this.getLength( $.trim( value ), element );
return this.optional( element ) || ( length >= param[ 0 ] && length <= param[ 1 ] );
},
// http://jqueryvalidation.org/min-method/
min: function( value, element, param ) {
return this.optional( element ) || value >= param;
},
// http://jqueryvalidation.org/max-method/
max: function( value, element, param ) {
return this.optional( element ) || value <= param;
},
// http://jqueryvalidation.org/range-method/
range: function( value, element, param ) {
return this.optional( element ) || ( value >= param[ 0 ] && value <= param[ 1 ] );
},
// http://jqueryvalidation.org/equalTo-method/
equalTo: function( value, element, param ) {
// bind to the blur event of the target in order to revalidate whenever the target field is updated
// TODO find a way to bind the event just once, avoiding the unbind-rebind overhead
var target = $( param );
if ( this.settings.onfocusout ) {
target.unbind( ".validate-equalTo" ).bind( "blur.validate-equalTo", function() {
$( element ).valid();
});
}
return value === target.val();
},
// http://jqueryvalidation.org/remote-method/
remote: function( value, element, param ) {
if ( this.optional( element ) ) {
return "dependency-mismatch";
}
var previous = this.previousValue( element ),
validator, data;
if (!this.settings.messages[ element.name ] ) {
this.settings.messages[ element.name ] = {};
}
previous.originalMessage = this.settings.messages[ element.name ].remote;
this.settings.messages[ element.name ].remote = previous.message;
param = typeof param === "string" && { url: param } || param;
if ( previous.old === value ) {
return previous.valid;
}
previous.old = value;
validator = this;
this.startRequest( element );
data = {};
data[ element.name ] = value;
$.ajax( $.extend( true, {
url: param,
mode: "abort",
port: "validate" + element.name,
dataType: "json",
data: data,
context: validator.currentForm,
success: function( response ) {
var valid = response === true || response === "true",
errors, message, submitted;
validator.settings.messages[ element.name ].remote = previous.originalMessage;
if ( valid ) {
submitted = validator.formSubmitted;
validator.prepareElement( element );
validator.formSubmitted = submitted;
validator.successList.push( element );
delete validator.invalid[ element.name ];
validator.showErrors();
} else {
errors = {};
message = response || validator.defaultMessage( element, "remote" );
errors[ element.name ] = previous.message = $.isFunction( message ) ? message( value ) : message;
validator.invalid[ element.name ] = true;
validator.showErrors( errors );
}
previous.valid = valid;
validator.stopRequest( element, valid );
}
}, param ) );
return "pending";
}
}
});
$.format = function deprecated() {
throw "$.format has been deprecated. Please use $.validator.format instead.";
};
// ajax mode: abort
// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort()
var pendingRequests = {},
ajax;
// Use a prefilter if available (1.5+)
if ( $.ajaxPrefilter ) {
$.ajaxPrefilter(function( settings, _, xhr ) {
var port = settings.port;
if ( settings.mode === "abort" ) {
if ( pendingRequests[port] ) {
pendingRequests[port].abort();
}
pendingRequests[port] = xhr;
}
});
} else {
// Proxy ajax
ajax = $.ajax;
$.ajax = function( settings ) {
var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode,
port = ( "port" in settings ? settings : $.ajaxSettings ).port;
if ( mode === "abort" ) {
if ( pendingRequests[port] ) {
pendingRequests[port].abort();
}
pendingRequests[port] = ajax.apply(this, arguments);
return pendingRequests[port];
}
return ajax.apply(this, arguments);
};
}
// provides delegate(type: String, delegate: Selector, handler: Callback) plugin for easier event delegation
// handler is only called when $(event.target).is(delegate), in the scope of the jquery-object for event.target
$.extend($.fn, {
validateDelegate: function( delegate, type, handler ) {
return this.bind(type, function( event ) {
var target = $(event.target);
if ( target.is(delegate) ) {
return handler.apply(target, arguments);
}
});
}
});
}));
// --- Additional jQuery.validate.js validators ---------
jQuery.validator.addMethod("phoneUS", function (phone_number, element) {
var digits = phone_number.replace(/\D/g, "");
return this.optional(element) || digits.length == 7 || digits.length == 10 || digits.length == 11;
}, "Enter a valid phone number or start with '+' for international.");
jQuery.validator.addMethod("phoneInternational", function (phone_number, element) {
return this.optional(element) || /^\+[0-9\-\(\)\s.]+$/i.test(phone_number);
}, "Please specify a valid phone number");
jQuery.validator.classRuleSettings.phoneInternational = { phoneInternational: true };
(function () {
function stripHtml(value) {
return value.replace(/<.[^<>]*?>/g, ' ').replace(/ | /gi, ' ')
.replace(/[.(),;:!?%#$'"_+=\/-]*/g, '');
}
jQuery.validator.addMethod("maxWords", function (value, element, params) {
return this.optional(element) || stripHtml(value).match(/\b\w+\b/g).length <= params;
}, jQuery.validator.format("Please enter {0} words or less."));
jQuery.validator.addMethod("minWords", function (value, element, params) {
return this.optional(element) || stripHtml(value).match(/\b\w+\b/g).length >= params;
}, jQuery.validator.format("Please enter at least {0} words."));
jQuery.validator.addMethod("rangeWords", function (value, element, params) {
var valueStripped = stripHtml(value);
var regex = /\b\w+\b/g;
return this.optional(element) || valueStripped.match(regex).length >= params[0] && valueStripped.match(regex).length <= params[1];
}, jQuery.validator.format("Please enter between {0} and {1} words."));
})();
jQuery.validator.addMethod("letterswithbasicpunc", function (value, element) {
return this.optional(element) || /^[a-z\-.,()'\"\s]+$/i.test(value);
}, "Letters or punctuation only please");
jQuery.validator.addMethod("alphanumeric", function (value, element) {
return this.optional(element) || /^\w+$/i.test(value);
}, "Letters, numbers, and underscores only please");
jQuery.validator.addMethod("lettersonly", function (value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Letters only please");
jQuery.validator.addMethod("nowhitespace", function (value, element) {
return this.optional(element) || /^\S+$/i.test(value);
}, "No white space please");
jQuery.validator.addMethod("nospacesUsername", function (value, element) {
return this.optional(element) || /^\S+$/i.test(value);
}, "Username cannot contain spaces.");
jQuery.validator.addMethod("ziprange", function (value, element) {
return this.optional(element) || /^90[2-5]\d\{2\}-\d{4}$/.test(value);
}, "Your ZIP-code must be in the range 902xx-xxxx to 905-xx-xxxx");
jQuery.validator.addMethod("zipcodeUS", function (value, element) {
return this.optional(element) || /\d{5}-\d{4}$|^\d{5}$/.test(value)
}, "The specified US ZIP Code is invalid");
jQuery.validator.addMethod("integer", function (value, element) {
return this.optional(element) || /^-?\d+$/.test(value);
}, "A positive or negative non-decimal number please");
jQuery.validator.addMethod("positiveInteger", function (value, element) {
return this.optional(element) || /^\d+$/.test(value);
}, "Please enter a positive whole number");
jQuery.validator.addMethod("time", function (value, element) {
return this.optional(element) || /^([0-1]\d|2[0-3]):([0-5]\d)$/.test(value);
}, "Please enter a valid time, between 00:00 and 23:59");
jQuery.validator.addMethod("time12h", function (value, element) {
return this.optional(element) || /^((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))$/i.test(value);
}, "Please enter a valid time, between 00:00 am and 12:00 pm");
jQuery.validator.addMethod('postcodeUK', function (postcode, element) {
postcode = (postcode.toUpperCase()).replace(/\s+/g, '');
return this.optional(element) || postcode.match(/^([^QZ][^IJZ]{0,1}\d{1,2})(\d[^CIKMOV]{2})$/) || postcode.match(/^([^QV]\d[ABCDEFGHJKSTUW])(\d[^CIKMOV]{2})$/) || postcode.match(/^([^QV][^IJZ]\d[ABEHMNPRVWXY])(\d[^CIKMOV]{2})$/) || postcode.match(/^(GIR)(0AA)$/) || postcode.match(/^(BFPO)(\d{1,4})$/) || postcode.match(/^(BFPO)(C\/O\d{1,3})$/);
}, 'Please specify a valid postcode');
// TODO check if value starts with <, otherwise don't try stripping anything
jQuery.validator.addMethod("strippedminlength", function (value, element, param) {
return jQuery(value).text().length >= param;
}, jQuery.validator.format("Please enter at least {0} characters"));
// NOTICE: Modified version of Castle.Components.Validator.CreditCardValidator
// Redistributed under the the Apache License 2.0 at http://www.apache.org/licenses/LICENSE-2.0
// Valid Types: mastercard, visa, amex, dinersclub, enroute, discover, jcb, unknown, all (overrides all other settings)
jQuery.validator.addMethod("creditcardtypes", function (value, element, param) {
if (/[^0-9-]+/.test(value)) {
return false;
}
value = value.replace(/\D/g, "");
var validTypes = 0x0000;
if (param.mastercard)
validTypes |= 0x0001;
if (param.visa)
validTypes |= 0x0002;
if (param.amex)
validTypes |= 0x0004;
if (param.dinersclub)
validTypes |= 0x0008;
if (param.enroute)
validTypes |= 0x0010;
if (param.discover)
validTypes |= 0x0020;
if (param.jcb)
validTypes |= 0x0040;
if (param.unknown)
validTypes |= 0x0080;
if (param.all)
validTypes = 0x0001 | 0x0002 | 0x0004 | 0x0008 | 0x0010 | 0x0020 | 0x0040 | 0x0080;
if (validTypes & 0x0001 && /^(5[12345])/.test(value)) { //mastercard
return value.length == 16;
}
if (validTypes & 0x0002 && /^(4)/.test(value)) { //visa
return value.length == 16;
}
if (validTypes & 0x0004 && /^(3[47])/.test(value)) { //amex
return value.length == 15;
}
if (validTypes & 0x0008 && /^(3(0[012345]|[68]))/.test(value)) { //dinersclub
return value.length == 14;
}
if (validTypes & 0x0010 && /^(2(014|149))/.test(value)) { //enroute
return value.length == 15;
}
if (validTypes & 0x0020 && /^(6011)/.test(value)) { //discover
return value.length == 16;
}
if (validTypes & 0x0040 && /^(3)/.test(value)) { //jcb
return value.length == 16;
}
if (validTypes & 0x0040 && /^(2131|1800)/.test(value)) { //jcb
return value.length == 15;
}
if (validTypes & 0x0080) { //unknown
return true;
}
return false;
}, "Please enter a valid credit card number.");
jQuery.validator.addMethod("pattern", function (value, element, param) {
if (this.optional(element)) {
return true;
}
if (typeof param === 'string') {
param = new RegExp('^(?:' + param + ')$');
}
return param.test(value);
}, "Invalid format.");
/*
* Lets you say "at least X inputs that match selector Y must be filled."
*
* The end result is that neither of these inputs:
*
*
*
*
* ...will validate unless at least one of them is filled.
*
* partnumber: {require_from_group: [1,".productinfo"]},
* description: {require_from_group: [1,".productinfo"]}
*
*/
jQuery.validator.addMethod("require_from_group", function (value, element, options) {
var validator = this;
var selector = options[1];
var validOrNot = $(selector, element.form).filter(function () {
return validator.elementValue(this);
}).length >= options[0];
if (!$(element).data('being_validated')) {
var fields = $(selector, element.form);
fields.data('being_validated', true);
fields.valid();
fields.data('being_validated', false);
}
return validOrNot;
}, jQuery.validator.format("Please supply at least {0} of these values."));
/*
* Lets you say "either at least X inputs that match selector Y must be filled,
* OR they must all be skipped (left blank)."
*
* The end result, is that none of these inputs:
*
*
*
*
*
* ...will validate unless either at least two of them are filled,
* OR none of them are.
*
* partnumber: {skip_or_fill_minimum: [2,".productinfo"]},
* description: {skip_or_fill_minimum: [2,".productinfo"]},
* color: {skip_or_fill_minimum: [2,".productinfo"]}
*
*/
jQuery.validator.addMethod("skip_or_fill_minimum", function (value, element, options) {
var validator = this;
numberRequired = options[0];
selector = options[1];
var numberFilled = $(selector, element.form).filter(function () {
return validator.elementValue(this);
}).length;
var valid = numberFilled >= numberRequired || numberFilled === 0;
if (!$(element).data('being_validated')) {
var fields = $(selector, element.form);
fields.data('being_validated', true);
fields.valid();
fields.data('being_validated', false);
}
return valid;
}, jQuery.validator.format("Please either skip these fields or fill at least {0} of them."));
//
// Make a server-side check to see if another record of this type already has this name
// Dependent on the saving controller having a "ValidateUniqueName" action.
//
jQuery.validator.addMethod("uniqueName", function (value, element, options) {
// Don't bother checking uniqueness unless there's actually a value to check
value = value.normalizeSpace();
if (!value)
return true;
var label = $(element).closest(".field").find("label").first();
label.append("(Verifying)");
var uri = $(element).closest("form").attr("action")
.replace("/Create/", "/ValidateUniqueName/")
.replace("/Update/", "/ValidateUniqueName/");
// No id designation
if (uri.endsWith("/Create")) {
uri = uri.replace("/Create", "/ValidateUniqueName");
}
// No id designation
else if (uri.endsWith("/Update")) {
uri = uri.replace("/Update", "/ValidateUniqueName");
}
else {
var lastToken = uri.stripTrailing("/").afterLast("/");
var lastTokenId = parseInt(lastToken)
if (lastToken && isNaN(lastTokenId)) {
uri = uri.stripTrailing("/").beforeLast("/") + "/ValidateUniqueName/0";
}
else if (lastToken) {
uri = uri.stripTrailing("/").beforeLast("/").beforeLast("/") + "/ValidateUniqueName/" + lastToken;
}
}
var dataValidateUrl = $(element).data("validate-url");
if (dataValidateUrl) {
uri = dataValidateUrl;
}
var result = false;
$.ajax({
url: uri,
data: { name: $(element).val().normalizeSpace() },
async: false,
cache: false,
success: function (data) {
result = parseBoolean(data);
}
});
label.find("span.thinking").remove();
return result;
}, "This name is already taken.");
jQuery.validator.classRuleSettings.uniqueName = { uniqueName: true };
jQuery.validator.addMethod("uniqueUsername", function (value, element, options) {
var userId = $("#User_Id").val() || 0;
var label = $(element).closest(".field").find("label").first();
label.append("(Verifying)");
var result = false;
var uri = "~/Settings/User/ValidateUniqueUsername/" + userId;
$.ajax({
url: window.Url(uri),
data: { username: value },
async: false,
cache: false,
success: function (data) {
result = parseBoolean(data);
}
});
label.find("span.thinking").remove();
return result;
}, "This username is already taken.");
jQuery.validator.classRuleSettings.uniqueUsername = { nospacesUsername: true, uniqueUsername: true };
jQuery.validator.addMethod("uniqueEmail", function (value, element, options) {
var userId = $("#User_Id").val() || 0;
var label = $(element).closest(".field").find("label").first();
label.append("(Verifying)");
var result = false;
var uri = "~/Settings/User/ValidateUniqueEmail/" + userId;
$.ajax({
url: window.Url(uri),
data: { email: value },
async: false,
cache: false,
success: function (data) {
result = parseBoolean(data);
}
});
label.find("span.thinking").remove();
return result;
}, "This email address is already in use.");
jQuery.validator.classRuleSettings.uniqueEmail = { uniqueEmail: true };
let userNameErrorMessage = ""
let getUserNameErrorMessage = function() {
return userNameErrorMessage;
}
jQuery.validator.addMethod("validUsername", function (value, element, options) {
let userId = $("#User_Id").val() || 0;
let args = {
UserId: userId,
UserName: element.value
}
let label = $(element).closest(".field").find("label").first();
label.append("(Verifying)");
let result = false;
let uri = "~/Settings/User/ValidateUsername/";
$.ajax({
url: window.Url(uri),
data: args,
async: false,
method: "POST",
success: function (data) {
result = data.isSuccess;
if (!data.isSuccess) {
userNameErrorMessage = data.message;
}
}
});
label.find("span.thinking").remove();
return result;
}, () => { return getUserNameErrorMessage(); });
jQuery.validator.classRuleSettings.validUsername = { nospacesUsername: true, validUsername: true };
//
// Checks for valid currency
//
jQuery.validator.addMethod("currency", function (value, element, options) {
return !value ||
value
.replaceOne($.constants.currencySymbol, "")
.replaceOne($.constants.numberDecimal, "")
.replaceAll($.constants.numberGroup, "")
.match(/^\d+$/g);
}, "Please enter a valid currency.");
jQuery.validator.classRuleSettings.currency = { currency: true };
//
// Checks for valid number
//
jQuery.validator.addMethod("number", function (value, element, options) {
return !value ||
value
.replaceOne($.constants.numberDecimal, "")
.replaceAll($.constants.numberGroup, "")
.match(/^\d+$/g);
}, "Not a valid number");
jQuery.validator.classRuleSettings.number = { number: true };
//
// Checks for valid date - not just the format, but are the numbers in it valid (e.g. "43/99/2012" is not really valid)
// NOTE: Relies on parseDate() used by jquery datepicker from jquery UI.
//
jQuery.validator.addMethod("validDate", function (value, element, options) {
try {
return (!value || parseDate(value)) ? true : false;
}
catch (e) {
return false;
}
}, function () { return "Date is not a valid '" + $.constants.dateFormat + "'"; });
jQuery.validator.classRuleSettings.validDate = { validDate: true };
//
// Checks to make sure the "End Date" is greater than this "Start Date"
// NOTE: Relies on parseDate() used by jquery datepicker from jquery UI.
//
jQuery.validator.addMethod("startDateLesser", function (value, element, options) {
try {
//check start date has a value
if (!value)
return true;
//check if this is not a date yet
if (value && !parseDate(value))
return true;
let otherValue = jQuery(element.getAttribute('data-end-date-selector')).val();
//check end date has a value
if (!otherValue)
return true;
// check if end date is not a value
if (otherValue && !parseDate(otherValue))
return true;
let startDate = parseDate(value);
let endDate = parseDate(otherValue);
return startDate <= endDate;
}
catch (e) {
//exceptions are parsing errors
//we only validate valid dates.
return true;
}
}, function () { return "Must be on or before the end date."; });
jQuery.validator.classRuleSettings.startDateLesser = { startDateLesser: true };
//
// Checks to make sure the "Start Date" is lesser than this "End Date"
// NOTE: Relies on parseDate() used by jquery datepicker from jquery UI.
//
jQuery.validator.addMethod("endDateGreater", function (value, element, options) {
try {
// make sure end date has value
if (!value)
return true;
//check if this end date is not a date yet
if (value && !parseDate(value))
return true;
let otherValue = jQuery(element.getAttribute('data-start-date-selector')).val();
// make sure start date has a value
if (!otherValue)
return true;
// check if start date is not a value
if (otherValue && !parseDate(otherValue))
return true;
let endDate = parseDate(value);
let startDate = parseDate(otherValue);
return endDate >= startDate;
}
catch (e) {
//exceptions are parsing errors
//we only validate valid dates.
return true;
}
}, function () { return "Must be on or after the start date."; });
jQuery.validator.classRuleSettings.endDateGreater = { endDateGreater: true };
//
// Checks for valid date - not just the format, but if it's a valid date (e.g. "February 30" is not really valid)
// NOTE: Relies on parseDate() used by jquery datepicker from jquery UI.
//
jQuery.validator.addMethod("validMonthDay", function (value, element, options) {
try {
return (!value || $.datepicker.parseDate('MM d', ("" + value).normalizeSpace().trim())) ? true : false;
}
catch (e) {
return false;
}
}, function () { return "Date is not valid"; });
jQuery.validator.classRuleSettings.validMonthDay = { validMonthDay: true };
//
// Checks for valid year
//
jQuery.validator.addMethod("validYear", function (value, element, options) {
try {
return (!value || value.match(/^[1-9]\d\d\d$/)) ? true : false;
}
catch (e) {
return false;
}
}, function () { return "Must be a 4 digit year"; });
jQuery.validator.classRuleSettings.validYear = { validYear: true };
//
// Ensures a somewhat valid website
//
jQuery.validator.addMethod("website", function (value, element, options) {
try {
// Optionally start with "http(s)://"
// Any number of valid domain name characters (0-9, a-Z, or -, _, :) followed by a dot, one or more times
// any number of valid TLD characters (a-Z)
// optionally, either a slash or a question mark followed by any number of valid characters for a URL (!$&'()*+,;=%a-zA-Z0-9-._~:@/?#)
return (!value || value.match(/^((http|https):\/\/)?([0-9a-zA-z\-_:]+\.)+[a-zA-z]+((\/|\?)[!$&'())*+,;=%a-zA-Z0-9\-\._~:@\/\?#]*)?$/g)) ? true : false;
}
catch (e) {
return false;
}
}, function () { return "Not a valid website (e.g. 'www.google.com')"; });
jQuery.validator.classRuleSettings.website = { website: true };
//
// Ensures a somewhat valid windows file name
// based on https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
//
jQuery.validator.addMethod("windows_file", function (value, element, options) {
// forbidden characters \ / : * ? " < > |
return (!value || value.match(/^[^\\/:\*\?"<>\|]+$/));
}, function () { return "Not a valid file name"; });
jQuery.validator.classRuleSettings.windows_file = { windows_file: true };
//
// Compares 2 number values to ensure one is less-than or equal to the other
// * Element must have data-number-lte="OTHER_ELEMENT_ID" to find comparison account
// * Element must have data-number-lte-label="Other Field Name" for error message
//
jQuery.validator.addMethod("number_lte", function (value, element, options) {
try {
var myValue = parseCurrency(value || "0");
var otherValue = parseCurrency($("#" + $(element).attr("data-number-lte")).val() || "0");
return myValue <= otherValue;
}
catch (e) {
return false;
}
}, function (result, e) { return "Please enter a value less than the " + $(e).attr("data-number-lte-label"); });
jQuery.validator.classRuleSettings.number_lte = { number_lte: true };
//
// Ensure the date is in the future
//
jQuery.validator.addMethod("date_no_past", function (value, element, options) {
try {
var now = new Date();
now.setHours(0);
now.setMinutes(0);
now.setSeconds(0);
now.setMilliseconds(0);
return now.getTime() <= parseDate(value).getTime();
}
catch (e) {
return false;
}
}, function () { return "May not be in the past"; });
jQuery.validator.classRuleSettings.date_no_past = { date_no_past: true };
jQuery.validator.addMethod("date_year_future", function(value, element, options) {
var nextYear = new Date(new Date().setFullYear(new Date().getFullYear() + 1));
return nextYear.getTime() > parseDate(value).getTime();
}, "May not be more than one year in the future");
jQuery.validator.classRuleSettings.date_year_future = { date_year_future: true };
jQuery.validator.addMethod("date_time_no_past", function(value, element, options) {
return new Date().getTime() <= new Date(value).getTime();
}, "Enter a future time or future date");
jQuery.validator.classRuleSettings.date_time_no_past = { date_time_no_past: true };
jQuery.validator.addMethod("facebookPage", function (value, element, option) {
if (($("#ShowFacebookLikeButton").val() == "true") && $(element).val() == "") {
return false;
} else {
return true;
}
}, "Please enter a Facebook Page to use Facebook features");
jQuery.validator.addMethod("facebookPageValidation", function (value, element, option) {
var validChars = /^[a-zA-Z0-9./]*$/;
return validChars.test($(element).val());
}, "Please enter a valid Facebook Page");
jQuery.validator.classRuleSettings.facebookPage = { facebookPage: true, facebookPageValidation: true };
jQuery.validator.addMethod("twitterHandle", function (value, element, option) {
if ($("#ShowTwitterFollowButton").val() == "true" && $(element).val() == "") {
return false;
} else {
return true;
}
}, "Please enter a Twitter handle to use the Follow button");
/*
If this Twitter handle regex changes, be sure to
update in AccountHeaderAccountModel.js twitterHandleIsValid method
*/
//invalidates twitter handles that arent valid - https://support.twitter.com/articles/101299.
jQuery.validator.addMethod("twitterHandleValidation", function (value, element, option) {
var validChars = /^@?[a-z0-9_]+$/i;
var val = $(element).val();
return val === "" || validChars.test(val);
}, "Please enter a valid Twitter handle");
jQuery.validator.classRuleSettings.twitterHandle = { twitterHandle: true, twitterHandleValidation: true };
jQuery.validator.classRuleSettings.twitterHandleValidation = { twitterHandleValidation: true };
var twitterTweetBoxMaxLength = 116;
jQuery.validator.addMethod("twitterTweetBox", function (value, element, option) {
return ($("#twitterTweetTextBox").val().length <= twitterTweetBoxMaxLength)
}, "Please shorten your Tweet.");
jQuery.validator.classRuleSettings.twitterTweetTextBox = { twitterTweetBox: true }
jQuery.validator.addMethod("redirectUrl", function (value, element, option) {
//regex from https://mathiasbynens.be/demo/url-regex @diegoperini
var regexUrl = new RegExp(/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i)
return (regexUrl.exec($("#redirectUrl").val()))
}, "Please enter a full valid URL (https://www.example.com)");
jQuery.validator.classRuleSettings.redirectUrl = { redirectUrl: true }
//
// Not really validation - just replaces < and > in HTML w/ [ and ]
//
jQuery.validator.addMethod("replace_html_chars", function (value, element, options) {
$(element).val(value.replace(//g, "]"));
return true;
}, function () { return ""; });
jQuery.validator.classRuleSettings.replace_html_chars = { replace_html_chars: true };
jQuery.validator.addMethod("spreedlyCardNumber", function (value, element, option) {
return $("#spreedly-number").data("isValid");
}, "Please enter a valid card number.");
jQuery.validator.classRuleSettings.spreedlyCardNumber = { spreedlyCardNumber: true };
jQuery.validator.addMethod("spreedlyCvvNumber", function (value, element, option) {
return $("#spreedly-cvv").data("isValid");
}, "Please enter a valid card verification number.");
jQuery.validator.classRuleSettings.spreedlyCvvNumber = { spreedlyCvvNumber: true };
jQuery.validator.addMethod("eventRegistrationTypeNameUnique", function (value, element, option) {
var thisElement = element;
var inputs = $("input.eventRegistrationTypeNameUnique");
for (var i = inputs.length - 1; i >= 0; i--) {
if (inputs[i].name != thisElement.name && $(inputs[i]).val() === $(thisElement).val())
return false;
}
return true;
}, "Please use a unique registration type name.");
jQuery.validator.classRuleSettings.eventRegistrationTypeNameUnique = { eventRegistrationTypeNameUnique: true };
jQuery.validator.addMethod("eventRegistrationFieldValueUnique", function(value, element, option) {
var thisElement = element;
if ($(thisElement).val() == 0)
return true;
var selects = $("select.eventRegistrationFieldValueUnique");
for (var i = selects.length - 1; i >= 0; i--) {
if (selects[i].id != thisElement.id && $(selects[i]).val() === $(thisElement).val())
return false;
}
return true;
}, "Please select a unique value.");
jQuery.validator.classRuleSettings.eventRegistrationFieldValueUnique = { eventRegistrationFieldValueUnique: true };
// Validate that entered Aplos Account ID came back as valid
jQuery.validator.addMethod("aplosAccountIdValid", function (value, element, option) {
var thisElement = element;
return $(thisElement).val() != "" && $(thisElement).data("aplos-valid") === true;
}, "Invalid Account ID");
jQuery.validator.classRuleSettings.aplosAccountIdValid = { aplosAccountIdValid: true };
// Validate that the registration amount is at least $1
jQuery.validator.methods.min1 = function (value, element, param) {
if (typeof (accounting) === "undefined") { // rip out $ and ,
value = (value.toString() || "").replace(/[\$,]/g, "");
}
else { // Use accounting.parse, to handle $ and ,
value = accounting.parse(value);
}
return this.optional(element) || value >= param;
};
jQuery.validator.classRuleSettings.minimum1 = { min1: 1 };
jQuery.validator.messages.min1 = 'Please enter a value of at least {0}.';
// Validate that the given field has not already been added to the same form somewhere else.
// That is, the field must be currently unused.
jQuery.validator.addMethod("unusedField", function (value, element, param) {
for (var i = 0; i < vm.customFields().length; i++) {
if (vm.customFields()[i].customTransactionFieldId() == value)
return false;
}
return true;
}, "This field is already used on this form. Choose another field.");
jQuery.validator.classRuleSettings.unusedField = { unusedField: true };
//Validate that a constituent picker field has at least one constituent for Benevon purposes
jQuery.validator.addMethod("benevonRequiredPicker", function (value, element, param) {
//check that the parent is visible because we only want to validate if Benevon fields are displayed
return $(element).parent().find('ul:visible').length ? $(element).parent().find('ul').children('li:visible').length : true;
}, "This field is required with a Benevon purpose.");
jQuery.validator.classRuleSettings.benevonRequiredPicker = { benevonRequiredPicker: true };
//Validate that a password does not contain '<' or '>' characters
jQuery.validator.addMethod("passwordNoAngleBrackets", function(value, element, options) {
return value.indexOf("<") === -1 && value.indexOf(">") === -1;
}, "Passwords cannot contain '<' or '>'.");
jQuery.validator.classRuleSettings.passwordNoAngleBrackets = { passwordNoAngleBrackets: true };
// Validate no "emoji" or more properly 4 byte characters are used
// get the value and compares to see if more than 3 bytes are used
// https://stackoverflow.com/questions/42710679/single-byte-double-byte-triple-byte-characters-how-to-find-which-one-is-entere
// https://stackoverflow.com/questions/25994001/how-to-calculate-byte-length-containing-utf8-characters-using-javascript
// Why did I use "codePointAt" rather than "charCodeAt"
// https://medium.com/reactnative/emojis-in-javascript-f693d0eb79fb
// Independent test character size
// https://mothereff.in/byte-counter
jQuery.validator.addMethod("disallowEmoji", function (value, element, options) {
var max = (1 << 16);
for (i = 0; i < value.length; i++) {
var char = value.codePointAt(i);
if (char > max) {
return false;
}
}
return true;
}, "Subjects cannot contain emoji.");
jQuery.validator.classRuleSettings.disallowEmoji = { disallowEmoji: true };
// polyfill where the browser does not support codePointAt() (such as ie 11)
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt
if (!String.prototype.codePointAt) {
(function () {
'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
var codePointAt = function (position) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var size = string.length;
// `ToInteger`
var index = position ? Number(position) : 0;
if (index != index) { // better `isNaN`
index = 0;
}
// Account for out-of-bounds indices:
if (index < 0 || index >= size) {
return undefined;
}
// Get the first code unit
var first = string.charCodeAt(index);
var second;
if ( // check if it's the start of a surrogate pair
first >= 0xD800 && first <= 0xDBFF && // high surrogate
size > index + 1 // there is a next code unit
) {
second = string.charCodeAt(index + 1);
if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
// http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
}
}
return first;
};
if (Object.defineProperty) {
Object.defineProperty(String.prototype, 'codePointAt', {
'value': codePointAt,
'configurable': true,
'writable': true
});
} else {
String.prototype.codePointAt = codePointAt;
}
}());
}
const caseSubjectTime = new Date().toISOString();
const initEmbeddedChat = function(databaseName,
gslbBaseURL,
liveAgentServiceUrl,
chatVisitorServiceUrl,
organizationId,
organizationName,
baseLiveAgentContentUrl,
deploymentId,
buttonId,
baseLiveAgentUrl,
eswliveAgentDevName) {
try {
embedded_svc.settings.extraPrechatInfo =
[{
"entityName": "Contact",
"showOnCreate": true,
"linkToEntityName": "Case",
"linkToEntityField": "ContactId",
"saveToTranscript": "Contact",
"entityFieldMaps": [
{
"isExactMatch": false,
"fieldName": "FirstName",
"doCreate": true,
"doFind": false,
"label": "FirstName"
},
{
"isExactMatch": true,
"fieldName": "LastName",
"doCreate": true,
"doFind": true,
"label": "LastName"
},
{
"isExactMatch": true,
"fieldName": "Email",
"doCreate": true,
"doFind": true,
"label": "Email"
}
]
},
{
"entityName": "Case",
"showOnCreate": true,
"saveToTranscript": "Case",
"entityFieldMaps":
[{
"isExactMatch": false,
"fieldName": "Subject",
"doCreate": true,
"doFind": false,
"label": "caseSubject"
},
{
"isExactMatch": false,
"fieldName": "What_can_we_help_you_with__c",
"doCreate": true,
"doFind": false,
"label": "What can we help you with?"
},
{
"isExactMatch": false,
"fieldName": "Origin",
"doCreate": true,
"doFind": false,
"label": "caseOrigin"
},
{
"isExactMatch": false,
"fieldName": "Type",
"doCreate": true,
"doFind": false,
"label": "caseType"
}]
},
{
"entityName": "Account",
"linkToEntityName": "Contact",
"linkToEntityField": "AccountId",
"showOnCreate": false,
"saveToTranscript": "Account",
"entityFieldMaps":
[{
"isExactMatch": true,
"fieldName": "Bloomerang_Database_Name__c",
"doCreate": false,
"doFind": true,
"label": "Bloomerang Database Name"
}]
}];
embedded_svc.settings.extraPrechatFormDetails = [
{
"label": "Bloomerang Database Name",
"value": databaseName,
"transcriptFields": [],
"displayToAgent": true
},
{
"label": "caseSubject",
"value": "Live Chat - " + caseSubjectTime,
"transcriptFields": [],
"displayToAgent": false
},
{
"label": "caseOrigin",
"value": "Chat",
"transcriptFields": [],
"displayToAgent": false
},
{
"label": "caseType",
"value": "Question",
"transcriptFields": [],
"displayToAgent": false
}
];
embedded_svc.settings.displayHelpButton = true; //Or false
embedded_svc.settings.language = 'en-US'; //For example, enter 'en' or 'en-US'
embedded_svc.settings.defaultMinimizedText = 'Chat with Us';
embedded_svc.settings.enabledFeatures = ['LiveAgent'];
embedded_svc.settings.entryFeature = 'LiveAgent';
embedded_svc.init(
liveAgentServiceUrl,
chatVisitorServiceUrl,
gslbBaseURL,
organizationId,
organizationName,
{
baseLiveAgentContentURL: baseLiveAgentContentUrl,
deploymentId: deploymentId,
buttonId: buttonId,
baseLiveAgentURL: baseLiveAgentUrl,
eswLiveAgentDevName: eswliveAgentDevName,
isOfflineSupportEnabled: true
}
);
} catch (err) {
console.error('Error loading Embedded Messaging: ', err);
}
};
const initMessagingForWeb = (salesforceOrganizationId,
salesForceEmbeddedServiceDeploymentName,
salesforceMessagingEndpoint,
salesForceOmniChannelBaseUrl) => {
try {
embeddedservice_bootstrap.settings.language = 'en_US';
embeddedservice_bootstrap.init(
salesforceOrganizationId,
salesForceEmbeddedServiceDeploymentName,
salesforceMessagingEndpoint,
{
scrt2URL: salesForceOmniChannelBaseUrl
}
);
} catch (err) {
console.error('Error loading Embedded Messaging: ', err);
}
};
/**
* @license MIT
* @fileOverview Favico animations
* @author Miroslav Magda, http://blog.ejci.net
* @version 0.3.9
*/
/**
* Create new favico instance
* @param {Object} Options
* @return {Object} Favico object
* @example
* var favico = new Favico({
* bgColor : '#d00',
* textColor : '#fff',
* fontFamily : 'sans-serif',
* fontStyle : 'bold',
* position : 'down',
* type : 'circle',
* animation : 'slide',
* dataUrl: function(url){},
* win: top
* });
*/
(function() {
var Favico = (function(opt) {
'use strict';
opt = (opt) ? opt : {};
var _def = {
bgColor : '#d00',
textColor : '#fff',
fontFamily : 'sans-serif', //Arial,Verdana,Times New Roman,serif,sans-serif,...
fontStyle : 'bold', //normal,italic,oblique,bold,bolder,lighter,100,200,300,400,500,600,700,800,900
type : 'circle',
position : 'down', // down, up, left, leftup (upleft)
animation : 'slide',
elementId : false,
dataUrl : false,
win: window
};
var _opt, _orig, _h, _w, _canvas, _context, _img, _ready, _lastBadge, _running, _readyCb, _stop, _browser, _animTimeout, _drawTimeout, _doc;
_browser = {};
_browser.ff = typeof InstallTrigger != 'undefined';
_browser.chrome = !!window.chrome;
_browser.opera = !!window.opera || navigator.userAgent.indexOf('Opera') >= 0;
_browser.ie = /*@cc_on!@*/false;
_browser.safari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
_browser.supported = (_browser.chrome || _browser.ff || _browser.opera);
var _queue = [];
_readyCb = function() {
};
_ready = _stop = false;
/**
* Initialize favico
*/
var init = function() {
//merge initial options
_opt = merge(_def, opt);
_opt.bgColor = hexToRgb(_opt.bgColor);
_opt.textColor = hexToRgb(_opt.textColor);
_opt.position = _opt.position.toLowerCase();
_opt.animation = (animation.types['' + _opt.animation]) ? _opt.animation : _def.animation;
_doc = _opt.win.document;
var isUp = _opt.position.indexOf('up') > -1;
var isLeft = _opt.position.indexOf('left') > -1;
//transform animation
if (isUp || isLeft) {
for (var i = 0; i < animation.types['' + _opt.animation].length; i++) {
var step = animation.types['' + _opt.animation][i];
if (isUp) {
if (step.y < 0.6) {
step.y = step.y - 0.4;
} else {
step.y = step.y - 2 * step.y + (1 - step.w);
}
}
if (isLeft) {
if (step.x < 0.6) {
step.x = step.x - 0.4;
} else {
step.x = step.x - 2 * step.x + (1 - step.h);
}
}
animation.types['' + _opt.animation][i] = step;
}
}
_opt.type = (type['' + _opt.type]) ? _opt.type : _def.type;
_orig = link.getIcon();
//create temp canvas
_canvas = document.createElement('canvas');
//create temp image
_img = document.createElement('img');
if (_orig.hasAttribute('href')) {
_img.setAttribute('crossOrigin', 'anonymous');
_img.setAttribute('src', _orig.getAttribute('href'));
//get width/height
_img.onload = function() {
_h = (_img.height > 0) ? _img.height : 32;
_w = (_img.width > 0) ? _img.width : 32;
_canvas.height = _h;
_canvas.width = _w;
_context = _canvas.getContext('2d');
icon.ready();
};
} else {
_img.setAttribute('src', '');
_h = 32;
_w = 32;
_img.height = _h;
_img.width = _w;
_canvas.height = _h;
_canvas.width = _w;
_context = _canvas.getContext('2d');
icon.ready();
}
};
/**
* Icon namespace
*/
var icon = {};
/**
* Icon is ready (reset icon) and start animation (if ther is any)
*/
icon.ready = function() {
_ready = true;
icon.reset();
_readyCb();
};
/**
* Reset icon to default state
*/
icon.reset = function() {
//reset
if (!_ready) {
return;
}
_queue = [];
_lastBadge = false;
_running = false;
_context.clearRect(0, 0, _w, _h);
_context.drawImage(_img, 0, 0, _w, _h);
//_stop=true;
link.setIcon(_canvas);
//webcam('stop');
//video('stop');
window.clearTimeout(_animTimeout);
window.clearTimeout(_drawTimeout);
};
/**
* Start animation
*/
icon.start = function() {
if (!_ready || _running) {
return;
}
var finished = function() {
_lastBadge = _queue[0];
_running = false;
if (_queue.length > 0) {
_queue.shift();
icon.start();
} else {
}
};
if (_queue.length > 0) {
_running = true;
var run = function() {
// apply options for this animation
['type', 'animation', 'bgColor', 'textColor', 'fontFamily', 'fontStyle'].forEach(function(a) {
if ( a in _queue[0].options) {
_opt[a] = _queue[0].options[a];
}
});
animation.run(_queue[0].options, function() {
finished();
}, false);
};
if (_lastBadge) {
animation.run(_lastBadge.options, function() {
run();
}, true);
} else {
run();
}
}
};
/**
* Badge types
*/
var type = {};
var options = function(opt) {
opt.n = (( typeof opt.n) === 'number') ? Math.abs(opt.n | 0) : opt.n;
opt.x = _w * opt.x;
opt.y = _h * opt.y;
opt.w = _w * opt.w;
opt.h = _h * opt.h;
opt.len = ("" + opt.n).length;
return opt;
};
/**
* Generate circle
* @param {Object} opt Badge options
*/
type.circle = function(opt) {
opt = options(opt);
var more = false;
if (opt.len === 2) {
opt.x = opt.x - opt.w * 0.4;
opt.w = opt.w * 1.4;
more = true;
} else if (opt.len >= 3) {
opt.x = opt.x - opt.w * 0.65;
opt.w = opt.w * 1.65;
more = true;
}
_context.clearRect(0, 0, _w, _h);
_context.drawImage(_img, 0, 0, _w, _h);
_context.beginPath();
_context.font = _opt.fontStyle + " " + Math.floor(opt.h * (opt.n > 99 ? 0.85 : 1)) + "px " + _opt.fontFamily;
_context.textAlign = 'center';
if (more) {
_context.moveTo(opt.x + opt.w / 2, opt.y);
_context.lineTo(opt.x + opt.w - opt.h / 2, opt.y);
_context.quadraticCurveTo(opt.x + opt.w, opt.y, opt.x + opt.w, opt.y + opt.h / 2);
_context.lineTo(opt.x + opt.w, opt.y + opt.h - opt.h / 2);
_context.quadraticCurveTo(opt.x + opt.w, opt.y + opt.h, opt.x + opt.w - opt.h / 2, opt.y + opt.h);
_context.lineTo(opt.x + opt.h / 2, opt.y + opt.h);
_context.quadraticCurveTo(opt.x, opt.y + opt.h, opt.x, opt.y + opt.h - opt.h / 2);
_context.lineTo(opt.x, opt.y + opt.h / 2);
_context.quadraticCurveTo(opt.x, opt.y, opt.x + opt.h / 2, opt.y);
} else {
_context.arc(opt.x + opt.w / 2, opt.y + opt.h / 2, opt.h / 2, 0, 2 * Math.PI);
}
_context.fillStyle = 'rgba(' + _opt.bgColor.r + ',' + _opt.bgColor.g + ',' + _opt.bgColor.b + ',' + opt.o + ')';
_context.fill();
_context.closePath();
_context.beginPath();
_context.stroke();
_context.fillStyle = 'rgba(' + _opt.textColor.r + ',' + _opt.textColor.g + ',' + _opt.textColor.b + ',' + opt.o + ')';
//_context.fillText((more) ? '9+' : opt.n, Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.15));
if (( typeof opt.n) === 'number' && opt.n > 999) {
_context.fillText(((opt.n > 9999) ? 9 : Math.floor(opt.n / 1000) ) + 'k+', Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.2));
} else {
_context.fillText(opt.n, Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.15));
}
_context.closePath();
};
/**
* Generate rectangle
* @param {Object} opt Badge options
*/
type.rectangle = function(opt) {
opt = options(opt);
var more = false;
if (opt.len === 2) {
opt.x = opt.x - opt.w * 0.4;
opt.w = opt.w * 1.4;
more = true;
} else if (opt.len >= 3) {
opt.x = opt.x - opt.w * 0.65;
opt.w = opt.w * 1.65;
more = true;
}
_context.clearRect(0, 0, _w, _h);
_context.drawImage(_img, 0, 0, _w, _h);
_context.beginPath();
_context.font = _opt.fontStyle + " " + Math.floor(opt.h * (opt.n > 99 ? 0.9 : 1)) + "px " + _opt.fontFamily;
_context.textAlign = 'center';
_context.fillStyle = 'rgba(' + _opt.bgColor.r + ',' + _opt.bgColor.g + ',' + _opt.bgColor.b + ',' + opt.o + ')';
_context.fillRect(opt.x, opt.y, opt.w, opt.h);
_context.fillStyle = 'rgba(' + _opt.textColor.r + ',' + _opt.textColor.g + ',' + _opt.textColor.b + ',' + opt.o + ')';
//_context.fillText((more) ? '9+' : opt.n, Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.15));
if (( typeof opt.n) === 'number' && opt.n > 999) {
_context.fillText(((opt.n > 9999) ? 9 : Math.floor(opt.n / 1000) ) + 'k+', Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.2));
} else {
_context.fillText(opt.n, Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.15));
}
_context.closePath();
};
/**
* Set badge
*/
var badge = function(number, opts) {
opts = (( typeof opts) === 'string' ? {
animation : opts
} : opts) || {};
_readyCb = function() {
try {
if ( typeof (number) === 'number' ? (number > 0) : (number !== '')) {
var q = {
type : 'badge',
options : {
n : number
}
};
if ('animation' in opts && animation.types['' + opts.animation]) {
q.options.animation = '' + opts.animation;
}
if ('type' in opts && type['' + opts.type]) {
q.options.type = '' + opts.type;
}
['bgColor', 'textColor'].forEach(function(o) {
if ( o in opts) {
q.options[o] = hexToRgb(opts[o]);
}
});
['fontStyle', 'fontFamily'].forEach(function(o) {
if ( o in opts) {
q.options[o] = opts[o];
}
});
_queue.push(q);
if (_queue.length > 100) {
throw new Error('Too many badges requests in queue.');
}
icon.start();
} else {
icon.reset();
}
} catch(e) {
throw new Error('Error setting badge. Message: ' + e.message);
}
};
if (_ready) {
_readyCb();
}
};
/**
* Set image as icon
*/
var image = function(imageElement) {
_readyCb = function() {
try {
var w = imageElement.width;
var h = imageElement.height;
var newImg = document.createElement('img');
var ratio = (w / _w < h / _h) ? (w / _w) : (h / _h);
newImg.setAttribute('crossOrigin', 'anonymous');
newImg.setAttribute('src', imageElement.getAttribute('src'));
newImg.height = (h / ratio);
newImg.width = (w / ratio);
_context.clearRect(0, 0, _w, _h);
_context.drawImage(newImg, 0, 0, _w, _h);
link.setIcon(_canvas);
} catch(e) {
throw new Error('Error setting image. Message: ' + e.message);
}
};
if (_ready) {
_readyCb();
}
};
/**
* Set video as icon
*/
var video = function(videoElement) {
_readyCb = function() {
try {
if (videoElement === 'stop') {
_stop = true;
icon.reset();
_stop = false;
return;
}
//var w = videoElement.width;
//var h = videoElement.height;
//var ratio = (w / _w < h / _h) ? (w / _w) : (h / _h);
videoElement.addEventListener('play', function() {
drawVideo(this);
}, false);
} catch(e) {
throw new Error('Error setting video. Message: ' + e.message);
}
};
if (_ready) {
_readyCb();
}
};
/**
* Set video as icon
*/
var webcam = function(action) {
//UR
if (!window.URL || !window.URL.createObjectURL) {
window.URL = window.URL || {};
window.URL.createObjectURL = function(obj) {
return obj;
};
}
if (_browser.supported) {
var newVideo = false;
navigator.getUserMedia = navigator.getUserMedia || navigator.oGetUserMedia || navigator.msGetUserMedia || navigator.mozGetUserMedia || navigator.webkitGetUserMedia;
_readyCb = function() {
try {
if (action === 'stop') {
_stop = true;
icon.reset();
_stop = false;
return;
}
newVideo = document.createElement('video');
newVideo.width = _w;
newVideo.height = _h;
navigator.getUserMedia({
video : true,
audio : false
}, function(stream) {
newVideo.src = URL.createObjectURL(stream);
newVideo.play();
drawVideo(newVideo);
}, function() {
});
} catch(e) {
throw new Error('Error setting webcam. Message: ' + e.message);
}
};
if (_ready) {
_readyCb();
}
}
};
/**
* Draw video to context and repeat :)
*/
function drawVideo(video) {
if (video.paused || video.ended || _stop) {
return false;
}
//nasty hack for FF webcam (Thanks to Julian Ćwirko, kontakt@redsunmedia.pl)
try {
_context.clearRect(0, 0, _w, _h);
_context.drawImage(video, 0, 0, _w, _h);
} catch(e) {
}
_drawTimeout = setTimeout(function() {
drawVideo(video);
}, animation.duration);
link.setIcon(_canvas);
}
var link = {};
/**
* Get icon from HEAD tag or create a new element
*/
link.getIcon = function() {
var elm = false;
//get link element
var getLink = function() {
var link = _doc.getElementsByTagName('head')[0].getElementsByTagName('link');
for (var l = link.length, i = (l - 1); i >= 0; i--) {
if ((/(^|\s)icon(\s|$)/i).test(link[i].getAttribute('rel'))) {
return link[i];
}
}
return false;
};
if (_opt.element) {
elm = _opt.element;
} else if (_opt.elementId) {
//if img element identified by elementId
elm = _doc.getElementById(_opt.elementId);
elm.setAttribute('href', elm.getAttribute('src'));
} else {
//if link element
elm = getLink();
if (elm === false) {
elm = _doc.createElement('link');
elm.setAttribute('rel', 'icon');
_doc.getElementsByTagName('head')[0].appendChild(elm);
}
}
elm.setAttribute('type', 'image/png');
return elm;
};
link.setIcon = function(canvas) {
var url = canvas.toDataURL('image/png');
if (_opt.dataUrl) {
//if using custom exporter
_opt.dataUrl(url);
}
if (_opt.element) {
_opt.element.setAttribute('href', url);
_opt.element.setAttribute('src', url);
} else if (_opt.elementId) {
//if is attached to element (image)
var elm = _doc.getElementById(_opt.elementId);
elm.setAttribute('href', url);
elm.setAttribute('src', url);
} else {
//if is attached to fav icon
if (_browser.ff || _browser.opera) {
//for FF we need to "recreate" element, atach to dom and remove old
//var originalType = _orig.getAttribute('rel');
var old = _orig;
_orig = _doc.createElement('link');
//_orig.setAttribute('rel', originalType);
if (_browser.opera) {
_orig.setAttribute('rel', 'icon');
}
_orig.setAttribute('rel', 'icon');
_orig.setAttribute('type', 'image/png');
_doc.getElementsByTagName('head')[0].appendChild(_orig);
_orig.setAttribute('href', url);
if (old.parentNode) {
old.parentNode.removeChild(old);
}
} else {
_orig.setAttribute('href', url);
}
}
};
//http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb#answer-5624139
//HEX to RGB convertor
function hexToRgb(hex) {
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r : parseInt(result[1], 16),
g : parseInt(result[2], 16),
b : parseInt(result[3], 16)
} : false;
}
/**
* Merge options
*/
function merge(def, opt) {
var mergedOpt = {};
var attrname;
for (attrname in def) {
mergedOpt[attrname] = def[attrname];
}
for (attrname in opt) {
mergedOpt[attrname] = opt[attrname];
}
return mergedOpt;
}
/**
* Cross-browser page visibility shim
* http://stackoverflow.com/questions/12536562/detect-whether-a-window-is-visible
*/
function isPageHidden() {
return _doc.hidden || _doc.msHidden || _doc.webkitHidden || _doc.mozHidden;
}
/**
* @namespace animation
*/
var animation = {};
/**
* Animation "frame" duration
*/
animation.duration = 40;
/**
* Animation types (none,fade,pop,slide)
*/
animation.types = {};
animation.types.fade = [{
x : 0.4,
y : 0.4,
w : 0.6,
h : 0.6,
o : 0.0
}, {
x : 0.4,
y : 0.4,
w : 0.6,
h : 0.6,
o : 0.1
}, {
x : 0.4,
y : 0.4,
w : 0.6,
h : 0.6,
o : 0.2
}, {
x : 0.4,
y : 0.4,
w : 0.6,
h : 0.6,
o : 0.3
}, {
x : 0.4,
y : 0.4,
w : 0.6,
h : 0.6,
o : 0.4
}, {
x : 0.4,
y : 0.4,
w : 0.6,
h : 0.6,
o : 0.5
}, {
x : 0.4,
y : 0.4,
w : 0.6,
h : 0.6,
o : 0.6
}, {
x : 0.4,
y : 0.4,
w : 0.6,
h : 0.6,
o : 0.7
}, {
x : 0.4,
y : 0.4,
w : 0.6,
h : 0.6,
o : 0.8
}, {
x : 0.4,
y : 0.4,
w : 0.6,
h : 0.6,
o : 0.9
}, {
x : 0.4,
y : 0.4,
w : 0.6,
h : 0.6,
o : 1.0
}];
animation.types.none = [{
x : 0.4,
y : 0.4,
w : 0.6,
h : 0.6,
o : 1
}];
animation.types.pop = [{
x : 1,
y : 1,
w : 0,
h : 0,
o : 1
}, {
x : 0.9,
y : 0.9,
w : 0.1,
h : 0.1,
o : 1
}, {
x : 0.8,
y : 0.8,
w : 0.2,
h : 0.2,
o : 1
}, {
x : 0.7,
y : 0.7,
w : 0.3,
h : 0.3,
o : 1
}, {
x : 0.6,
y : 0.6,
w : 0.4,
h : 0.4,
o : 1
}, {
x : 0.5,
y : 0.5,
w : 0.5,
h : 0.5,
o : 1
}, {
x : 0.4,
y : 0.4,
w : 0.6,
h : 0.6,
o : 1
}];
animation.types.popFade = [{
x : 0.75,
y : 0.75,
w : 0,
h : 0,
o : 0
}, {
x : 0.65,
y : 0.65,
w : 0.1,
h : 0.1,
o : 0.2
}, {
x : 0.6,
y : 0.6,
w : 0.2,
h : 0.2,
o : 0.4
}, {
x : 0.55,
y : 0.55,
w : 0.3,
h : 0.3,
o : 0.6
}, {
x : 0.50,
y : 0.50,
w : 0.4,
h : 0.4,
o : 0.8
}, {
x : 0.45,
y : 0.45,
w : 0.5,
h : 0.5,
o : 0.9
}, {
x : 0.4,
y : 0.4,
w : 0.6,
h : 0.6,
o : 1
}];
animation.types.slide = [{
x : 0.4,
y : 1,
w : 0.6,
h : 0.6,
o : 1
}, {
x : 0.4,
y : 0.9,
w : 0.6,
h : 0.6,
o : 1
}, {
x : 0.4,
y : 0.9,
w : 0.6,
h : 0.6,
o : 1
}, {
x : 0.4,
y : 0.8,
w : 0.6,
h : 0.6,
o : 1
}, {
x : 0.4,
y : 0.7,
w : 0.6,
h : 0.6,
o : 1
}, {
x : 0.4,
y : 0.6,
w : 0.6,
h : 0.6,
o : 1
}, {
x : 0.4,
y : 0.5,
w : 0.6,
h : 0.6,
o : 1
}, {
x : 0.4,
y : 0.4,
w : 0.6,
h : 0.6,
o : 1
}];
/**
* Run animation
* @param {Object} opt Animation options
* @param {Object} cb Callabak after all steps are done
* @param {Object} revert Reverse order? true|false
* @param {Object} step Optional step number (frame bumber)
*/
animation.run = function(opt, cb, revert, step) {
var animationType = animation.types[isPageHidden() ? 'none' : _opt.animation];
if (revert === true) {
step = ( typeof step !== 'undefined') ? step : animationType.length - 1;
} else {
step = ( typeof step !== 'undefined') ? step : 0;
}
cb = (cb) ? cb : function() {
};
if ((step < animationType.length) && (step >= 0)) {
type[_opt.type](merge(opt, animationType[step]));
_animTimeout = setTimeout(function() {
if (revert) {
step = step - 1;
} else {
step = step + 1;
}
animation.run(opt, cb, revert, step);
}, animation.duration);
link.setIcon(_canvas);
} else {
cb();
return;
}
};
//auto init
init();
return {
badge : badge,
video : video,
image : image,
webcam : webcam,
reset : icon.reset,
browser : {
supported : _browser.supported
}
};
});
// AMD / RequireJS
if ( typeof define !== 'undefined' && define.amd) {
define([], function() {
return Favico;
});
}
// CommonJS
else if ( typeof module !== 'undefined' && module.exports) {
module.exports = Favico;
}
// included directly via