Your IP : 52.15.236.223
/* Prototype JavaScript framework, version 1.7
* (c) 2005-2010 Sam Stephenson
*
* Prototype is freely distributable under the terms of an MIT-style license.
* For details, see the Prototype web site: http://www.prototypejs.org/
*
*--------------------------------------------------------------------------*/
var Prototype = {
Version: '1.7',
Browser: (function(){
var ua = navigator.userAgent;
var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]';
return {
IE: !!window.attachEvent && !isOpera,
Opera: isOpera,
WebKit: ua.indexOf('AppleWebKit/') > -1,
Gecko: ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') === -1,
MobileSafari: /Apple.*Mobile/.test(ua)
}
})(),
BrowserFeatures: {
XPath: !!document.evaluate,
SelectorsAPI: !!document.querySelector,
ElementExtensions: (function() {
var constructor = window.Element || window.HTMLElement;
return !!(constructor && constructor.prototype);
})(),
SpecificElementExtensions: (function() {
if (typeof window.HTMLDivElement !== 'undefined')
return true;
var div = document.createElement('div'),
form = document.createElement('form'),
isSupported = false;
if (div['__proto__'] && (div['__proto__'] !== form['__proto__'])) {
isSupported = true;
}
div = form = null;
return isSupported;
})()
},
ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
emptyFunction: function() { },
K: function(x) { return x }
};
if (Prototype.Browser.MobileSafari)
Prototype.BrowserFeatures.SpecificElementExtensions = false;
var Abstract = { };
var Try = {
these: function() {
var returnValue;
for (var i = 0, length = arguments.length; i < length; i++) {
var lambda = arguments[i];
try {
returnValue = lambda();
break;
} catch (e) { }
}
return returnValue;
}
};
/* Based on Alex Arnell's inheritance implementation. */
var Class = (function() {
var IS_DONTENUM_BUGGY = (function(){
for (var p in { toString: 1 }) {
if (p === 'toString') return false;
}
return true;
})();
function subclass() {};
function create() {
var parent = null, properties = $A(arguments);
if (Object.isFunction(properties[0]))
parent = properties.shift();
function klass() {
this.initialize.apply(this, arguments);
}
Object.extend(klass, Class.Methods);
klass.superclass = parent;
klass.subclasses = [];
if (parent) {
subclass.prototype = parent.prototype;
klass.prototype = new subclass;
parent.subclasses.push(klass);
}
for (var i = 0, length = properties.length; i < length; i++)
klass.addMethods(properties[i]);
if (!klass.prototype.initialize)
klass.prototype.initialize = Prototype.emptyFunction;
klass.prototype.constructor = klass;
return klass;
}
function addMethods(source) {
var ancestor = this.superclass && this.superclass.prototype,
properties = Object.keys(source);
if (IS_DONTENUM_BUGGY) {
if (source.toString != Object.prototype.toString)
properties.push("toString");
if (source.valueOf != Object.prototype.valueOf)
properties.push("valueOf");
}
for (var i = 0, length = properties.length; i < length; i++) {
var property = properties[i], value = source[property];
if (ancestor && Object.isFunction(value) &&
value.argumentNames()[0] == "$super") {
var method = value;
value = (function(m) {
return function() { return ancestor[m].apply(this, arguments); };
})(property).wrap(method);
value.valueOf = method.valueOf.bind(method);
value.toString = method.toString.bind(method);
}
this.prototype[property] = value;
}
return this;
}
return {
create: create,
Methods: {
addMethods: addMethods
}
};
})();
(function() {
var _toString = Object.prototype.toString,
NULL_TYPE = 'Null',
UNDEFINED_TYPE = 'Undefined',
BOOLEAN_TYPE = 'Boolean',
NUMBER_TYPE = 'Number',
STRING_TYPE = 'String',
OBJECT_TYPE = 'Object',
FUNCTION_CLASS = '[object Function]',
BOOLEAN_CLASS = '[object Boolean]',
NUMBER_CLASS = '[object Number]',
STRING_CLASS = '[object String]',
ARRAY_CLASS = '[object Array]',
DATE_CLASS = '[object Date]',
NATIVE_JSON_STRINGIFY_SUPPORT = window.JSON &&
typeof JSON.stringify === 'function' &&
JSON.stringify(0) === '0' &&
typeof JSON.stringify(Prototype.K) === 'undefined';
function Type(o) {
switch(o) {
case null: return NULL_TYPE;
case (void 0): return UNDEFINED_TYPE;
}
var type = typeof o;
switch(type) {
case 'boolean': return BOOLEAN_TYPE;
case 'number': return NUMBER_TYPE;
case 'string': return STRING_TYPE;
}
return OBJECT_TYPE;
}
function extend(destination, source) {
for (var property in source)
destination[property] = source[property];
return destination;
}
function inspect(object) {
try {
if (isUndefined(object)) return 'undefined';
if (object === null) return 'null';
return object.inspect ? object.inspect() : String(object);
} catch (e) {
if (e instanceof RangeError) return '...';
throw e;
}
}
function toJSON(value) {
return Str('', { '': value }, []);
}
function Str(key, holder, stack) {
var value = holder[key],
type = typeof value;
if (Type(value) === OBJECT_TYPE && typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
var _class = _toString.call(value);
switch (_class) {
case NUMBER_CLASS:
case BOOLEAN_CLASS:
case STRING_CLASS:
value = value.valueOf();
}
switch (value) {
case null: return 'null';
case true: return 'true';
case false: return 'false';
}
type = typeof value;
switch (type) {
case 'string':
return value.inspect(true);
case 'number':
return isFinite(value) ? String(value) : 'null';
case 'object':
for (var i = 0, length = stack.length; i < length; i++) {
if (stack[i] === value) { throw new TypeError(); }
}
stack.push(value);
var partial = [];
if (_class === ARRAY_CLASS) {
for (var i = 0, length = value.length; i < length; i++) {
var str = Str(i, value, stack);
partial.push(typeof str === 'undefined' ? 'null' : str);
}
partial = '[' + partial.join(',') + ']';
} else {
var keys = Object.keys(value);
for (var i = 0, length = keys.length; i < length; i++) {
var key = keys[i], str = Str(key, value, stack);
if (typeof str !== "undefined") {
partial.push(key.inspect(true)+ ':' + str);
}
}
partial = '{' + partial.join(',') + '}';
}
stack.pop();
return partial;
}
}
function stringify(object) {
return JSON.stringify(object);
}
function toQueryString(object) {
return $H(object).toQueryString();
}
function toHTML(object) {
return object && object.toHTML ? object.toHTML() : String.interpret(object);
}
function keys(object) {
if (Type(object) !== OBJECT_TYPE) { throw new TypeError(); }
var results = [];
for (var property in object) {
if (object.hasOwnProperty(property)) {
results.push(property);
}
}
return results;
}
function values(object) {
var results = [];
for (var property in object)
results.push(object[property]);
return results;
}
function clone(object) {
return extend({ }, object);
}
function isElement(object) {
return !!(object && object.nodeType == 1);
}
function isArray(object) {
return _toString.call(object) === ARRAY_CLASS;
}
var hasNativeIsArray = (typeof Array.isArray == 'function')
&& Array.isArray([]) && !Array.isArray({});
if (hasNativeIsArray) {
isArray = Array.isArray;
}
function isHash(object) {
return object instanceof Hash;
}
function isFunction(object) {
return _toString.call(object) === FUNCTION_CLASS;
}
function isString(object) {
return _toString.call(object) === STRING_CLASS;
}
function isNumber(object) {
return _toString.call(object) === NUMBER_CLASS;
}
function isDate(object) {
return _toString.call(object) === DATE_CLASS;
}
function isUndefined(object) {
return typeof object === "undefined";
}
extend(Object, {
extend: extend,
inspect: inspect,
toJSON: NATIVE_JSON_STRINGIFY_SUPPORT ? stringify : toJSON,
toQueryString: toQueryString,
toHTML: toHTML,
keys: Object.keys || keys,
values: values,
clone: clone,
isElement: isElement,
isArray: isArray,
isHash: isHash,
isFunction: isFunction,
isString: isString,
isNumber: isNumber,
isDate: isDate,
isUndefined: isUndefined
});
})();
Object.extend(Function.prototype, (function() {
var slice = Array.prototype.slice;
function update(array, args) {
var arrayLength = array.length, length = args.length;
while (length--) array[arrayLength + length] = args[length];
return array;
}
function merge(array, args) {
array = slice.call(array, 0);
return update(array, args);
}
function argumentNames() {
var names = this.toString().match(/^[\s\(]*function[^(]*\(([^)]*)\)/)[1]
.replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, '')
.replace(/\s+/g, '').split(',');
return names.length == 1 && !names[0] ? [] : names;
}
function bind(context) {
if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
var __method = this, args = slice.call(arguments, 1);
return function() {
var a = merge(args, arguments);
return __method.apply(context, a);
}
}
function bindAsEventListener(context) {
var __method = this, args = slice.call(arguments, 1);
return function(event) {
var a = update([event || window.event], args);
return __method.apply(context, a);
}
}
function curry() {
if (!arguments.length) return this;
var __method = this, args = slice.call(arguments, 0);
return function() {
var a = merge(args, arguments);
return __method.apply(this, a);
}
}
function delay(timeout) {
var __method = this, args = slice.call(arguments, 1);
timeout = timeout * 1000;
return window.setTimeout(function() {
return __method.apply(__method, args);
}, timeout);
}
function defer() {
var args = update([0.01], arguments);
return this.delay.apply(this, args);
}
function wrap(wrapper) {
var __method = this;
return function() {
var a = update([__method.bind(this)], arguments);
return wrapper.apply(this, a);
}
}
function methodize() {
if (this._methodized) return this._methodized;
var __method = this;
return this._methodized = function() {
var a = update([this], arguments);
return __method.apply(null, a);
};
}
return {
argumentNames: argumentNames,
bind: bind,
bindAsEventListener: bindAsEventListener,
curry: curry,
delay: delay,
defer: defer,
wrap: wrap,
methodize: methodize
}
})());
(function(proto) {
function toISOString() {
return this.getUTCFullYear() + '-' +
(this.getUTCMonth() + 1).toPaddedString(2) + '-' +
this.getUTCDate().toPaddedString(2) + 'T' +
this.getUTCHours().toPaddedString(2) + ':' +
this.getUTCMinutes().toPaddedString(2) + ':' +
this.getUTCSeconds().toPaddedString(2) + 'Z';
}
function toJSON() {
return this.toISOString();
}
if (!proto.toISOString) proto.toISOString = toISOString;
if (!proto.toJSON) proto.toJSON = toJSON;
})(Date.prototype);
RegExp.prototype.match = RegExp.prototype.test;
RegExp.escape = function(str) {
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
var PeriodicalExecuter = Class.create({
initialize: function(callback, frequency) {
this.callback = callback;
this.frequency = frequency;
this.currentlyExecuting = false;
this.registerCallback();
},
registerCallback: function() {
this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
},
execute: function() {
this.callback(this);
},
stop: function() {
if (!this.timer) return;
clearInterval(this.timer);
this.timer = null;
},
onTimerEvent: function() {
if (!this.currentlyExecuting) {
try {
this.currentlyExecuting = true;
this.execute();
this.currentlyExecuting = false;
} catch(e) {
this.currentlyExecuting = false;
throw e;
}
}
}
});
Object.extend(String, {
interpret: function(value) {
return value == null ? '' : String(value);
},
specialChar: {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'\\': '\\\\'
}
});
Object.extend(String.prototype, (function() {
var NATIVE_JSON_PARSE_SUPPORT = window.JSON &&
typeof JSON.parse === 'function' &&
JSON.parse('{"test": true}').test;
function prepareReplacement(replacement) {
if (Object.isFunction(replacement)) return replacement;
var template = new Template(replacement);
return function(match) { return template.evaluate(match) };
}
function gsub(pattern, replacement) {
var result = '', source = this, match;
replacement = prepareReplacement(replacement);
if (Object.isString(pattern))
pattern = RegExp.escape(pattern);
if (!(pattern.length || pattern.source)) {
replacement = replacement('');
return replacement + source.split('').join(replacement) + replacement;
}
while (source.length > 0) {
if (match = source.match(pattern)) {
result += source.slice(0, match.index);
result += String.interpret(replacement(match));
source = source.slice(match.index + match[0].length);
} else {
result += source, source = '';
}
}
return result;
}
function sub(pattern, replacement, count) {
replacement = prepareReplacement(replacement);
count = Object.isUndefined(count) ? 1 : count;
return this.gsub(pattern, function(match) {
if (--count < 0) return match[0];
return replacement(match);
});
}
function scan(pattern, iterator) {
this.gsub(pattern, iterator);
return String(this);
}
function truncate(length, truncation) {
length = length || 30;
truncation = Object.isUndefined(truncation) ? '...' : truncation;
return this.length > length ?
this.slice(0, length - truncation.length) + truncation : String(this);
}
function strip() {
return this.replace(/^\s+/, '').replace(/\s+$/, '');
}
function stripTags() {
return this.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi, '');
}
function stripScripts() {
return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
}
function extractScripts() {
var matchAll = new RegExp(Prototype.ScriptFragment, 'img'),
matchOne = new RegExp(Prototype.ScriptFragment, 'im');
return (this.match(matchAll) || []).map(function(scriptTag) {
return (scriptTag.match(matchOne) || ['', ''])[1];
});
}
function evalScripts() {
return this.extractScripts().map(function(script) { return eval(script) });
}
function escapeHTML() {
return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
function unescapeHTML() {
return this.stripTags().replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');
}
function toQueryParams(separator) {
var match = this.strip().match(/([^?#]*)(#.*)?$/);
if (!match) return { };
return match[1].split(separator || '&').inject({ }, function(hash, pair) {
if ((pair = pair.split('='))[0]) {
var key = decodeURIComponent(pair.shift()),
value = pair.length > 1 ? pair.join('=') : pair[0];
if (value != undefined) value = decodeURIComponent(value);
if (key in hash) {
if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
hash[key].push(value);
}
else hash[key] = value;
}
return hash;
});
}
function toArray() {
return this.split('');
}
function succ() {
return this.slice(0, this.length - 1) +
String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
}
function times(count) {
return count < 1 ? '' : new Array(count + 1).join(this);
}
function camelize() {
return this.replace(/-+(.)?/g, function(match, chr) {
return chr ? chr.toUpperCase() : '';
});
}
function capitalize() {
return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
}
function underscore() {
return this.replace(/::/g, '/')
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
.replace(/([a-z\d])([A-Z])/g, '$1_$2')
.replace(/-/g, '_')
.toLowerCase();
}
function dasherize() {
return this.replace(/_/g, '-');
}
function inspect(useDoubleQuotes) {
var escapedString = this.replace(/[\x00-\x1f\\]/g, function(character) {
if (character in String.specialChar) {
return String.specialChar[character];
}
return '\\u00' + character.charCodeAt().toPaddedString(2, 16);
});
if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
return "'" + escapedString.replace(/'/g, '\\\'') + "'";
}
function unfilterJSON(filter) {
return this.replace(filter || Prototype.JSONFilter, '$1');
}
function isJSON() {
var str = this;
if (str.blank()) return false;
str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@');
str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
return (/^[\],:{}\s]*$/).test(str);
}
function evalJSON(sanitize) {
var json = this.unfilterJSON(),
cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
if (cx.test(json)) {
json = json.replace(cx, function (a) {
return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
try {
if (!sanitize || json.isJSON()) return eval('(' + json + ')');
} catch (e) { }
throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
}
function parseJSON() {
var json = this.unfilterJSON();
return JSON.parse(json);
}
function include(pattern) {
return this.indexOf(pattern) > -1;
}
function startsWith(pattern) {
return this.lastIndexOf(pattern, 0) === 0;
}
function endsWith(pattern) {
var d = this.length - pattern.length;
return d >= 0 && this.indexOf(pattern, d) === d;
}
function empty() {
return this == '';
}
function blank() {
return /^\s*$/.test(this);
}
function interpolate(object, pattern) {
return new Template(this, pattern).evaluate(object);
}
return {
gsub: gsub,
sub: sub,
scan: scan,
truncate: truncate,
strip: String.prototype.trim || strip,
stripTags: stripTags,
stripScripts: stripScripts,
extractScripts: extractScripts,
evalScripts: evalScripts,
escapeHTML: escapeHTML,
unescapeHTML: unescapeHTML,
toQueryParams: toQueryParams,
parseQuery: toQueryParams,
toArray: toArray,
succ: succ,
times: times,
camelize: camelize,
capitalize: capitalize,
underscore: underscore,
dasherize: dasherize,
inspect: inspect,
unfilterJSON: unfilterJSON,
isJSON: isJSON,
evalJSON: NATIVE_JSON_PARSE_SUPPORT ? parseJSON : evalJSON,
include: include,
startsWith: startsWith,
endsWith: endsWith,
empty: empty,
blank: blank,
interpolate: interpolate
};
})());
var Template = Class.create({
initialize: function(template, pattern) {
this.template = template.toString();
this.pattern = pattern || Template.Pattern;
},
evaluate: function(object) {
if (object && Object.isFunction(object.toTemplateReplacements))
object = object.toTemplateReplacements();
return this.template.gsub(this.pattern, function(match) {
if (object == null) return (match[1] + '');
var before = match[1] || '';
if (before == '\\') return match[2];
var ctx = object, expr = match[3],
pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
match = pattern.exec(expr);
if (match == null) return before;
while (match != null) {
var comp = match[1].startsWith('[') ? match[2].replace(/\\\\]/g, ']') : match[1];
ctx = ctx[comp];
if (null == ctx || '' == match[3]) break;
expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
match = pattern.exec(expr);
}
return before + String.interpret(ctx);
});
}
});
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
var $break = { };
var Enumerable = (function() {
function each(iterator, context) {
var index = 0;
try {
this._each(function(value) {
iterator.call(context, value, index++);
});
} catch (e) {
if (e != $break) throw e;
}
return this;
}
function eachSlice(number, iterator, context) {
var index = -number, slices = [], array = this.toArray();
if (number < 1) return array;
while ((index += number) < array.length)
slices.push(array.slice(index, index+number));
return slices.collect(iterator, context);
}
function all(iterator, context) {
iterator = iterator || Prototype.K;
var result = true;
this.each(function(value, index) {
result = result && !!iterator.call(context, value, index);
if (!result) throw $break;
});
return result;
}
function any(iterator, context) {
iterator = iterator || Prototype.K;
var result = false;
this.each(function(value, index) {
if (result = !!iterator.call(context, value, index))
throw $break;
});
return result;
}
function collect(iterator, context) {
iterator = iterator || Prototype.K;
var results = [];
this.each(function(value, index) {
results.push(iterator.call(context, value, index));
});
return results;
}
function detect(iterator, context) {
var result;
this.each(function(value, index) {
if (iterator.call(context, value, index)) {
result = value;
throw $break;
}
});
return result;
}
function findAll(iterator, context) {
var results = [];
this.each(function(value, index) {
if (iterator.call(context, value, index))
results.push(value);
});
return results;
}
function grep(filter, iterator, context) {
iterator = iterator || Prototype.K;
var results = [];
if (Object.isString(filter))
filter = new RegExp(RegExp.escape(filter));
this.each(function(value, index) {
if (filter.match(value))
results.push(iterator.call(context, value, index));
});
return results;
}
function include(object) {
if (Object.isFunction(this.indexOf))
if (this.indexOf(object) != -1) return true;
var found = false;
this.each(function(value) {
if (value == object) {
found = true;
throw $break;
}
});
return found;
}
function inGroupsOf(number, fillWith) {
fillWith = Object.isUndefined(fillWith) ? null : fillWith;
return this.eachSlice(number, function(slice) {
while(slice.length < number) slice.push(fillWith);
return slice;
});
}
function inject(memo, iterator, context) {
this.each(function(value, index) {
memo = iterator.call(context, memo, value, index);
});
return memo;
}
function invoke(method) {
var args = $A(arguments).slice(1);
return this.map(function(value) {
return value[method].apply(value, args);
});
}
function max(iterator, context) {
iterator = iterator || Prototype.K;
var result;
this.each(function(value, index) {
value = iterator.call(context, value, index);
if (result == null || value >= result)
result = value;
});
return result;
}
function min(iterator, context) {
iterator = iterator || Prototype.K;
var result;
this.each(function(value, index) {
value = iterator.call(context, value, index);
if (result == null || value < result)
result = value;
});
return result;
}
function partition(iterator, context) {
iterator = iterator || Prototype.K;
var trues = [], falses = [];
this.each(function(value, index) {
(iterator.call(context, value, index) ?
trues : falses).push(value);
});
return [trues, falses];
}
function pluck(property) {
var results = [];
this.each(function(value) {
results.push(value[property]);
});
return results;
}
function reject(iterator, context) {
var results = [];
this.each(function(value, index) {
if (!iterator.call(context, value, index))
results.push(value);
});
return results;
}
function sortBy(iterator, context) {
return this.map(function(value, index) {
return {
value: value,
criteria: iterator.call(context, value, index)
};
}).sort(function(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}).pluck('value');
}
function toArray() {
return this.map();
}
function zip() {
var iterator = Prototype.K, args = $A(arguments);
if (Object.isFunction(args.last()))
iterator = args.pop();
var collections = [this].concat(args).map($A);
return this.map(function(value, index) {
return iterator(collections.pluck(index));
});
}
function size() {
return this.toArray().length;
}
function inspect() {
return '#<Enumerable:' + this.toArray().inspect() + '>';
}
return {
each: each,
eachSlice: eachSlice,
all: all,
every: all,
any: any,
some: any,
collect: collect,
map: collect,
detect: detect,
findAll: findAll,
select: findAll,
filter: findAll,
grep: grep,
include: include,
member: include,
inGroupsOf: inGroupsOf,
inject: inject,
invoke: invoke,
max: max,
min: min,
partition: partition,
pluck: pluck,
reject: reject,
sortBy: sortBy,
toArray: toArray,
entries: toArray,
zip: zip,
size: size,
inspect: inspect,
find: detect
};
})();
function $A(iterable) {
if (!iterable) return [];
if ('toArray' in Object(iterable)) return iterable.toArray();
var length = iterable.length || 0, results = new Array(length);
while (length--) results[length] = iterable[length];
return results;
}
function $w(string) {
if (!Object.isString(string)) return [];
string = string.strip();
return string ? string.split(/\s+/) : [];
}
Array.from = $A;
(function() {
var arrayProto = Array.prototype,
slice = arrayProto.slice,
_each = arrayProto.forEach; // use native browser JS 1.6 implementation if available
function each(iterator, context) {
for (var i = 0, length = this.length >>> 0; i < length; i++) {
if (i in this) iterator.call(context, this[i], i, this);
}
}
if (!_each) _each = each;
function clear() {
this.length = 0;
return this;
}
function first() {
return this[0];
}
function last() {
return this[this.length - 1];
}
function compact() {
return this.select(function(value) {
return value != null;
});
}
function flatten() {
return this.inject([], function(array, value) {
if (Object.isArray(value))
return array.concat(value.flatten());
array.push(value);
return array;
});
}
function without() {
var values = slice.call(arguments, 0);
return this.select(function(value) {
return !values.include(value);
});
}
function reverse(inline) {
return (inline === false ? this.toArray() : this)._reverse();
}
function uniq(sorted) {
return this.inject([], function(array, value, index) {
if (0 == index || (sorted ? array.last() != value : !array.include(value)))
array.push(value);
return array;
});
}
function intersect(array) {
return this.uniq().findAll(function(item) {
return array.detect(function(value) { return item === value });
});
}
function clone() {
return slice.call(this, 0);
}
function size() {
return this.length;
}
function inspect() {
return '[' + this.map(Object.inspect).join(', ') + ']';
}
function indexOf(item, i) {
i || (i = 0);
var length = this.length;
if (i < 0) i = length + i;
for (; i < length; i++)
if (this[i] === item) return i;
return -1;
}
function lastIndexOf(item, i) {
i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
var n = this.slice(0, i).reverse().indexOf(item);
return (n < 0) ? n : i - n - 1;
}
function concat() {
var array = slice.call(this, 0), item;
for (var i = 0, length = arguments.length; i < length; i++) {
item = arguments[i];
if (Object.isArray(item) && !('callee' in item)) {
for (var j = 0, arrayLength = item.length; j < arrayLength; j++)
array.push(item[j]);
} else {
array.push(item);
}
}
return array;
}
Object.extend(arrayProto, Enumerable);
if (!arrayProto._reverse)
arrayProto._reverse = arrayProto.reverse;
Object.extend(arrayProto, {
_each: _each,
clear: clear,
first: first,
last: last,
compact: compact,
flatten: flatten,
without: without,
reverse: reverse,
uniq: uniq,
intersect: intersect,
clone: clone,
toArray: clone,
size: size,
inspect: inspect
});
var CONCAT_ARGUMENTS_BUGGY = (function() {
return [].concat(arguments)[0][0] !== 1;
})(1,2)
if (CONCAT_ARGUMENTS_BUGGY) arrayProto.concat = concat;
if (!arrayProto.indexOf) arrayProto.indexOf = indexOf;
if (!arrayProto.lastIndexOf) arrayProto.lastIndexOf = lastIndexOf;
})();
function $H(object) {
return new Hash(object);
};
var Hash = Class.create(Enumerable, (function() {
function initialize(object) {
this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
}
function _each(iterator) {
for (var key in this._object) {
var value = this._object[key], pair = [key, value];
pair.key = key;
pair.value = value;
iterator(pair);
}
}
function set(key, value) {
return this._object[key] = value;
}
function get(key) {
if (this._object[key] !== Object.prototype[key])
return this._object[key];
}
function unset(key) {
var value = this._object[key];
delete this._object[key];
return value;
}
function toObject() {
return Object.clone(this._object);
}
function keys() {
return this.pluck('key');
}
function values() {
return this.pluck('value');
}
function index(value) {
var match = this.detect(function(pair) {
return pair.value === value;
});
return match && match.key;
}
function merge(object) {
return this.clone().update(object);
}
function update(object) {
return new Hash(object).inject(this, function(result, pair) {
result.set(pair.key, pair.value);
return result;
});
}
function toQueryPair(key, value) {
if (Object.isUndefined(value)) return key;
return key + '=' + encodeURIComponent(String.interpret(value));
}
function toQueryString() {
return this.inject([], function(results, pair) {
var key = encodeURIComponent(pair.key), values = pair.value;
if (values && typeof values == 'object') {
if (Object.isArray(values)) {
var queryValues = [];
for (var i = 0, len = values.length, value; i < len; i++) {
value = values[i];
queryValues.push(toQueryPair(key, value));
}
return results.concat(queryValues);
}
} else results.push(toQueryPair(key, values));
return results;
}).join('&');
}
function inspect() {
return '#<Hash:{' + this.map(function(pair) {
return pair.map(Object.inspect).join(': ');
}).join(', ') + '}>';
}
function clone() {
return new Hash(this);
}
return {
initialize: initialize,
_each: _each,
set: set,
get: get,
unset: unset,
toObject: toObject,
toTemplateReplacements: toObject,
keys: keys,
values: values,
index: index,
merge: merge,
update: update,
toQueryString: toQueryString,
inspect: inspect,
toJSON: toObject,
clone: clone
};
})());
Hash.from = $H;
Object.extend(Number.prototype, (function() {
function toColorPart() {
return this.toPaddedString(2, 16);
}
function succ() {
return this + 1;
}
function times(iterator, context) {
$R(0, this, true).each(iterator, context);
return this;
}
function toPaddedString(length, radix) {
var string = this.toString(radix || 10);
return '0'.times(length - string.length) + string;
}
function abs() {
return Math.abs(this);
}
function round() {
return Math.round(this);
}
function ceil() {
return Math.ceil(this);
}
function floor() {
return Math.floor(this);
}
return {
toColorPart: toColorPart,
succ: succ,
times: times,
toPaddedString: toPaddedString,
abs: abs,
round: round,
ceil: ceil,
floor: floor
};
})());
function $R(start, end, exclusive) {
return new ObjectRange(start, end, exclusive);
}
var ObjectRange = Class.create(Enumerable, (function() {
function initialize(start, end, exclusive) {
this.start = start;
this.end = end;
this.exclusive = exclusive;
}
function _each(iterator) {
var value = this.start;
while (this.include(value)) {
iterator(value);
value = value.succ();
}
}
function include(value) {
if (value < this.start)
return false;
if (this.exclusive)
return value < this.end;
return value <= this.end;
}
return {
initialize: initialize,
_each: _each,
include: include
};
})());
var Ajax = {
getTransport: function() {
return Try.these(
function() {return new XMLHttpRequest()},
function() {return new ActiveXObject('Msxml2.XMLHTTP')},
function() {return new ActiveXObject('Microsoft.XMLHTTP')}
) || false;
},
activeRequestCount: 0
};
Ajax.Responders = {
responders: [],
_each: function(iterator) {
this.responders._each(iterator);
},
register: function(responder) {
if (!this.include(responder))
this.responders.push(responder);
},
unregister: function(responder) {
this.responders = this.responders.without(responder);
},
dispatch: function(callback, request, transport, json) {
this.each(function(responder) {
if (Object.isFunction(responder[callback])) {
try {
responder[callback].apply(responder, [request, transport, json]);
} catch (e) { }
}
});
}
};
Object.extend(Ajax.Responders, Enumerable);
Ajax.Responders.register({
onCreate: function() { Ajax.activeRequestCount++ },
onComplete: function() { Ajax.activeRequestCount-- }
});
Ajax.Base = Class.create({
initialize: function(options) {
this.options = {
method: 'post',
asynchronous: true,
contentType: 'application/x-www-form-urlencoded',
encoding: 'UTF-8',
parameters: '',
evalJSON: true,
evalJS: true
};
Object.extend(this.options, options || { });
this.options.method = this.options.method.toLowerCase();
if (Object.isHash(this.options.parameters))
this.options.parameters = this.options.parameters.toObject();
}
});
Ajax.Request = Class.create(Ajax.Base, {
_complete: false,
initialize: function($super, url, options) {
$super(options);
this.transport = Ajax.getTransport();
this.request(url);
},
request: function(url) {
this.url = url;
this.method = this.options.method;
var params = Object.isString(this.options.parameters) ?
this.options.parameters :
Object.toQueryString(this.options.parameters);
if (!['get', 'post'].include(this.method)) {
params += (params ? '&' : '') + "_method=" + this.method;
this.method = 'post';
}
if (params && this.method === 'get') {
this.url += (this.url.include('?') ? '&' : '?') + params;
}
this.parameters = params.toQueryParams();
try {
var response = new Ajax.Response(this);
if (this.options.onCreate) this.options.onCreate(response);
Ajax.Responders.dispatch('onCreate', this, response);
this.transport.open(this.method.toUpperCase(), this.url,
this.options.asynchronous);
if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1);
this.transport.onreadystatechange = this.onStateChange.bind(this);
this.setRequestHeaders();
this.body = this.method == 'post' ? (this.options.postBody || params) : null;
this.transport.send(this.body);
/* Force Firefox to handle ready state 4 for synchronous requests */
if (!this.options.asynchronous && this.transport.overrideMimeType)
this.onStateChange();
}
catch (e) {
this.dispatchException(e);
}
},
onStateChange: function() {
var readyState = this.transport.readyState;
if (readyState > 1 && !((readyState == 4) && this._complete))
this.respondToReadyState(this.transport.readyState);
},
setRequestHeaders: function() {
var headers = {
'X-Requested-With': 'XMLHttpRequest',
'X-Prototype-Version': Prototype.Version,
'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
};
if (this.method == 'post') {
headers['Content-type'] = this.options.contentType +
(this.options.encoding ? '; charset=' + this.options.encoding : '');
/* Force "Connection: close" for older Mozilla browsers to work
* around a bug where XMLHttpRequest sends an incorrect
* Content-length header. See Mozilla Bugzilla #246651.
*/
if (this.transport.overrideMimeType &&
(navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
headers['Connection'] = 'close';
}
if (typeof this.options.requestHeaders == 'object') {
var extras = this.options.requestHeaders;
if (Object.isFunction(extras.push))
for (var i = 0, length = extras.length; i < length; i += 2)
headers[extras[i]] = extras[i+1];
else
$H(extras).each(function(pair) { headers[pair.key] = pair.value });
}
for (var name in headers)
this.transport.setRequestHeader(name, headers[name]);
},
success: function() {
var status = this.getStatus();
return !status || (status >= 200 && status < 300) || status == 304;
},
getStatus: function() {
try {
if (this.transport.status === 1223) return 204;
return this.transport.status || 0;
} catch (e) { return 0 }
},
respondToReadyState: function(readyState) {
var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);
if (state == 'Complete') {
try {
this._complete = true;
(this.options['on' + response.status]
|| this.options['on' + (this.success() ? 'Success' : 'Failure')]
|| Prototype.emptyFunction)(response, response.headerJSON);
} catch (e) {
this.dispatchException(e);
}
var contentType = response.getHeader('Content-type');
if (this.options.evalJS == 'force'
|| (this.options.evalJS && this.isSameOrigin() && contentType
&& contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
this.evalResponse();
}
try {
(this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
} catch (e) {
this.dispatchException(e);
}
if (state == 'Complete') {
this.transport.onreadystatechange = Prototype.emptyFunction;
}
},
isSameOrigin: function() {
var m = this.url.match(/^\s*https?:\/\/[^\/]*/);
return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({
protocol: location.protocol,
domain: document.domain,
port: location.port ? ':' + location.port : ''
}));
},
getHeader: function(name) {
try {
return this.transport.getResponseHeader(name) || null;
} catch (e) { return null; }
},
evalResponse: function() {
try {
return eval((this.transport.responseText || '').unfilterJSON());
} catch (e) {
this.dispatchException(e);
}
},
dispatchException: function(exception) {
(this.options.onException || Prototype.emptyFunction)(this, exception);
Ajax.Responders.dispatch('onException', this, exception);
}
});
Ajax.Request.Events =
['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
Ajax.Response = Class.create({
initialize: function(request){
this.request = request;
var transport = this.transport = request.transport,
readyState = this.readyState = transport.readyState;
if ((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) {
this.status = this.getStatus();
this.statusText = this.getStatusText();
this.responseText = String.interpret(transport.responseText);
this.headerJSON = this._getHeaderJSON();
}
if (readyState == 4) {
var xml = transport.responseXML;
this.responseXML = Object.isUndefined(xml) ? null : xml;
this.responseJSON = this._getResponseJSON();
}
},
status: 0,
statusText: '',
getStatus: Ajax.Request.prototype.getStatus,
getStatusText: function() {
try {
return this.transport.statusText || '';
} catch (e) { return '' }
},
getHeader: Ajax.Request.prototype.getHeader,
getAllHeaders: function() {
try {
return this.getAllResponseHeaders();
} catch (e) { return null }
},
getResponseHeader: function(name) {
return this.transport.getResponseHeader(name);
},
getAllResponseHeaders: function() {
return this.transport.getAllResponseHeaders();
},
_getHeaderJSON: function() {
var json = this.getHeader('X-JSON');
if (!json) return null;
json = decodeURIComponent(escape(json));
try {
return json.evalJSON(this.request.options.sanitizeJSON ||
!this.request.isSameOrigin());
} catch (e) {
this.request.dispatchException(e);
}
},
_getResponseJSON: function() {
var options = this.request.options;
if (!options.evalJSON || (options.evalJSON != 'force' &&
!(this.getHeader('Content-type') || '').include('application/json')) ||
this.responseText.blank())
return null;
try {
return this.responseText.evalJSON(options.sanitizeJSON ||
!this.request.isSameOrigin());
} catch (e) {
this.request.dispatchException(e);
}
}
});
Ajax.Updater = Class.create(Ajax.Request, {
initialize: function($super, container, url, options) {
this.container = {
success: (container.success || container),
failure: (container.failure || (container.success ? null : container))
};
options = Object.clone(options);
var onComplete = options.onComplete;
options.onComplete = (function(response, json) {
this.updateContent(response.responseText);
if (Object.isFunction(onComplete)) onComplete(response, json);
}).bind(this);
$super(url, options);
},
updateContent: function(responseText) {
var receiver = this.container[this.success() ? 'success' : 'failure'],
options = this.options;
if (!options.evalScripts) responseText = responseText.stripScripts();
if (receiver = $(receiver)) {
if (options.insertion) {
if (Object.isString(options.insertion)) {
var insertion = { }; insertion[options.insertion] = responseText;
receiver.insert(insertion);
}
else options.insertion(receiver, responseText);
}
else receiver.update(responseText);
}
}
});
Ajax.PeriodicalUpdater = Class.create(Ajax.Base, {
initialize: function($super, container, url, options) {
$super(options);
this.onComplete = this.options.onComplete;
this.frequency = (this.options.frequency || 2);
this.decay = (this.options.decay || 1);
this.updater = { };
this.container = container;
this.url = url;
this.start();
},
start: function() {
this.options.onComplete = this.updateComplete.bind(this);
this.onTimerEvent();
},
stop: function() {
this.updater.options.onComplete = undefined;
clearTimeout(this.timer);
(this.onComplete || Prototype.emptyFunction).apply(this, arguments);
},
updateComplete: function(response) {
if (this.options.decay) {
this.decay = (response.responseText == this.lastText ?
this.decay * this.options.decay : 1);
this.lastText = response.responseText;
}
this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency);
},
onTimerEvent: function() {
this.updater = new Ajax.Updater(this.container, this.url, this.options);
}
});
function $(element) {
if (arguments.length > 1) {
for (var i = 0, elements = [], length = arguments.length; i < length; i++)
elements.push($(arguments[i]));
return elements;
}
if (Object.isString(element))
element = document.getElementById(element);
return Element.extend(element);
}
if (Prototype.BrowserFeatures.XPath) {
document._getElementsByXPath = function(expression, parentElement) {
var results = [];
var query = document.evaluate(expression, $(parentElement) || document,
null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i = 0, length = query.snapshotLength; i < length; i++)
results.push(Element.extend(query.snapshotItem(i)));
return results;
};
}
/*--------------------------------------------------------------------------*/
if (!Node) var Node = { };
if (!Node.ELEMENT_NODE) {
Object.extend(Node, {
ELEMENT_NODE: 1,
ATTRIBUTE_NODE: 2,
TEXT_NODE: 3,
CDATA_SECTION_NODE: 4,
ENTITY_REFERENCE_NODE: 5,
ENTITY_NODE: 6,
PROCESSING_INSTRUCTION_NODE: 7,
COMMENT_NODE: 8,
DOCUMENT_NODE: 9,
DOCUMENT_TYPE_NODE: 10,
DOCUMENT_FRAGMENT_NODE: 11,
NOTATION_NODE: 12
});
}
(function(global) {
function shouldUseCache(tagName, attributes) {
if (tagName === 'select') return false;
if ('type' in attributes) return false;
return true;
}
var HAS_EXTENDED_CREATE_ELEMENT_SYNTAX = (function(){
try {
var el = document.createElement('<input name="x">');
return el.tagName.toLowerCase() === 'input' && el.name === 'x';
}
catch(err) {
return false;
}
})();
var element = global.Element;
global.Element = function(tagName, attributes) {
attributes = attributes || { };
tagName = tagName.toLowerCase();
var cache = Element.cache;
if (HAS_EXTENDED_CREATE_ELEMENT_SYNTAX && attributes.name) {
tagName = '<' + tagName + ' name="' + attributes.name + '">';
delete attributes.name;
return Element.writeAttribute(document.createElement(tagName), attributes);
}
if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
var node = shouldUseCache(tagName, attributes) ?
cache[tagName].cloneNode(false) : document.createElement(tagName);
return Element.writeAttribute(node, attributes);
};
Object.extend(global.Element, element || { });
if (element) global.Element.prototype = element.prototype;
})(this);
Element.idCounter = 1;
Element.cache = { };
Element._purgeElement = function(element) {
var uid = element._prototypeUID;
if (uid) {
Element.stopObserving(element);
element._prototypeUID = void 0;
delete Element.Storage[uid];
}
}
Element.Methods = {
visible: function(element) {
return $(element).style.display != 'none';
},
toggle: function(element) {
element = $(element);
Element[Element.visible(element) ? 'hide' : 'show'](element);
return element;
},
hide: function(element) {
element = $(element);
element.style.display = 'none';
return element;
},
show: function(element) {
element = $(element);
element.style.display = '';
return element;
},
remove: function(element) {
element = $(element);
element.parentNode.removeChild(element);
return element;
},
update: (function(){
var SELECT_ELEMENT_INNERHTML_BUGGY = (function(){
var el = document.createElement("select"),
isBuggy = true;
el.innerHTML = "<option value=\"test\">test</option>";
if (el.options && el.options[0]) {
isBuggy = el.options[0].nodeName.toUpperCase() !== "OPTION";
}
el = null;
return isBuggy;
})();
var TABLE_ELEMENT_INNERHTML_BUGGY = (function(){
try {
var el = document.createElement("table");
if (el && el.tBodies) {
el.innerHTML = "<tbody><tr><td>test</td></tr></tbody>";
var isBuggy = typeof el.tBodies[0] == "undefined";
el = null;
return isBuggy;
}
} catch (e) {
return true;
}
})();
var LINK_ELEMENT_INNERHTML_BUGGY = (function() {
try {
var el = document.createElement('div');
el.innerHTML = "<link>";
var isBuggy = (el.childNodes.length === 0);
el = null;
return isBuggy;
} catch(e) {
return true;
}
})();
var ANY_INNERHTML_BUGGY = SELECT_ELEMENT_INNERHTML_BUGGY ||
TABLE_ELEMENT_INNERHTML_BUGGY || LINK_ELEMENT_INNERHTML_BUGGY;
var SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING = (function () {
var s = document.createElement("script"),
isBuggy = false;
try {
s.appendChild(document.createTextNode(""));
isBuggy = !s.firstChild ||
s.firstChild && s.firstChild.nodeType !== 3;
} catch (e) {
isBuggy = true;
}
s = null;
return isBuggy;
})();
function update(element, content) {
element = $(element);
var purgeElement = Element._purgeElement;
var descendants = element.getElementsByTagName('*'),
i = descendants.length;
while (i--) purgeElement(descendants[i]);
if (content && content.toElement)
content = content.toElement();
if (Object.isElement(content))
return element.update().insert(content);
content = Object.toHTML(content);
var tagName = element.tagName.toUpperCase();
if (tagName === 'SCRIPT' && SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING) {
element.text = content;
return element;
}
if (ANY_INNERHTML_BUGGY) {
if (tagName in Element._insertionTranslations.tags) {
while (element.firstChild) {
element.removeChild(element.firstChild);
}
Element._getContentFromAnonymousElement(tagName, content.stripScripts())
.each(function(node) {
element.appendChild(node)
});
} else if (LINK_ELEMENT_INNERHTML_BUGGY && Object.isString(content) && content.indexOf('<link') > -1) {
while (element.firstChild) {
element.removeChild(element.firstChild);
}
var nodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts(), true);
nodes.each(function(node) { element.appendChild(node) });
}
else {
element.innerHTML = content.stripScripts();
}
}
else {
element.innerHTML = content.stripScripts();
}
content.evalScripts.bind(content).defer();
return element;
}
return update;
})(),
replace: function(element, content) {
element = $(element);
if (content && content.toElement) content = content.toElement();
else if (!Object.isElement(content)) {
content = Object.toHTML(content);
var range = element.ownerDocument.createRange();
range.selectNode(element);
content.evalScripts.bind(content).defer();
content = range.createContextualFragment(content.stripScripts());
}
element.parentNode.replaceChild(content, element);
return element;
},
insert: function(element, insertions) {
element = $(element);
if (Object.isString(insertions) || Object.isNumber(insertions) ||
Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
insertions = {bottom:insertions};
var content, insert, tagName, childNodes;
for (var position in insertions) {
content = insertions[position];
position = position.toLowerCase();
insert = Element._insertionTranslations[position];
if (content && content.toElement) content = content.toElement();
if (Object.isElement(content)) {
insert(element, content);
continue;
}
content = Object.toHTML(content);
tagName = ((position == 'before' || position == 'after')
? element.parentNode : element).tagName.toUpperCase();
childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
if (position == 'top' || position == 'after') childNodes.reverse();
childNodes.each(insert.curry(element));
content.evalScripts.bind(content).defer();
}
return element;
},
wrap: function(element, wrapper, attributes) {
element = $(element);
if (Object.isElement(wrapper))
$(wrapper).writeAttribute(attributes || { });
else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
else wrapper = new Element('div', wrapper);
if (element.parentNode)
element.parentNode.replaceChild(wrapper, element);
wrapper.appendChild(element);
return wrapper;
},
inspect: function(element) {
element = $(element);
var result = '<' + element.tagName.toLowerCase();
$H({'id': 'id', 'className': 'class'}).each(function(pair) {
var property = pair.first(),
attribute = pair.last(),
value = (element[property] || '').toString();
if (value) result += ' ' + attribute + '=' + value.inspect(true);
});
return result + '>';
},
recursivelyCollect: function(element, property, maximumLength) {
element = $(element);
maximumLength = maximumLength || -1;
var elements = [];
while (element = element[property]) {
if (element.nodeType == 1)
elements.push(Element.extend(element));
if (elements.length == maximumLength)
break;
}
return elements;
},
ancestors: function(element) {
return Element.recursivelyCollect(element, 'parentNode');
},
descendants: function(element) {
return Element.select(element, "*");
},
firstDescendant: function(element) {
element = $(element).firstChild;
while (element && element.nodeType != 1) element = element.nextSibling;
return $(element);
},
immediateDescendants: function(element) {
var results = [], child = $(element).firstChild;
while (child) {
if (child.nodeType === 1) {
results.push(Element.extend(child));
}
child = child.nextSibling;
}
return results;
},
previousSiblings: function(element, maximumLength) {
return Element.recursivelyCollect(element, 'previousSibling');
},
nextSiblings: function(element) {
return Element.recursivelyCollect(element, 'nextSibling');
},
siblings: function(element) {
element = $(element);
return Element.previousSiblings(element).reverse()
.concat(Element.nextSiblings(element));
},
match: function(element, selector) {
element = $(element);
if (Object.isString(selector))
return Prototype.Selector.match(element, selector);
return selector.match(element);
},
up: function(element, expression, index) {
element = $(element);
if (arguments.length == 1) return $(element.parentNode);
var ancestors = Element.ancestors(element);
return Object.isNumber(expression) ? ancestors[expression] :
Prototype.Selector.find(ancestors, expression, index);
},
down: function(element, expression, index) {
element = $(element);
if (arguments.length == 1) return Element.firstDescendant(element);
return Object.isNumber(expression) ? Element.descendants(element)[expression] :
Element.select(element, expression)[index || 0];
},
previous: function(element, expression, index) {
element = $(element);
if (Object.isNumber(expression)) index = expression, expression = false;
if (!Object.isNumber(index)) index = 0;
if (expression) {
return Prototype.Selector.find(element.previousSiblings(), expression, index);
} else {
return element.recursivelyCollect("previousSibling", index + 1)[index];
}
},
next: function(element, expression, index) {
element = $(element);
if (Object.isNumber(expression)) index = expression, expression = false;
if (!Object.isNumber(index)) index = 0;
if (expression) {
return Prototype.Selector.find(element.nextSiblings(), expression, index);
} else {
var maximumLength = Object.isNumber(index) ? index + 1 : 1;
return element.recursivelyCollect("nextSibling", index + 1)[index];
}
},
select: function(element) {
element = $(element);
var expressions = Array.prototype.slice.call(arguments, 1).join(', ');
return Prototype.Selector.select(expressions, element);
},
adjacent: function(element) {
element = $(element);
var expressions = Array.prototype.slice.call(arguments, 1).join(', ');
return Prototype.Selector.select(expressions, element.parentNode).without(element);
},
identify: function(element) {
element = $(element);
var id = Element.readAttribute(element, 'id');
if (id) return id;
do { id = 'anonymous_element_' + Element.idCounter++ } while ($(id));
Element.writeAttribute(element, 'id', id);
return id;
},
readAttribute: function(element, name) {
element = $(element);
if (Prototype.Browser.IE) {
var t = Element._attributeTranslations.read;
if (t.values[name]) return t.values[name](element, name);
if (t.names[name]) name = t.names[name];
if (name.include(':')) {
return (!element.attributes || !element.attributes[name]) ? null :
element.attributes[name].value;
}
}
return element.getAttribute(name);
},
writeAttribute: function(element, name, value) {
element = $(element);
var attributes = { }, t = Element._attributeTranslations.write;
if (typeof name == 'object') attributes = name;
else attributes[name] = Object.isUndefined(value) ? true : value;
for (var attr in attributes) {
name = t.names[attr] || attr;
value = attributes[attr];
if (t.values[attr]) name = t.values[attr](element, value);
if (value === false || value === null)
element.removeAttribute(name);
else if (value === true)
element.setAttribute(name, name);
else element.setAttribute(name, value);
}
return element;
},
getHeight: function(element) {
return Element.getDimensions(element).height;
},
getWidth: function(element) {
return Element.getDimensions(element).width;
},
classNames: function(element) {
return new Element.ClassNames(element);
},
hasClassName: function(element, className) {
if (!(element = $(element))) return;
var elementClassName = element.className;
return (elementClassName.length > 0 && (elementClassName == className ||
new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
},
addClassName: function(element, className) {
if (!(element = $(element))) return;
if (!Element.hasClassName(element, className))
element.className += (element.className ? ' ' : '') + className;
return element;
},
removeClassName: function(element, className) {
if (!(element = $(element))) return;
element.className = element.className.replace(
new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
return element;
},
toggleClassName: function(element, className) {
if (!(element = $(element))) return;
return Element[Element.hasClassName(element, className) ?
'removeClassName' : 'addClassName'](element, className);
},
cleanWhitespace: function(element) {
element = $(element);
var node = element.firstChild;
while (node) {
var nextNode = node.nextSibling;
if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
element.removeChild(node);
node = nextNode;
}
return element;
},
empty: function(element) {
return $(element).innerHTML.blank();
},
descendantOf: function(element, ancestor) {
element = $(element), ancestor = $(ancestor);
if (element.compareDocumentPosition)
return (element.compareDocumentPosition(ancestor) & 8) === 8;
if (ancestor.contains)
return ancestor.contains(element) && ancestor !== element;
while (element = element.parentNode)
if (element == ancestor) return true;
return false;
},
scrollTo: function(element) {
element = $(element);
var pos = Element.cumulativeOffset(element);
window.scrollTo(pos[0], pos[1]);
return element;
},
getStyle: function(element, style) {
element = $(element);
style = style == 'float' ? 'cssFloat' : style.camelize();
var value = element.style[style];
if (!value || value == 'auto') {
var css = document.defaultView.getComputedStyle(element, null);
value = css ? css[style] : null;
}
if (style == 'opacity') return value ? parseFloat(value) : 1.0;
return value == 'auto' ? null : value;
},
getOpacity: function(element) {
return $(element).getStyle('opacity');
},
setStyle: function(element, styles) {
element = $(element);
var elementStyle = element.style, match;
if (Object.isString(styles)) {
element.style.cssText += ';' + styles;
return styles.include('opacity') ?
element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
}
for (var property in styles)
if (property == 'opacity') element.setOpacity(styles[property]);
else
elementStyle[(property == 'float' || property == 'cssFloat') ?
(Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
property] = styles[property];
return element;
},
setOpacity: function(element, value) {
element = $(element);
element.style.opacity = (value == 1 || value === '') ? '' :
(value < 0.00001) ? 0 : value;
return element;
},
makePositioned: function(element) {
element = $(element);
var pos = Element.getStyle(element, 'position');
if (pos == 'static' || !pos) {
element._madePositioned = true;
element.style.position = 'relative';
if (Prototype.Browser.Opera) {
element.style.top = 0;
element.style.left = 0;
}
}
return element;
},
undoPositioned: function(element) {
element = $(element);
if (element._madePositioned) {
element._madePositioned = undefined;
element.style.position =
element.style.top =
element.style.left =
element.style.bottom =
element.style.right = '';
}
return element;
},
makeClipping: function(element) {
element = $(element);
if (element._overflow) return element;
element._overflow = Element.getStyle(element, 'overflow') || 'auto';
if (element._overflow !== 'hidden')
element.style.overflow = 'hidden';
return element;
},
undoClipping: function(element) {
element = $(element);
if (!element._overflow) return element;
element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
element._overflow = null;
return element;
},
clonePosition: function(element, source) {
var options = Object.extend({
setLeft: true,
setTop: true,
setWidth: true,
setHeight: true,
offsetTop: 0,
offsetLeft: 0
}, arguments[2] || { });
source = $(source);
var p = Element.viewportOffset(source), delta = [0, 0], parent = null;
element = $(element);
if (Element.getStyle(element, 'position') == 'absolute') {
parent = Element.getOffsetParent(element);
delta = Element.viewportOffset(parent);
}
if (parent == document.body) {
delta[0] -= document.body.offsetLeft;
delta[1] -= document.body.offsetTop;
}
if (options.setLeft) element.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
if (options.setTop) element.style.top = (p[1] - delta[1] + options.offsetTop) + 'px';
if (options.setWidth) element.style.width = source.offsetWidth + 'px';
if (options.setHeight) element.style.height = source.offsetHeight + 'px';
return element;
}
};
Object.extend(Element.Methods, {
getElementsBySelector: Element.Methods.select,
childElements: Element.Methods.immediateDescendants
});
Element._attributeTranslations = {
write: {
names: {
className: 'class',
htmlFor: 'for'
},
values: { }
}
};
if (Prototype.Browser.Opera) {
Element.Methods.getStyle = Element.Methods.getStyle.wrap(
function(proceed, element, style) {
switch (style) {
case 'height': case 'width':
if (!Element.visible(element)) return null;
var dim = parseInt(proceed(element, style), 10);
if (dim !== element['offset' + style.capitalize()])
return dim + 'px';
var properties;
if (style === 'height') {
properties = ['border-top-width', 'padding-top',
'padding-bottom', 'border-bottom-width'];
}
else {
properties = ['border-left-width', 'padding-left',
'padding-right', 'border-right-width'];
}
return properties.inject(dim, function(memo, property) {
var val = proceed(element, property);
return val === null ? memo : memo - parseInt(val, 10);
}) + 'px';
default: return proceed(element, style);
}
}
);
Element.Methods.readAttribute = Element.Methods.readAttribute.wrap(
function(proceed, element, attribute) {
if (attribute === 'title') return element.title;
return proceed(element, attribute);
}
);
}
else if (Prototype.Browser.IE) {
Element.Methods.getStyle = function(element, style) {
element = $(element);
style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
var value = element.style[style];
if (!value && element.currentStyle) value = element.currentStyle[style];
if (style == 'opacity') {
if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
if (value[1]) return parseFloat(value[1]) / 100;
return 1.0;
}
if (value == 'auto') {
if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
return element['offset' + style.capitalize()] + 'px';
return null;
}
return value;
};
Element.Methods.setOpacity = function(element, value) {
function stripAlpha(filter){
return filter.replace(/alpha\([^\)]*\)/gi,'');
}
element = $(element);
var currentStyle = element.currentStyle;
if ((currentStyle && !currentStyle.hasLayout) ||
(!currentStyle && element.style.zoom == 'normal'))
element.style.zoom = 1;
var filter = element.getStyle('filter'), style = element.style;
if (value == 1 || value === '') {
(filter = stripAlpha(filter)) ?
style.filter = filter : style.removeAttribute('filter');
return element;
} else if (value < 0.00001) value = 0;
style.filter = stripAlpha(filter) +
'alpha(opacity=' + (value * 100) + ')';
return element;
};
Element._attributeTranslations = (function(){
var classProp = 'className',
forProp = 'for',
el = document.createElement('div');
el.setAttribute(classProp, 'x');
if (el.className !== 'x') {
el.setAttribute('class', 'x');
if (el.className === 'x') {
classProp = 'class';
}
}
el = null;
el = document.createElement('label');
el.setAttribute(forProp, 'x');
if (el.htmlFor !== 'x') {
el.setAttribute('htmlFor', 'x');
if (el.htmlFor === 'x') {
forProp = 'htmlFor';
}
}
el = null;
return {
read: {
names: {
'class': classProp,
'className': classProp,
'for': forProp,
'htmlFor': forProp
},
values: {
_getAttr: function(element, attribute) {
return element.getAttribute(attribute);
},
_getAttr2: function(element, attribute) {
return element.getAttribute(attribute, 2);
},
_getAttrNode: function(element, attribute) {
var node = element.getAttributeNode(attribute);
return node ? node.value : "";
},
_getEv: (function(){
var el = document.createElement('div'), f;
el.onclick = Prototype.emptyFunction;
var value = el.getAttribute('onclick');
if (String(value).indexOf('{') > -1) {
f = function(element, attribute) {
attribute = element.getAttribute(attribute);
if (!attribute) return null;
attribute = attribute.toString();
attribute = attribute.split('{')[1];
attribute = attribute.split('}')[0];
return attribute.strip();
};
}
else if (value === '') {
f = function(element, attribute) {
attribute = element.getAttribute(attribute);
if (!attribute) return null;
return attribute.strip();
};
}
el = null;
return f;
})(),
_flag: function(element, attribute) {
return $(element).hasAttribute(attribute) ? attribute : null;
},
style: function(element) {
return element.style.cssText.toLowerCase();
},
title: function(element) {
return element.title;
}
}
}
}
})();
Element._attributeTranslations.write = {
names: Object.extend({
cellpadding: 'cellPadding',
cellspacing: 'cellSpacing'
}, Element._attributeTranslations.read.names),
values: {
checked: function(element, value) {
element.checked = !!value;
},
style: function(element, value) {
element.style.cssText = value ? value : '';
}
}
};
Element._attributeTranslations.has = {};
$w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
'encType maxLength readOnly longDesc frameBorder').each(function(attr) {
Element._attributeTranslations.write.names[attr.toLowerCase()] = attr;
Element._attributeTranslations.has[attr.toLowerCase()] = attr;
});
(function(v) {
Object.extend(v, {
href: v._getAttr2,
src: v._getAttr2,
type: v._getAttr,
action: v._getAttrNode,
disabled: v._flag,
checked: v._flag,
readonly: v._flag,
multiple: v._flag,
onload: v._getEv,
onunload: v._getEv,
onclick: v._getEv,
ondblclick: v._getEv,
onmousedown: v._getEv,
onmouseup: v._getEv,
onmouseover: v._getEv,
onmousemove: v._getEv,
onmouseout: v._getEv,
onfocus: v._getEv,
onblur: v._getEv,
onkeypress: v._getEv,
onkeydown: v._getEv,
onkeyup: v._getEv,
onsubmit: v._getEv,
onreset: v._getEv,
onselect: v._getEv,
onchange: v._getEv
});
})(Element._attributeTranslations.read.values);
if (Prototype.BrowserFeatures.ElementExtensions) {
(function() {
function _descendants(element) {
var nodes = element.getElementsByTagName('*'), results = [];
for (var i = 0, node; node = nodes[i]; i++)
if (node.tagName !== "!") // Filter out comment nodes.
results.push(node);
return results;
}
Element.Methods.down = function(element, expression, index) {
element = $(element);
if (arguments.length == 1) return element.firstDescendant();
return Object.isNumber(expression) ? _descendants(element)[expression] :
Element.select(element, expression)[index || 0];
}
})();
}
}
else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) {
Element.Methods.setOpacity = function(element, value) {
element = $(element);
element.style.opacity = (value == 1) ? 0.999999 :
(value === '') ? '' : (value < 0.00001) ? 0 : value;
return element;
};
}
else if (Prototype.Browser.WebKit) {
Element.Methods.setOpacity = function(element, value) {
element = $(element);
element.style.opacity = (value == 1 || value === '') ? '' :
(value < 0.00001) ? 0 : value;
if (value == 1)
if (element.tagName.toUpperCase() == 'IMG' && element.width) {
element.width++; element.width--;
} else try {
var n = document.createTextNode(' ');
element.appendChild(n);
element.removeChild(n);
} catch (e) { }
return element;
};
}
if ('outerHTML' in document.documentElement) {
Element.Methods.replace = function(element, content) {
element = $(element);
if (content && content.toElement) content = content.toElement();
if (Object.isElement(content)) {
element.parentNode.replaceChild(content, element);
return element;
}
content = Object.toHTML(content);
var parent = element.parentNode, tagName = parent.tagName.toUpperCase();
if (Element._insertionTranslations.tags[tagName]) {
var nextSibling = element.next(),
fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
parent.removeChild(element);
if (nextSibling)
fragments.each(function(node) { parent.insertBefore(node, nextSibling) });
else
fragments.each(function(node) { parent.appendChild(node) });
}
else element.outerHTML = content.stripScripts();
content.evalScripts.bind(content).defer();
return element;
};
}
Element._returnOffset = function(l, t) {
var result = [l, t];
result.left = l;
result.top = t;
return result;
};
Element._getContentFromAnonymousElement = function(tagName, html, force) {
var div = new Element('div'),
t = Element._insertionTranslations.tags[tagName];
var workaround = false;
if (t) workaround = true;
else if (force) {
workaround = true;
t = ['', '', 0];
}
if (workaround) {
div.innerHTML = ' ' + t[0] + html + t[1];
div.removeChild(div.firstChild);
for (var i = t[2]; i--; ) {
div = div.firstChild;
}
}
else {
div.innerHTML = html;
}
return $A(div.childNodes);
};
Element._insertionTranslations = {
before: function(element, node) {
element.parentNode.insertBefore(node, element);
},
top: function(element, node) {
element.insertBefore(node, element.firstChild);
},
bottom: function(element, node) {
element.appendChild(node);
},
after: function(element, node) {
element.parentNode.insertBefore(node, element.nextSibling);
},
tags: {
TABLE: ['<table>', '</table>', 1],
TBODY: ['<table><tbody>', '</tbody></table>', 2],
TR: ['<table><tbody><tr>', '</tr></tbody></table>', 3],
TD: ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
SELECT: ['<select>', '</select>', 1]
}
};
(function() {
var tags = Element._insertionTranslations.tags;
Object.extend(tags, {
THEAD: tags.TBODY,
TFOOT: tags.TBODY,
TH: tags.TD
});
})();
Element.Methods.Simulated = {
hasAttribute: function(element, attribute) {
attribute = Element._attributeTranslations.has[attribute] || attribute;
var node = $(element).getAttributeNode(attribute);
return !!(node && node.specified);
}
};
Element.Methods.ByTag = { };
Object.extend(Element, Element.Methods);
(function(div) {
if (!Prototype.BrowserFeatures.ElementExtensions && div['__proto__']) {
window.HTMLElement = { };
window.HTMLElement.prototype = div['__proto__'];
Prototype.BrowserFeatures.ElementExtensions = true;
}
div = null;
})(document.createElement('div'));
Element.extend = (function() {
function checkDeficiency(tagName) {
if (typeof window.Element != 'undefined') {
var proto = window.Element.prototype;
if (proto) {
var id = '_' + (Math.random()+'').slice(2),
el = document.createElement(tagName);
proto[id] = 'x';
var isBuggy = (el[id] !== 'x');
delete proto[id];
el = null;
return isBuggy;
}
}
return false;
}
function extendElementWith(element, methods) {
for (var property in methods) {
var value = methods[property];
if (Object.isFunction(value) && !(property in element))
element[property] = value.methodize();
}
}
var HTMLOBJECTELEMENT_PROTOTYPE_BUGGY = checkDeficiency('object');
if (Prototype.BrowserFeatures.SpecificElementExtensions) {
if (HTMLOBJECTELEMENT_PROTOTYPE_BUGGY) {
return function(element) {
if (element && typeof element._extendedByPrototype == 'undefined') {
var t = element.tagName;
if (t && (/^(?:object|applet|embed)$/i.test(t))) {
extendElementWith(element, Element.Methods);
extendElementWith(element, Element.Methods.Simulated);
extendElementWith(element, Element.Methods.ByTag[t.toUpperCase()]);
}
}
return element;
}
}
return Prototype.K;
}
var Methods = { }, ByTag = Element.Methods.ByTag;
var extend = Object.extend(function(element) {
if (!element || typeof element._extendedByPrototype != 'undefined' ||
element.nodeType != 1 || element == window) return element;
var methods = Object.clone(Methods),
tagName = element.tagName.toUpperCase();
if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);
extendElementWith(element, methods);
element._extendedByPrototype = Prototype.emptyFunction;
return element;
}, {
refresh: function() {
if (!Prototype.BrowserFeatures.ElementExtensions) {
Object.extend(Methods, Element.Methods);
Object.extend(Methods, Element.Methods.Simulated);
}
}
});
extend.refresh();
return extend;
})();
if (document.documentElement.hasAttribute) {
Element.hasAttribute = function(element, attribute) {
return element.hasAttribute(attribute);
};
}
else {
Element.hasAttribute = Element.Methods.Simulated.hasAttribute;
}
Element.addMethods = function(methods) {
var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;
if (!methods) {
Object.extend(Form, Form.Methods);
Object.extend(Form.Element, Form.Element.Methods);
Object.extend(Element.Methods.ByTag, {
"FORM": Object.clone(Form.Methods),
"INPUT": Object.clone(Form.Element.Methods),
"SELECT": Object.clone(Form.Element.Methods),
"TEXTAREA": Object.clone(Form.Element.Methods),
"BUTTON": Object.clone(Form.Element.Methods)
});
}
if (arguments.length == 2) {
var tagName = methods;
methods = arguments[1];
}
if (!tagName) Object.extend(Element.Methods, methods || { });
else {
if (Object.isArray(tagName)) tagName.each(extend);
else extend(tagName);
}
function extend(tagName) {
tagName = tagName.toUpperCase();
if (!Element.Methods.ByTag[tagName])
Element.Methods.ByTag[tagName] = { };
Object.extend(Element.Methods.ByTag[tagName], methods);
}
function copy(methods, destination, onlyIfAbsent) {
onlyIfAbsent = onlyIfAbsent || false;
for (var property in methods) {
var value = methods[property];
if (!Object.isFunction(value)) continue;
if (!onlyIfAbsent || !(property in destination))
destination[property] = value.methodize();
}
}
function findDOMClass(tagName) {
var klass;
var trans = {
"OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
"FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
"DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
"H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
"INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
"TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
"TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
"TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
"FrameSet", "IFRAME": "IFrame"
};
if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
if (window[klass]) return window[klass];
klass = 'HTML' + tagName + 'Element';
if (window[klass]) return window[klass];
klass = 'HTML' + tagName.capitalize() + 'Element';
if (window[klass]) return window[klass];
var element = document.createElement(tagName),
proto = element['__proto__'] || element.constructor.prototype;
element = null;
return proto;
}
var elementPrototype = window.HTMLElement ? HTMLElement.prototype :
Element.prototype;
if (F.ElementExtensions) {
copy(Element.Methods, elementPrototype);
copy(Element.Methods.Simulated, elementPrototype, true);
}
if (F.SpecificElementExtensions) {
for (var tag in Element.Methods.ByTag) {
var klass = findDOMClass(tag);
if (Object.isUndefined(klass)) continue;
copy(T[tag], klass.prototype);
}
}
Object.extend(Element, Element.Methods);
delete Element.ByTag;
if (Element.extend.refresh) Element.extend.refresh();
Element.cache = { };
};
document.viewport = {
getDimensions: function() {
return { width: this.getWidth(), height: this.getHeight() };
},
getScrollOffsets: function() {
return Element._returnOffset(
window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
}
};
(function(viewport) {
var B = Prototype.Browser, doc = document, element, property = {};
function getRootElement() {
if (B.WebKit && !doc.evaluate)
return document;
if (B.Opera && window.parseFloat(window.opera.version()) < 9.5)
return document.body;
return document.documentElement;
}
function define(D) {
if (!element) element = getRootElement();
property[D] = 'client' + D;
viewport['get' + D] = function() { return element[property[D]] };
return viewport['get' + D]();
}
viewport.getWidth = define.curry('Width');
viewport.getHeight = define.curry('Height');
})(document.viewport);
Element.Storage = {
UID: 1
};
Element.addMethods({
getStorage: function(element) {
if (!(element = $(element))) return;
var uid;
if (element === window) {
uid = 0;
} else {
if (typeof element._prototypeUID === "undefined")
element._prototypeUID = Element.Storage.UID++;
uid = element._prototypeUID;
}
if (!Element.Storage[uid])
Element.Storage[uid] = $H();
return Element.Storage[uid];
},
store: function(element, key, value) {
if (!(element = $(element))) return;
if (arguments.length === 2) {
Element.getStorage(element).update(key);
} else {
Element.getStorage(element).set(key, value);
}
return element;
},
retrieve: function(element, key, defaultValue) {
if (!(element = $(element))) return;
var hash = Element.getStorage(element), value = hash.get(key);
if (Object.isUndefined(value)) {
hash.set(key, defaultValue);
value = defaultValue;
}
return value;
},
clone: function(element, deep) {
if (!(element = $(element))) return;
var clone = element.cloneNode(deep);
clone._prototypeUID = void 0;
if (deep) {
var descendants = Element.select(clone, '*'),
i = descendants.length;
while (i--) {
descendants[i]._prototypeUID = void 0;
}
}
return Element.extend(clone);
},
purge: function(element) {
if (!(element = $(element))) return;
var purgeElement = Element._purgeElement;
purgeElement(element);
var descendants = element.getElementsByTagName('*'),
i = descendants.length;
while (i--) purgeElement(descendants[i]);
return null;
}
});
(function() {
function toDecimal(pctString) {
var match = pctString.match(/^(\d+)%?$/i);
if (!match) return null;
return (Number(match[1]) / 100);
}
function getPixelValue(value, property, context) {
var element = null;
if (Object.isElement(value)) {
element = value;
value = element.getStyle(property);
}
if (value === null) {
return null;
}
if ((/^(?:-)?\d+(\.\d+)?(px)?$/i).test(value)) {
return window.parseFloat(value);
}
var isPercentage = value.include('%'), isViewport = (context === document.viewport);
if (/\d/.test(value) && element && element.runtimeStyle && !(isPercentage && isViewport)) {
var style = element.style.left, rStyle = element.runtimeStyle.left;
element.runtimeStyle.left = element.currentStyle.left;
element.style.left = value || 0;
value = element.style.pixelLeft;
element.style.left = style;
element.runtimeStyle.left = rStyle;
return value;
}
if (element && isPercentage) {
context = context || element.parentNode;
var decimal = toDecimal(value);
var whole = null;
var position = element.getStyle('position');
var isHorizontal = property.include('left') || property.include('right') ||
property.include('width');
var isVertical = property.include('top') || property.include('bottom') ||
property.include('height');
if (context === document.viewport) {
if (isHorizontal) {
whole = document.viewport.getWidth();
} else if (isVertical) {
whole = document.viewport.getHeight();
}
} else {
if (isHorizontal) {
whole = $(context).measure('width');
} else if (isVertical) {
whole = $(context).measure('height');
}
}
return (whole === null) ? 0 : whole * decimal;
}
return 0;
}
function toCSSPixels(number) {
if (Object.isString(number) && number.endsWith('px')) {
return number;
}
return number + 'px';
}
function isDisplayed(element) {
var originalElement = element;
while (element && element.parentNode) {
var display = element.getStyle('display');
if (display === 'none') {
return false;
}
element = $(element.parentNode);
}
return true;
}
var hasLayout = Prototype.K;
if ('currentStyle' in document.documentElement) {
hasLayout = function(element) {
if (!element.currentStyle.hasLayout) {
element.style.zoom = 1;
}
return element;
};
}
function cssNameFor(key) {
if (key.include('border')) key = key + '-width';
return key.camelize();
}
Element.Layout = Class.create(Hash, {
initialize: function($super, element, preCompute) {
$super();
this.element = $(element);
Element.Layout.PROPERTIES.each( function(property) {
this._set(property, null);
}, this);
if (preCompute) {
this._preComputing = true;
this._begin();
Element.Layout.PROPERTIES.each( this._compute, this );
this._end();
this._preComputing = false;
}
},
_set: function(property, value) {
return Hash.prototype.set.call(this, property, value);
},
set: function(property, value) {
throw "Properties of Element.Layout are read-only.";
},
get: function($super, property) {
var value = $super(property);
return value === null ? this._compute(property) : value;
},
_begin: function() {
if (this._prepared) return;
var element = this.element;
if (isDisplayed(element)) {
this._prepared = true;
return;
}
var originalStyles = {
position: element.style.position || '',
width: element.style.width || '',
visibility: element.style.visibility || '',
display: element.style.display || ''
};
element.store('prototype_original_styles', originalStyles);
var position = element.getStyle('position'),
width = element.getStyle('width');
if (width === "0px" || width === null) {
element.style.display = 'block';
width = element.getStyle('width');
}
var context = (position === 'fixed') ? document.viewport :
element.parentNode;
element.setStyle({
position: 'absolute',
visibility: 'hidden',
display: 'block'
});
var positionedWidth = element.getStyle('width');
var newWidth;
if (width && (positionedWidth === width)) {
newWidth = getPixelValue(element, 'width', context);
} else if (position === 'absolute' || position === 'fixed') {
newWidth = getPixelValue(element, 'width', context);
} else {
var parent = element.parentNode, pLayout = $(parent).getLayout();
newWidth = pLayout.get('width') -
this.get('margin-left') -
this.get('border-left') -
this.get('padding-left') -
this.get('padding-right') -
this.get('border-right') -
this.get('margin-right');
}
element.setStyle({ width: newWidth + 'px' });
this._prepared = true;
},
_end: function() {
var element = this.element;
var originalStyles = element.retrieve('prototype_original_styles');
element.store('prototype_original_styles', null);
element.setStyle(originalStyles);
this._prepared = false;
},
_compute: function(property) {
var COMPUTATIONS = Element.Layout.COMPUTATIONS;
if (!(property in COMPUTATIONS)) {
throw "Property not found.";
}
return this._set(property, COMPUTATIONS[property].call(this, this.element));
},
toObject: function() {
var args = $A(arguments);
var keys = (args.length === 0) ? Element.Layout.PROPERTIES :
args.join(' ').split(' ');
var obj = {};
keys.each( function(key) {
if (!Element.Layout.PROPERTIES.include(key)) return;
var value = this.get(key);
if (value != null) obj[key] = value;
}, this);
return obj;
},
toHash: function() {
var obj = this.toObject.apply(this, arguments);
return new Hash(obj);
},
toCSS: function() {
var args = $A(arguments);
var keys = (args.length === 0) ? Element.Layout.PROPERTIES :
args.join(' ').split(' ');
var css = {};
keys.each( function(key) {
if (!Element.Layout.PROPERTIES.include(key)) return;
if (Element.Layout.COMPOSITE_PROPERTIES.include(key)) return;
var value = this.get(key);
if (value != null) css[cssNameFor(key)] = value + 'px';
}, this);
return css;
},
inspect: function() {
return "#<Element.Layout>";
}
});
Object.extend(Element.Layout, {
PROPERTIES: $w('height width top left right bottom border-left border-right border-top border-bottom padding-left padding-right padding-top padding-bottom margin-top margin-bottom margin-left margin-right padding-box-width padding-box-height border-box-width border-box-height margin-box-width margin-box-height'),
COMPOSITE_PROPERTIES: $w('padding-box-width padding-box-height margin-box-width margin-box-height border-box-width border-box-height'),
COMPUTATIONS: {
'height': function(element) {
if (!this._preComputing) this._begin();
var bHeight = this.get('border-box-height');
if (bHeight <= 0) {
if (!this._preComputing) this._end();
return 0;
}
var bTop = this.get('border-top'),
bBottom = this.get('border-bottom');
var pTop = this.get('padding-top'),
pBottom = this.get('padding-bottom');
if (!this._preComputing) this._end();
return bHeight - bTop - bBottom - pTop - pBottom;
},
'width': function(element) {
if (!this._preComputing) this._begin();
var bWidth = this.get('border-box-width');
if (bWidth <= 0) {
if (!this._preComputing) this._end();
return 0;
}
var bLeft = this.get('border-left'),
bRight = this.get('border-right');
var pLeft = this.get('padding-left'),
pRight = this.get('padding-right');
if (!this._preComputing) this._end();
return bWidth - bLeft - bRight - pLeft - pRight;
},
'padding-box-height': function(element) {
var height = this.get('height'),
pTop = this.get('padding-top'),
pBottom = this.get('padding-bottom');
return height + pTop + pBottom;
},
'padding-box-width': function(element) {
var width = this.get('width'),
pLeft = this.get('padding-left'),
pRight = this.get('padding-right');
return width + pLeft + pRight;
},
'border-box-height': function(element) {
if (!this._preComputing) this._begin();
var height = element.offsetHeight;
if (!this._preComputing) this._end();
return height;
},
'border-box-width': function(element) {
if (!this._preComputing) this._begin();
var width = element.offsetWidth;
if (!this._preComputing) this._end();
return width;
},
'margin-box-height': function(element) {
var bHeight = this.get('border-box-height'),
mTop = this.get('margin-top'),
mBottom = this.get('margin-bottom');
if (bHeight <= 0) return 0;
return bHeight + mTop + mBottom;
},
'margin-box-width': function(element) {
var bWidth = this.get('border-box-width'),
mLeft = this.get('margin-left'),
mRight = this.get('margin-right');
if (bWidth <= 0) return 0;
return bWidth + mLeft + mRight;
},
'top': function(element) {
var offset = element.positionedOffset();
return offset.top;
},
'bottom': function(element) {
var offset = element.positionedOffset(),
parent = element.getOffsetParent(),
pHeight = parent.measure('height');
var mHeight = this.get('border-box-height');
return pHeight - mHeight - offset.top;
},
'left': function(element) {
var offset = element.positionedOffset();
return offset.left;
},
'right': function(element) {
var offset = element.positionedOffset(),
parent = element.getOffsetParent(),
pWidth = parent.measure('width');
var mWidth = this.get('border-box-width');
return pWidth - mWidth - offset.left;
},
'padding-top': function(element) {
return getPixelValue(element, 'paddingTop');
},
'padding-bottom': function(element) {
return getPixelValue(element, 'paddingBottom');
},
'padding-left': function(element) {
return getPixelValue(element, 'paddingLeft');
},
'padding-right': function(element) {
return getPixelValue(element, 'paddingRight');
},
'border-top': function(element) {
return getPixelValue(element, 'borderTopWidth');
},
'border-bottom': function(element) {
return getPixelValue(element, 'borderBottomWidth');
},
'border-left': function(element) {
return getPixelValue(element, 'borderLeftWidth');
},
'border-right': function(element) {
return getPixelValue(element, 'borderRightWidth');
},
'margin-top': function(element) {
return getPixelValue(element, 'marginTop');
},
'margin-bottom': function(element) {
return getPixelValue(element, 'marginBottom');
},
'margin-left': function(element) {
return getPixelValue(element, 'marginLeft');
},
'margin-right': function(element) {
return getPixelValue(element, 'marginRight');
}
}
});
if ('getBoundingClientRect' in document.documentElement) {
Object.extend(Element.Layout.COMPUTATIONS, {
'right': function(element) {
var parent = hasLayout(element.getOffsetParent());
var rect = element.getBoundingClientRect(),
pRect = parent.getBoundingClientRect();
return (pRect.right - rect.right).round();
},
'bottom': function(element) {
var parent = hasLayout(element.getOffsetParent());
var rect = element.getBoundingClientRect(),
pRect = parent.getBoundingClientRect();
return (pRect.bottom - rect.bottom).round();
}
});
}
Element.Offset = Class.create({
initialize: function(left, top) {
this.left = left.round();
this.top = top.round();
this[0] = this.left;
this[1] = this.top;
},
relativeTo: function(offset) {
return new Element.Offset(
this.left - offset.left,
this.top - offset.top
);
},
inspect: function() {
return "#<Element.Offset left: #{left} top: #{top}>".interpolate(this);
},
toString: function() {
return "[#{left}, #{top}]".interpolate(this);
},
toArray: function() {
return [this.left, this.top];
}
});
function getLayout(element, preCompute) {
return new Element.Layout(element, preCompute);
}
function measure(element, property) {
return $(element).getLayout().get(property);
}
function getDimensions(element) {
element = $(element);
var display = Element.getStyle(element, 'display');
if (display && display !== 'none') {
return { width: element.offsetWidth, height: element.offsetHeight };
}
var style = element.style;
var originalStyles = {
visibility: style.visibility,
position: style.position,
display: style.display
};
var newStyles = {
visibility: 'hidden',
display: 'block'
};
if (originalStyles.position !== 'fixed')
newStyles.position = 'absolute';
Element.setStyle(element, newStyles);
var dimensions = {
width: element.offsetWidth,
height: element.offsetHeight
};
Element.setStyle(element, originalStyles);
return dimensions;
}
function getOffsetParent(element) {
element = $(element);
if (isDocument(element) || isDetached(element) || isBody(element) || isHtml(element))
return $(document.body);
var isInline = (Element.getStyle(element, 'display') === 'inline');
if (!isInline && element.offsetParent) return $(element.offsetParent);
while ((element = element.parentNode) && element !== document.body) {
if (Element.getStyle(element, 'position') !== 'static') {
return isHtml(element) ? $(document.body) : $(element);
}
}
return $(document.body);
}
function cumulativeOffset(element) {
element = $(element);
var valueT = 0, valueL = 0;
if (element.parentNode) {
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
element = element.offsetParent;
} while (element);
}
return new Element.Offset(valueL, valueT);
}
function positionedOffset(element) {
element = $(element);
var layout = element.getLayout();
var valueT = 0, valueL = 0;
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
element = element.offsetParent;
if (element) {
if (isBody(element)) break;
var p = Element.getStyle(element, 'position');
if (p !== 'static') break;
}
} while (element);
valueL -= layout.get('margin-top');
valueT -= layout.get('margin-left');
return new Element.Offset(valueL, valueT);
}
function cumulativeScrollOffset(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.scrollTop || 0;
valueL += element.scrollLeft || 0;
element = element.parentNode;
} while (element);
return new Element.Offset(valueL, valueT);
}
function viewportOffset(forElement) {
element = $(element);
var valueT = 0, valueL = 0, docBody = document.body;
var element = forElement;
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
if (element.offsetParent == docBody &&
Element.getStyle(element, 'position') == 'absolute') break;
} while (element = element.offsetParent);
element = forElement;
do {
if (element != docBody) {
valueT -= element.scrollTop || 0;
valueL -= element.scrollLeft || 0;
}
} while (element = element.parentNode);
return new Element.Offset(valueL, valueT);
}
function absolutize(element) {
element = $(element);
if (Element.getStyle(element, 'position') === 'absolute') {
return element;
}
var offsetParent = getOffsetParent(element);
var eOffset = element.viewportOffset(),
pOffset = offsetParent.viewportOffset();
var offset = eOffset.relativeTo(pOffset);
var layout = element.getLayout();
element.store('prototype_absolutize_original_styles', {
left: element.getStyle('left'),
top: element.getStyle('top'),
width: element.getStyle('width'),
height: element.getStyle('height')
});
element.setStyle({
position: 'absolute',
top: offset.top + 'px',
left: offset.left + 'px',
width: layout.get('width') + 'px',
height: layout.get('height') + 'px'
});
return element;
}
function relativize(element) {
element = $(element);
if (Element.getStyle(element, 'position') === 'relative') {
return element;
}
var originalStyles =
element.retrieve('prototype_absolutize_original_styles');
if (originalStyles) element.setStyle(originalStyles);
return element;
}
if (Prototype.Browser.IE) {
getOffsetParent = getOffsetParent.wrap(
function(proceed, element) {
element = $(element);
if (isDocument(element) || isDetached(element) || isBody(element) || isHtml(element))
return $(document.body);
var position = element.getStyle('position');
if (position !== 'static') return proceed(element);
element.setStyle({ position: 'relative' });
var value = proceed(element);
element.setStyle({ position: position });
return value;
}
);
positionedOffset = positionedOffset.wrap(function(proceed, element) {
element = $(element);
if (!element.parentNode) return new Element.Offset(0, 0);
var position = element.getStyle('position');
if (position !== 'static') return proceed(element);
var offsetParent = element.getOffsetParent();
if (offsetParent && offsetParent.getStyle('position') === 'fixed')
hasLayout(offsetParent);
element.setStyle({ position: 'relative' });
var value = proceed(element);
element.setStyle({ position: position });
return value;
});
} else if (Prototype.Browser.Webkit) {
cumulativeOffset = function(element) {
element = $(element);
var valueT = 0, valueL = 0;
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
if (element.offsetParent == document.body)
if (Element.getStyle(element, 'position') == 'absolute') break;
element = element.offsetParent;
} while (element);
return new Element.Offset(valueL, valueT);
};
}
Element.addMethods({
getLayout: getLayout,
measure: measure,
getDimensions: getDimensions,
getOffsetParent: getOffsetParent,
cumulativeOffset: cumulativeOffset,
positionedOffset: positionedOffset,
cumulativeScrollOffset: cumulativeScrollOffset,
viewportOffset: viewportOffset,
absolutize: absolutize,
relativize: relativize
});
function isBody(element) {
return element.nodeName.toUpperCase() === 'BODY';
}
function isHtml(element) {
return element.nodeName.toUpperCase() === 'HTML';
}
function isDocument(element) {
return element.nodeType === Node.DOCUMENT_NODE;
}
function isDetached(element) {
return element !== document.body &&
!Element.descendantOf(element, document.body);
}
if ('getBoundingClientRect' in document.documentElement) {
Element.addMethods({
viewportOffset: function(element) {
element = $(element);
if (isDetached(element)) return new Element.Offset(0, 0);
var rect = element.getBoundingClientRect(),
docEl = document.documentElement;
return new Element.Offset(rect.left - docEl.clientLeft,
rect.top - docEl.clientTop);
}
});
}
})();
window.$$ = function() {
var expression = $A(arguments).join(', ');
return Prototype.Selector.select(expression, document);
};
Prototype.Selector = (function() {
function select() {
throw new Error('Method "Prototype.Selector.select" must be defined.');
}
function match() {
throw new Error('Method "Prototype.Selector.match" must be defined.');
}
function find(elements, expression, index) {
index = index || 0;
var match = Prototype.Selector.match, length = elements.length, matchIndex = 0, i;
for (i = 0; i < length; i++) {
if (match(elements[i], expression) && index == matchIndex++) {
return Element.extend(elements[i]);
}
}
}
function extendElements(elements) {
for (var i = 0, length = elements.length; i < length; i++) {
Element.extend(elements[i]);
}
return elements;
}
var K = Prototype.K;
return {
select: select,
match: match,
find: find,
extendElements: (Element.extend === K) ? K : extendElements,
extendElement: Element.extend
};
})();
Prototype._original_property = window.Sizzle;
/*!
* Sizzle CSS Selector Engine - v1.0
* Copyright 2009, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
(function(){
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
done = 0,
toString = Object.prototype.toString,
hasDuplicate = false,
baseHasDuplicate = true;
[0, 0].sort(function(){
baseHasDuplicate = false;
return 0;
});
var Sizzle = function(selector, context, results, seed) {
results = results || [];
var origContext = context = context || document;
if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
var parts = [], m, set, checkSet, check, mode, extra, prune = true, contextXML = isXML(context),
soFar = selector;
while ( (chunker.exec(""), m = chunker.exec(soFar)) !== null ) {
soFar = m[3];
parts.push( m[1] );
if ( m[2] ) {
extra = m[3];
break;
}
}
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context );
} else {
set = Expr.relative[ parts[0] ] ?
[ context ] :
Sizzle( parts.shift(), context );
while ( parts.length ) {
selector = parts.shift();
if ( Expr.relative[ selector ] )
selector += parts.shift();
set = posProcess( selector, set );
}
}
} else {
if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
var ret = Sizzle.find( parts.shift(), context, contextXML );
context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0];
}
if ( context ) {
var ret = seed ?
{ expr: parts.pop(), set: makeArray(seed) } :
Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set;
if ( parts.length > 0 ) {
checkSet = makeArray(set);
} else {
prune = false;
}
while ( parts.length ) {
var cur = parts.pop(), pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, contextXML );
}
} else {
checkSet = parts = [];
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
throw "Syntax error, unrecognized expression: " + (cur || selector);
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context && context.nodeType === 1 ) {
for ( var i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
} else {
for ( var i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
results.push( set[i] );
}
}
}
} else {
makeArray( checkSet, results );
}
if ( extra ) {
Sizzle( extra, origContext, results, seed );
Sizzle.uniqueSort( results );
}
return results;
};
Sizzle.uniqueSort = function(results){
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
results.sort(sortOrder);
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[i-1] ) {
results.splice(i--, 1);
}
}
}
}
return results;
};
Sizzle.matches = function(expr, set){
return Sizzle(expr, null, null, set);
};
Sizzle.find = function(expr, context, isXML){
var set, match;
if ( !expr ) {
return [];
}
for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
var type = Expr.order[i], match;
if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
var left = match[1];
match.splice(1,1);
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace(/\\/g, "");
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = context.getElementsByTagName("*");
}
return {set: set, expr: expr};
};
Sizzle.filter = function(expr, set, inplace, not){
var old = expr, result = [], curLoop = set, match, anyFound,
isXMLFilter = set && set[0] && isXML(set[0]);
while ( expr && set.length ) {
for ( var type in Expr.filter ) {
if ( (match = Expr.match[ type ].exec( expr )) != null ) {
var filter = Expr.filter[ type ], found, item;
anyFound = false;
if ( curLoop == result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
var pass = not ^ !!found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
if ( expr == old ) {
if ( anyFound == null ) {
throw "Syntax error, unrecognized expression: " + expr;
} else {
break;
}
}
old = expr;
}
return curLoop;
};
var Expr = Sizzle.selectors = {
order: [ "ID", "NAME", "TAG" ],
match: {
ID: /#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/
},
leftMatch: {},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function(elem){
return elem.getAttribute("href");
}
},
relative: {
"+": function(checkSet, part, isXML){
var isPartStr = typeof part === "string",
isTag = isPartStr && !/\W/.test(part),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag && !isXML ) {
part = part.toUpperCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function(checkSet, part, isXML){
var isPartStr = typeof part === "string";
if ( isPartStr && !/\W/.test(part) ) {
part = isXML ? part : part.toUpperCase();
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName === part ? parent : false;
}
}
} else {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function(checkSet, part, isXML){
var doneName = done++, checkFn = dirCheck;
if ( !/\W/.test(part) ) {
var nodeCheck = part = isXML ? part : part.toUpperCase();
checkFn = dirNodeCheck;
}
checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
},
"~": function(checkSet, part, isXML){
var doneName = done++, checkFn = dirCheck;
if ( typeof part === "string" && !/\W/.test(part) ) {
var nodeCheck = part = isXML ? part : part.toUpperCase();
checkFn = dirNodeCheck;
}
checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);
}
},
find: {
ID: function(match, context, isXML){
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
return m ? [m] : [];
}
},
NAME: function(match, context, isXML){
if ( typeof context.getElementsByName !== "undefined" ) {
var ret = [], results = context.getElementsByName(match[1]);
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: function(match, context){
return context.getElementsByTagName(match[1]);
}
},
preFilter: {
CLASS: function(match, curLoop, inplace, result, not, isXML){
match = " " + match[1].replace(/\\/g, "") + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").indexOf(match) >= 0) ) {
if ( !inplace )
result.push( elem );
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function(match){
return match[1].replace(/\\/g, "");
},
TAG: function(match, curLoop){
for ( var i = 0; curLoop[i] === false; i++ ){}
return curLoop[i] && isXML(curLoop[i]) ? match[1] : match[1].toUpperCase();
},
CHILD: function(match){
if ( match[1] == "nth" ) {
var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
match[2] == "even" && "2n" || match[2] == "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
match[0] = done++;
return match;
},
ATTR: function(match, curLoop, inplace, result, not, isXML){
var name = match[1].replace(/\\/g, "");
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function(match, curLoop, inplace, result, not){
if ( match[1] === "not" ) {
if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
match[3] = Sizzle(match[3], null, null, curLoop);
} else {
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function(match){
match.unshift( true );
return match;
}
},
filters: {
enabled: function(elem){
return elem.disabled === false && elem.type !== "hidden";
},
disabled: function(elem){
return elem.disabled === true;
},
checked: function(elem){
return elem.checked === true;
},
selected: function(elem){
elem.parentNode.selectedIndex;
return elem.selected === true;
},
parent: function(elem){
return !!elem.firstChild;
},
empty: function(elem){
return !elem.firstChild;
},
has: function(elem, i, match){
return !!Sizzle( match[3], elem ).length;
},
header: function(elem){
return /h\d/i.test( elem.nodeName );
},
text: function(elem){
return "text" === elem.type;
},
radio: function(elem){
return "radio" === elem.type;
},
checkbox: function(elem){
return "checkbox" === elem.type;
},
file: function(elem){
return "file" === elem.type;
},
password: function(elem){
return "password" === elem.type;
},
submit: function(elem){
return "submit" === elem.type;
},
image: function(elem){
return "image" === elem.type;
},
reset: function(elem){
return "reset" === elem.type;
},
button: function(elem){
return "button" === elem.type || elem.nodeName.toUpperCase() === "BUTTON";
},
input: function(elem){
return /input|select|textarea|button/i.test(elem.nodeName);
}
},
setFilters: {
first: function(elem, i){
return i === 0;
},
last: function(elem, i, match, array){
return i === array.length - 1;
},
even: function(elem, i){
return i % 2 === 0;
},
odd: function(elem, i){
return i % 2 === 1;
},
lt: function(elem, i, match){
return i < match[3] - 0;
},
gt: function(elem, i, match){
return i > match[3] - 0;
},
nth: function(elem, i, match){
return match[3] - 0 == i;
},
eq: function(elem, i, match){
return match[3] - 0 == i;
}
},
filter: {
PSEUDO: function(elem, match, i, array){
var name = match[1], filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "contains" ) {
return (elem.textContent || elem.innerText || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
var not = match[3];
for ( var i = 0, l = not.length; i < l; i++ ) {
if ( not[i] === elem ) {
return false;
}
}
return true;
}
},
CHILD: function(elem, match){
var type = match[1], node = elem;
switch (type) {
case 'only':
case 'first':
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) return false;
}
if ( type == 'first') return true;
node = elem;
case 'last':
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) return false;
}
return true;
case 'nth':
var first = match[2], last = match[3];
if ( first == 1 && last == 0 ) {
return true;
}
var doneName = match[0],
parent = elem.parentNode;
if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
var count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent.sizcache = doneName;
}
var diff = elem.nodeIndex - last;
if ( first == 0 ) {
return diff == 0;
} else {
return ( diff % first == 0 && diff / first >= 0 );
}
}
},
ID: function(elem, match){
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
TAG: function(elem, match){
return (match === "*" && elem.nodeType === 1) || elem.nodeName === match;
},
CLASS: function(elem, match){
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
ATTR: function(elem, match){
var name = match[1],
result = Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf(check) >= 0 :
type === "~=" ?
(" " + value + " ").indexOf(check) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value != check :
type === "^=" ?
value.indexOf(check) === 0 :
type === "$=" ?
value.substr(value.length - check.length) === check :
type === "|=" ?
value === check || value.substr(0, check.length + 1) === check + "-" :
false;
},
POS: function(elem, match, i, array){
var name = match[2], filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
var origPOS = Expr.match.POS;
for ( var type in Expr.match ) {
Expr.match[ type ] = new RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source );
Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source );
}
var makeArray = function(array, results) {
array = Array.prototype.slice.call( array, 0 );
if ( results ) {
results.push.apply( results, array );
return results;
}
return array;
};
try {
Array.prototype.slice.call( document.documentElement.childNodes, 0 );
} catch(e){
makeArray = function(array, results) {
var ret = results || [];
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
} else {
if ( typeof array.length === "number" ) {
for ( var i = 0, l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
} else {
for ( var i = 0; array[i]; i++ ) {
ret.push( array[i] );
}
}
}
return ret;
};
}
var sortOrder;
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
if ( a == b ) {
hasDuplicate = true;
}
return 0;
}
var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
if ( ret === 0 ) {
hasDuplicate = true;
}
return ret;
};
} else if ( "sourceIndex" in document.documentElement ) {
sortOrder = function( a, b ) {
if ( !a.sourceIndex || !b.sourceIndex ) {
if ( a == b ) {
hasDuplicate = true;
}
return 0;
}
var ret = a.sourceIndex - b.sourceIndex;
if ( ret === 0 ) {
hasDuplicate = true;
}
return ret;
};
} else if ( document.createRange ) {
sortOrder = function( a, b ) {
if ( !a.ownerDocument || !b.ownerDocument ) {
if ( a == b ) {
hasDuplicate = true;
}
return 0;
}
var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
aRange.setStart(a, 0);
aRange.setEnd(a, 0);
bRange.setStart(b, 0);
bRange.setEnd(b, 0);
var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
if ( ret === 0 ) {
hasDuplicate = true;
}
return ret;
};
}
(function(){
var form = document.createElement("div"),
id = "script" + (new Date).getTime();
form.innerHTML = "<a name='" + id + "'/>";
var root = document.documentElement;
root.insertBefore( form, root.firstChild );
if ( !!document.getElementById( id ) ) {
Expr.find.ID = function(match, context, isXML){
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : [];
}
};
Expr.filter.ID = function(elem, match){
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return elem.nodeType === 1 && node && node.nodeValue === match;
};
}
root.removeChild( form );
root = form = null; // release memory in IE
})();
(function(){
var div = document.createElement("div");
div.appendChild( document.createComment("") );
if ( div.getElementsByTagName("*").length > 0 ) {
Expr.find.TAG = function(match, context){
var results = context.getElementsByTagName(match[1]);
if ( match[1] === "*" ) {
var tmp = [];
for ( var i = 0; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
tmp.push( results[i] );
}
}
results = tmp;
}
return results;
};
}
div.innerHTML = "<a href='#'></a>";
if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
div.firstChild.getAttribute("href") !== "#" ) {
Expr.attrHandle.href = function(elem){
return elem.getAttribute("href", 2);
};
}
div = null; // release memory in IE
})();
if ( document.querySelectorAll ) (function(){
var oldSizzle = Sizzle, div = document.createElement("div");
div.innerHTML = "<p class='TEST'></p>";
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
Sizzle = function(query, context, extra, seed){
context = context || document;
if ( !seed && context.nodeType === 9 && !isXML(context) ) {
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(e){}
}
return oldSizzle(query, context, extra, seed);
};
for ( var prop in oldSizzle ) {
Sizzle[ prop ] = oldSizzle[ prop ];
}
div = null; // release memory in IE
})();
if ( document.getElementsByClassName && document.documentElement.getElementsByClassName ) (function(){
var div = document.createElement("div");
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
if ( div.getElementsByClassName("e").length === 0 )
return;
div.lastChild.className = "e";
if ( div.getElementsByClassName("e").length === 1 )
return;
Expr.order.splice(1, 0, "CLASS");
Expr.find.CLASS = function(match, context, isXML) {
if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
return context.getElementsByClassName(match[1]);
}
};
div = null; // release memory in IE
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
var sibDir = dir == "previousSibling" && !isXML;
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
if ( sibDir && elem.nodeType === 1 ){
elem.sizcache = doneName;
elem.sizset = i;
}
elem = elem[dir];
var match = false;
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 && !isXML ){
elem.sizcache = doneName;
elem.sizset = i;
}
if ( elem.nodeName === cur ) {
match = elem;
break;
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
var sibDir = dir == "previousSibling" && !isXML;
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
if ( sibDir && elem.nodeType === 1 ) {
elem.sizcache = doneName;
elem.sizset = i;
}
elem = elem[dir];
var match = false;
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 ) {
if ( !isXML ) {
elem.sizcache = doneName;
elem.sizset = i;
}
if ( typeof cur !== "string" ) {
if ( elem === cur ) {
match = true;
break;
}
} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
match = elem;
break;
}
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
var contains = document.compareDocumentPosition ? function(a, b){
return a.compareDocumentPosition(b) & 16;
} : function(a, b){
return a !== b && (a.contains ? a.contains(b) : true);
};
var isXML = function(elem){
return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
!!elem.ownerDocument && elem.ownerDocument.documentElement.nodeName !== "HTML";
};
var posProcess = function(selector, context){
var tmpSet = [], later = "", match,
root = context.nodeType ? [context] : context;
while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( Expr.match.PSEUDO, "" );
}
selector = Expr.relative[selector] ? selector + "*" : selector;
for ( var i = 0, l = root.length; i < l; i++ ) {
Sizzle( selector, root[i], tmpSet );
}
return Sizzle.filter( later, tmpSet );
};
window.Sizzle = Sizzle;
})();
;(function(engine) {
var extendElements = Prototype.Selector.extendElements;
function select(selector, scope) {
return extendElements(engine(selector, scope || document));
}
function match(element, selector) {
return engine.matches(selector, [element]).length == 1;
}
Prototype.Selector.engine = engine;
Prototype.Selector.select = select;
Prototype.Selector.match = match;
})(Sizzle);
window.Sizzle = Prototype._original_property;
delete Prototype._original_property;
var Form = {
reset: function(form) {
form = $(form);
form.reset();
return form;
},
serializeElements: function(elements, options) {
if (typeof options != 'object') options = { hash: !!options };
else if (Object.isUndefined(options.hash)) options.hash = true;
var key, value, submitted = false, submit = options.submit, accumulator, initial;
if (options.hash) {
initial = {};
accumulator = function(result, key, value) {
if (key in result) {
if (!Object.isArray(result[key])) result[key] = [result[key]];
result[key].push(value);
} else result[key] = value;
return result;
};
} else {
initial = '';
accumulator = function(result, key, value) {
return result + (result ? '&' : '') + encodeURIComponent(key) + '=' + encodeURIComponent(value);
}
}
return elements.inject(initial, function(result, element) {
if (!element.disabled && element.name) {
key = element.name; value = $(element).getValue();
if (value != null && element.type != 'file' && (element.type != 'submit' || (!submitted &&
submit !== false && (!submit || key == submit) && (submitted = true)))) {
result = accumulator(result, key, value);
}
}
return result;
});
}
};
Form.Methods = {
serialize: function(form, options) {
return Form.serializeElements(Form.getElements(form), options);
},
getElements: function(form) {
var elements = $(form).getElementsByTagName('*'),
element,
arr = [ ],
serializers = Form.Element.Serializers;
for (var i = 0; element = elements[i]; i++) {
arr.push(element);
}
return arr.inject([], function(elements, child) {
if (serializers[child.tagName.toLowerCase()])
elements.push(Element.extend(child));
return elements;
})
},
getInputs: function(form, typeName, name) {
form = $(form);
var inputs = form.getElementsByTagName('input');
if (!typeName && !name) return $A(inputs).map(Element.extend);
for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
var input = inputs[i];
if ((typeName && input.type != typeName) || (name && input.name != name))
continue;
matchingInputs.push(Element.extend(input));
}
return matchingInputs;
},
disable: function(form) {
form = $(form);
Form.getElements(form).invoke('disable');
return form;
},
enable: function(form) {
form = $(form);
Form.getElements(form).invoke('enable');
return form;
},
findFirstElement: function(form) {
var elements = $(form).getElements().findAll(function(element) {
return 'hidden' != element.type && !element.disabled;
});
var firstByIndex = elements.findAll(function(element) {
return element.hasAttribute('tabIndex') && element.tabIndex >= 0;
}).sortBy(function(element) { return element.tabIndex }).first();
return firstByIndex ? firstByIndex : elements.find(function(element) {
return /^(?:input|select|textarea)$/i.test(element.tagName);
});
},
focusFirstElement: function(form) {
form = $(form);
var element = form.findFirstElement();
if (element) element.activate();
return form;
},
request: function(form, options) {
form = $(form), options = Object.clone(options || { });
var params = options.parameters, action = form.readAttribute('action') || '';
if (action.blank()) action = window.location.href;
options.parameters = form.serialize(true);
if (params) {
if (Object.isString(params)) params = params.toQueryParams();
Object.extend(options.parameters, params);
}
if (form.hasAttribute('method') && !options.method)
options.method = form.method;
return new Ajax.Request(action, options);
}
};
/*--------------------------------------------------------------------------*/
Form.Element = {
focus: function(element) {
$(element).focus();
return element;
},
select: function(element) {
$(element).select();
return element;
}
};
Form.Element.Methods = {
serialize: function(element) {
element = $(element);
if (!element.disabled && element.name) {
var value = element.getValue();
if (value != undefined) {
var pair = { };
pair[element.name] = value;
return Object.toQueryString(pair);
}
}
return '';
},
getValue: function(element) {
element = $(element);
var method = element.tagName.toLowerCase();
return Form.Element.Serializers[method](element);
},
setValue: function(element, value) {
element = $(element);
var method = element.tagName.toLowerCase();
Form.Element.Serializers[method](element, value);
return element;
},
clear: function(element) {
$(element).value = '';
return element;
},
present: function(element) {
return $(element).value != '';
},
activate: function(element) {
element = $(element);
try {
element.focus();
if (element.select && (element.tagName.toLowerCase() != 'input' ||
!(/^(?:button|reset|submit)$/i.test(element.type))))
element.select();
} catch (e) { }
return element;
},
disable: function(element) {
element = $(element);
element.disabled = true;
return element;
},
enable: function(element) {
element = $(element);
element.disabled = false;
return element;
}
};
/*--------------------------------------------------------------------------*/
var Field = Form.Element;
var $F = Form.Element.Methods.getValue;
/*--------------------------------------------------------------------------*/
Form.Element.Serializers = (function() {
function input(element, value) {
switch (element.type.toLowerCase()) {
case 'checkbox':
case 'radio':
return inputSelector(element, value);
default:
return valueSelector(element, value);
}
}
function inputSelector(element, value) {
if (Object.isUndefined(value))
return element.checked ? element.value : null;
else element.checked = !!value;
}
function valueSelector(element, value) {
if (Object.isUndefined(value)) return element.value;
else element.value = value;
}
function select(element, value) {
if (Object.isUndefined(value))
return (element.type === 'select-one' ? selectOne : selectMany)(element);
var opt, currentValue, single = !Object.isArray(value);
for (var i = 0, length = element.length; i < length; i++) {
opt = element.options[i];
currentValue = this.optionValue(opt);
if (single) {
if (currentValue == value) {
opt.selected = true;
return;
}
}
else opt.selected = value.include(currentValue);
}
}
function selectOne(element) {
var index = element.selectedIndex;
return index >= 0 ? optionValue(element.options[index]) : null;
}
function selectMany(element) {
var values, length = element.length;
if (!length) return null;
for (var i = 0, values = []; i < length; i++) {
var opt = element.options[i];
if (opt.selected) values.push(optionValue(opt));
}
return values;
}
function optionValue(opt) {
return Element.hasAttribute(opt, 'value') ? opt.value : opt.text;
}
return {
input: input,
inputSelector: inputSelector,
textarea: valueSelector,
select: select,
selectOne: selectOne,
selectMany: selectMany,
optionValue: optionValue,
button: valueSelector
};
})();
/*--------------------------------------------------------------------------*/
Abstract.TimedObserver = Class.create(PeriodicalExecuter, {
initialize: function($super, element, frequency, callback) {
$super(callback, frequency);
this.element = $(element);
this.lastValue = this.getValue();
},
execute: function() {
var value = this.getValue();
if (Object.isString(this.lastValue) && Object.isString(value) ?
this.lastValue != value : String(this.lastValue) != String(value)) {
this.callback(this.element, value);
this.lastValue = value;
}
}
});
Form.Element.Observer = Class.create(Abstract.TimedObserver, {
getValue: function() {
return Form.Element.getValue(this.element);
}
});
Form.Observer = Class.create(Abstract.TimedObserver, {
getValue: function() {
return Form.serialize(this.element);
}
});
/*--------------------------------------------------------------------------*/
Abstract.EventObserver = Class.create({
initialize: function(element, callback) {
this.element = $(element);
this.callback = callback;
this.lastValue = this.getValue();
if (this.element.tagName.toLowerCase() == 'form')
this.registerFormCallbacks();
else
this.registerCallback(this.element);
},
onElementEvent: function() {
var value = this.getValue();
if (this.lastValue != value) {
this.callback(this.element, value);
this.lastValue = value;
}
},
registerFormCallbacks: function() {
Form.getElements(this.element).each(this.registerCallback, this);
},
registerCallback: function(element) {
if (element.type) {
switch (element.type.toLowerCase()) {
case 'checkbox':
case 'radio':
Event.observe(element, 'click', this.onElementEvent.bind(this));
break;
default:
Event.observe(element, 'change', this.onElementEvent.bind(this));
break;
}
}
}
});
Form.Element.EventObserver = Class.create(Abstract.EventObserver, {
getValue: function() {
return Form.Element.getValue(this.element);
}
});
Form.EventObserver = Class.create(Abstract.EventObserver, {
getValue: function() {
return Form.serialize(this.element);
}
});
(function() {
var Event = {
KEY_BACKSPACE: 8,
KEY_TAB: 9,
KEY_RETURN: 13,
KEY_ESC: 27,
KEY_LEFT: 37,
KEY_UP: 38,
KEY_RIGHT: 39,
KEY_DOWN: 40,
KEY_DELETE: 46,
KEY_HOME: 36,
KEY_END: 35,
KEY_PAGEUP: 33,
KEY_PAGEDOWN: 34,
KEY_INSERT: 45,
cache: {}
};
var docEl = document.documentElement;
var MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED = 'onmouseenter' in docEl
&& 'onmouseleave' in docEl;
var isIELegacyEvent = function(event) { return false; };
if (window.attachEvent) {
if (window.addEventListener) {
isIELegacyEvent = function(event) {
return !(event instanceof window.Event);
};
} else {
isIELegacyEvent = function(event) { return true; };
}
}
var _isButton;
function _isButtonForDOMEvents(event, code) {
return event.which ? (event.which === code + 1) : (event.button === code);
}
var legacyButtonMap = { 0: 1, 1: 4, 2: 2 };
function _isButtonForLegacyEvents(event, code) {
return event.button === legacyButtonMap[code];
}
function _isButtonForWebKit(event, code) {
switch (code) {
case 0: return event.which == 1 && !event.metaKey;
case 1: return event.which == 2 || (event.which == 1 && event.metaKey);
case 2: return event.which == 3;
default: return false;
}
}
if (window.attachEvent) {
if (!window.addEventListener) {
_isButton = _isButtonForLegacyEvents;
} else {
_isButton = function(event, code) {
return isIELegacyEvent(event) ? _isButtonForLegacyEvents(event, code) :
_isButtonForDOMEvents(event, code);
}
}
} else if (Prototype.Browser.WebKit) {
_isButton = _isButtonForWebKit;
} else {
_isButton = _isButtonForDOMEvents;
}
function isLeftClick(event) { return _isButton(event, 0) }
function isMiddleClick(event) { return _isButton(event, 1) }
function isRightClick(event) { return _isButton(event, 2) }
function element(event) {
event = Event.extend(event);
var node = event.target, type = event.type,
currentTarget = event.currentTarget;
if (currentTarget && currentTarget.tagName) {
if (type === 'load' || type === 'error' ||
(type === 'click' && currentTarget.tagName.toLowerCase() === 'input'
&& currentTarget.type === 'radio'))
node = currentTarget;
}
if (node.nodeType == Node.TEXT_NODE)
node = node.parentNode;
return Element.extend(node);
}
function findElement(event, expression) {
var element = Event.element(event);
if (!expression) return element;
while (element) {
if (Object.isElement(element) && Prototype.Selector.match(element, expression)) {
return Element.extend(element);
}
element = element.parentNode;
}
}
function pointer(event) {
return { x: pointerX(event), y: pointerY(event) };
}
function pointerX(event) {
var docElement = document.documentElement,
body = document.body || { scrollLeft: 0 };
return event.pageX || (event.clientX +
(docElement.scrollLeft || body.scrollLeft) -
(docElement.clientLeft || 0));
}
function pointerY(event) {
var docElement = document.documentElement,
body = document.body || { scrollTop: 0 };
return event.pageY || (event.clientY +
(docElement.scrollTop || body.scrollTop) -
(docElement.clientTop || 0));
}
function stop(event) {
Event.extend(event);
event.preventDefault();
event.stopPropagation();
event.stopped = true;
}
Event.Methods = {
isLeftClick: isLeftClick,
isMiddleClick: isMiddleClick,
isRightClick: isRightClick,
element: element,
findElement: findElement,
pointer: pointer,
pointerX: pointerX,
pointerY: pointerY,
stop: stop
};
var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
m[name] = Event.Methods[name].methodize();
return m;
});
if (window.attachEvent) {
function _relatedTarget(event) {
var element;
switch (event.type) {
case 'mouseover':
case 'mouseenter':
element = event.fromElement;
break;
case 'mouseout':
case 'mouseleave':
element = event.toElement;
break;
default:
return null;
}
return Element.extend(element);
}
var additionalMethods = {
stopPropagation: function() { this.cancelBubble = true },
preventDefault: function() { this.returnValue = false },
inspect: function() { return '[object Event]' }
};
Event.extend = function(event, element) {
if (!event) return false;
if (!isIELegacyEvent(event)) return event;
if (event._extendedByPrototype) return event;
event._extendedByPrototype = Prototype.emptyFunction;
var pointer = Event.pointer(event);
Object.extend(event, {
target: event.srcElement || element,
relatedTarget: _relatedTarget(event),
pageX: pointer.x,
pageY: pointer.y
});
Object.extend(event, methods);
Object.extend(event, additionalMethods);
return event;
};
} else {
Event.extend = Prototype.K;
}
if (window.addEventListener) {
Event.prototype = window.Event.prototype || document.createEvent('HTMLEvents').__proto__;
Object.extend(Event.prototype, methods);
}
function _createResponder(element, eventName, handler) {
var registry = Element.retrieve(element, 'prototype_event_registry');
if (Object.isUndefined(registry)) {
CACHE.push(element);
registry = Element.retrieve(element, 'prototype_event_registry', $H());
}
var respondersForEvent = registry.get(eventName);
if (Object.isUndefined(respondersForEvent)) {
respondersForEvent = [];
registry.set(eventName, respondersForEvent);
}
if (respondersForEvent.pluck('handler').include(handler)) return false;
var responder;
if (eventName.include(":")) {
responder = function(event) {
if (Object.isUndefined(event.eventName))
return false;
if (event.eventName !== eventName)
return false;
Event.extend(event, element);
handler.call(element, event);
};
} else {
if (!MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED &&
(eventName === "mouseenter" || eventName === "mouseleave")) {
if (eventName === "mouseenter" || eventName === "mouseleave") {
responder = function(event) {
Event.extend(event, element);
var parent = event.relatedTarget;
while (parent && parent !== element) {
try { parent = parent.parentNode; }
catch(e) { parent = element; }
}
if (parent === element) return;
handler.call(element, event);
};
}
} else {
responder = function(event) {
Event.extend(event, element);
handler.call(element, event);
};
}
}
responder.handler = handler;
respondersForEvent.push(responder);
return responder;
}
function _destroyCache() {
for (var i = 0, length = CACHE.length; i < length; i++) {
Event.stopObserving(CACHE[i]);
CACHE[i] = null;
}
}
var CACHE = [];
if (Prototype.Browser.IE)
window.attachEvent('onunload', _destroyCache);
if (Prototype.Browser.WebKit)
window.addEventListener('unload', Prototype.emptyFunction, false);
var _getDOMEventName = Prototype.K,
translations = { mouseenter: "mouseover", mouseleave: "mouseout" };
if (!MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED) {
_getDOMEventName = function(eventName) {
return (translations[eventName] || eventName);
};
}
function observe(element, eventName, handler) {
element = $(element);
var responder = _createResponder(element, eventName, handler);
if (!responder) return element;
if (eventName.include(':')) {
if (element.addEventListener)
element.addEventListener("dataavailable", responder, false);
else {
element.attachEvent("ondataavailable", responder);
element.attachEvent("onlosecapture", responder);
}
} else {
var actualEventName = _getDOMEventName(eventName);
if (element.addEventListener)
element.addEventListener(actualEventName, responder, false);
else
element.attachEvent("on" + actualEventName, responder);
}
return element;
}
function stopObserving(element, eventName, handler) {
element = $(element);
var registry = Element.retrieve(element, 'prototype_event_registry');
if (!registry) return element;
if (!eventName) {
registry.each( function(pair) {
var eventName = pair.key;
stopObserving(element, eventName);
});
return element;
}
var responders = registry.get(eventName);
if (!responders) return element;
if (!handler) {
responders.each(function(r) {
stopObserving(element, eventName, r.handler);
});
return element;
}
var i = responders.length, responder;
while (i--) {
if (responders[i].handler === handler) {
responder = responders[i];
break;
}
}
if (!responder) return element;
if (eventName.include(':')) {
if (element.removeEventListener)
element.removeEventListener("dataavailable", responder, false);
else {
element.detachEvent("ondataavailable", responder);
element.detachEvent("onlosecapture", responder);
}
} else {
var actualEventName = _getDOMEventName(eventName);
if (element.removeEventListener)
element.removeEventListener(actualEventName, responder, false);
else
element.detachEvent('on' + actualEventName, responder);
}
registry.set(eventName, responders.without(responder));
return element;
}
function fire(element, eventName, memo, bubble) {
element = $(element);
if (Object.isUndefined(bubble))
bubble = true;
if (element == document && document.createEvent && !element.dispatchEvent)
element = document.documentElement;
var event;
if (document.createEvent) {
event = document.createEvent('HTMLEvents');
event.initEvent('dataavailable', bubble, true);
} else {
event = document.createEventObject();
event.eventType = bubble ? 'ondataavailable' : 'onlosecapture';
}
event.eventName = eventName;
event.memo = memo || { };
if (document.createEvent)
element.dispatchEvent(event);
else
element.fireEvent(event.eventType, event);
return Event.extend(event);
}
Event.Handler = Class.create({
initialize: function(element, eventName, selector, callback) {
this.element = $(element);
this.eventName = eventName;
this.selector = selector;
this.callback = callback;
this.handler = this.handleEvent.bind(this);
},
start: function() {
Event.observe(this.element, this.eventName, this.handler);
return this;
},
stop: function() {
Event.stopObserving(this.element, this.eventName, this.handler);
return this;
},
handleEvent: function(event) {
var element = Event.findElement(event, this.selector);
if (element) this.callback.call(this.element, event, element);
}
});
function on(element, eventName, selector, callback) {
element = $(element);
if (Object.isFunction(selector) && Object.isUndefined(callback)) {
callback = selector, selector = null;
}
return new Event.Handler(element, eventName, selector, callback).start();
}
Object.extend(Event, Event.Methods);
Object.extend(Event, {
fire: fire,
observe: observe,
stopObserving: stopObserving,
on: on
});
Element.addMethods({
fire: fire,
observe: observe,
stopObserving: stopObserving,
on: on
});
Object.extend(document, {
fire: fire.methodize(),
observe: observe.methodize(),
stopObserving: stopObserving.methodize(),
on: on.methodize(),
loaded: false
});
if (window.Event) Object.extend(window.Event, Event);
else window.Event = Event;
})();
(function() {
/* Support for the DOMContentLoaded event is based on work by Dan Webb,
Matthias Miller, Dean Edwards, John Resig, and Diego Perini. */
var timer;
function fireContentLoadedEvent() {
if (document.loaded) return;
if (timer) window.clearTimeout(timer);
document.loaded = true;
document.fire('dom:loaded');
}
function checkReadyState() {
if (document.readyState === 'complete') {
document.stopObserving('readystatechange', checkReadyState);
fireContentLoadedEvent();
}
}
function pollDoScroll() {
try { document.documentElement.doScroll('left'); }
catch(e) {
timer = pollDoScroll.defer();
return;
}
fireContentLoadedEvent();
}
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', fireContentLoadedEvent, false);
} else {
document.observe('readystatechange', checkReadyState);
if (window == top)
timer = pollDoScroll.defer();
}
Event.observe(window, 'load', fireContentLoadedEvent);
})();
Element.addMethods();
/*------------------------------- DEPRECATED -------------------------------*/
Hash.toQueryString = Object.toQueryString;
var Toggle = { display: Element.toggle };
Element.Methods.childOf = Element.Methods.descendantOf;
var Insertion = {
Before: function(element, content) {
return Element.insert(element, {before:content});
},
Top: function(element, content) {
return Element.insert(element, {top:content});
},
Bottom: function(element, content) {
return Element.insert(element, {bottom:content});
},
After: function(element, content) {
return Element.insert(element, {after:content});
}
};
var $continue = new Error('"throw $continue" is deprecated, use "return" instead');
var Position = {
includeScrollOffsets: false,
prepare: function() {
this.deltaX = window.pageXOffset
|| document.documentElement.scrollLeft
|| document.body.scrollLeft
|| 0;
this.deltaY = window.pageYOffset
|| document.documentElement.scrollTop
|| document.body.scrollTop
|| 0;
},
within: function(element, x, y) {
if (this.includeScrollOffsets)
return this.withinIncludingScrolloffsets(element, x, y);
this.xcomp = x;
this.ycomp = y;
this.offset = Element.cumulativeOffset(element);
return (y >= this.offset[1] &&
y < this.offset[1] + element.offsetHeight &&
x >= this.offset[0] &&
x < this.offset[0] + element.offsetWidth);
},
withinIncludingScrolloffsets: function(element, x, y) {
var offsetcache = Element.cumulativeScrollOffset(element);
this.xcomp = x + offsetcache[0] - this.deltaX;
this.ycomp = y + offsetcache[1] - this.deltaY;
this.offset = Element.cumulativeOffset(element);
return (this.ycomp >= this.offset[1] &&
this.ycomp < this.offset[1] + element.offsetHeight &&
this.xcomp >= this.offset[0] &&
this.xcomp < this.offset[0] + element.offsetWidth);
},
overlap: function(mode, element) {
if (!mode) return 0;
if (mode == 'vertical')
return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
element.offsetHeight;
if (mode == 'horizontal')
return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
element.offsetWidth;
},
cumulativeOffset: Element.Methods.cumulativeOffset,
positionedOffset: Element.Methods.positionedOffset,
absolutize: function(element) {
Position.prepare();
return Element.absolutize(element);
},
relativize: function(element) {
Position.prepare();
return Element.relativize(element);
},
realOffset: Element.Methods.cumulativeScrollOffset,
offsetParent: Element.Methods.getOffsetParent,
page: Element.Methods.viewportOffset,
clone: function(source, target, options) {
options = options || { };
return Element.clonePosition(target, source, options);
}
};
/*--------------------------------------------------------------------------*/
if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){
function iter(name) {
return name.blank() ? null : "[contains(concat(' ', @class, ' '), ' " + name + " ')]";
}
instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ?
function(element, className) {
className = className.toString().strip();
var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className);
return cond ? document._getElementsByXPath('.//*' + cond, element) : [];
} : function(element, className) {
className = className.toString().strip();
var elements = [], classNames = (/\s/.test(className) ? $w(className) : null);
if (!classNames && !className) return elements;
var nodes = $(element).getElementsByTagName('*');
className = ' ' + className + ' ';
for (var i = 0, child, cn; child = nodes[i]; i++) {
if (child.className && (cn = ' ' + child.className + ' ') && (cn.include(className) ||
(classNames && classNames.all(function(name) {
return !name.toString().blank() && cn.include(' ' + name + ' ');
}))))
elements.push(Element.extend(child));
}
return elements;
};
return function(className, parentElement) {
return $(parentElement || document.body).getElementsByClassName(className);
};
}(Element.Methods);
/*--------------------------------------------------------------------------*/
Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
initialize: function(element) {
this.element = $(element);
},
_each: function(iterator) {
this.element.className.split(/\s+/).select(function(name) {
return name.length > 0;
})._each(iterator);
},
set: function(className) {
this.element.className = className;
},
add: function(classNameToAdd) {
if (this.include(classNameToAdd)) return;
this.set($A(this).concat(classNameToAdd).join(' '));
},
remove: function(classNameToRemove) {
if (!this.include(classNameToRemove)) return;
this.set($A(this).without(classNameToRemove).join(' '));
},
toString: function() {
return $A(this).join(' ');
}
};
Object.extend(Element.ClassNames.prototype, Enumerable);
/*--------------------------------------------------------------------------*/
(function() {
window.Selector = Class.create({
initialize: function(expression) {
this.expression = expression.strip();
},
findElements: function(rootElement) {
return Prototype.Selector.select(this.expression, rootElement);
},
match: function(element) {
return Prototype.Selector.match(element, this.expression);
},
toString: function() {
return this.expression;
},
inspect: function() {
return "#<Selector: " + this.expression + ">";
}
});
Object.extend(Selector, {
matchElements: function(elements, expression) {
var match = Prototype.Selector.match,
results = [];
for (var i = 0, length = elements.length; i < length; i++) {
var element = elements[i];
if (match(element, expression)) {
results.push(Element.extend(element));
}
}
return results;
},
findElement: function(elements, expression, index) {
index = index || 0;
var matchIndex = 0, element;
for (var i = 0, length = elements.length; i < length; i++) {
element = elements[i];
if (Prototype.Selector.match(element, expression) && index === matchIndex++) {
return Element.extend(element);
}
}
},
findChildElements: function(element, expressions) {
var selector = expressions.toArray().join(', ');
return Prototype.Selector.select(selector, element || document);
}
});
})();
// Credit Card Validation Javascript
// copyright 12th May 2003, by Stephen Chapman, Felgall Pty Ltd
// You have permission to copy and use this javascript provided that
// the content of the script is not changed in any way.
function validateCreditCard(s) {
// remove non-numerics
var v = "0123456789";
var w = "";
for (i=0; i < s.length; i++) {
x = s.charAt(i);
if (v.indexOf(x,0) != -1)
w += x;
}
// validate number
j = w.length / 2;
k = Math.floor(j);
m = Math.ceil(j) - k;
c = 0;
for (i=0; i<k; i++) {
a = w.charAt(i*2+m) * 2;
c += a > 9 ? Math.floor(a/10 + a%10) : a;
}
for (i=0; i<k+m; i++) c += w.charAt(i*2+1-m) * 1;
return (c%10 == 0);
}
/*
* Really easy field validation with Prototype
* http://tetlaw.id.au/view/javascript/really-easy-field-validation
* Andrew Tetlaw
* Version 1.5.4.1 (2007-01-05)
*
* Copyright (c) 2007 Andrew Tetlaw
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
var Validator = Class.create();
Validator.prototype = {
initialize : function(className, error, test, options) {
if(typeof test == 'function'){
this.options = $H(options);
this._test = test;
} else {
this.options = $H(test);
this._test = function(){return true};
}
this.error = error || 'Validation failed.';
this.className = className;
},
test : function(v, elm) {
return (this._test(v,elm) && this.options.all(function(p){
return Validator.methods[p.key] ? Validator.methods[p.key](v,elm,p.value) : true;
}));
}
}
Validator.methods = {
pattern : function(v,elm,opt) {return Validation.get('IsEmpty').test(v) || opt.test(v)},
minLength : function(v,elm,opt) {return v.length >= opt},
maxLength : function(v,elm,opt) {return v.length <= opt},
min : function(v,elm,opt) {return v >= parseFloat(opt)},
max : function(v,elm,opt) {return v <= parseFloat(opt)},
notOneOf : function(v,elm,opt) {return $A(opt).all(function(value) {
return v != value;
})},
oneOf : function(v,elm,opt) {return $A(opt).any(function(value) {
return v == value;
})},
is : function(v,elm,opt) {return v == opt},
isNot : function(v,elm,opt) {return v != opt},
equalToField : function(v,elm,opt) {return v == $F(opt)},
notEqualToField : function(v,elm,opt) {return v != $F(opt)},
include : function(v,elm,opt) {return $A(opt).all(function(value) {
return Validation.get(value).test(v,elm);
})}
}
var Validation = Class.create();
Validation.defaultOptions = {
onSubmit : true,
stopOnFirst : false,
immediate : false,
focusOnError : true,
useTitles : false,
addClassNameToContainer: false,
containerClassName: '.input-box',
onFormValidate : function(result, form) {},
onElementValidate : function(result, elm) {}
};
Validation.prototype = {
initialize : function(form, options){
this.form = $(form);
if (!this.form) {
return;
}
this.options = Object.extend({
onSubmit : Validation.defaultOptions.onSubmit,
stopOnFirst : Validation.defaultOptions.stopOnFirst,
immediate : Validation.defaultOptions.immediate,
focusOnError : Validation.defaultOptions.focusOnError,
useTitles : Validation.defaultOptions.useTitles,
onFormValidate : Validation.defaultOptions.onFormValidate,
onElementValidate : Validation.defaultOptions.onElementValidate
}, options || {});
if(this.options.onSubmit) Event.observe(this.form,'submit',this.onSubmit.bind(this),false);
if(this.options.immediate) {
Form.getElements(this.form).each(function(input) { // Thanks Mike!
if (input.tagName.toLowerCase() == 'select') {
Event.observe(input, 'blur', this.onChange.bindAsEventListener(this));
}
if (input.type.toLowerCase() == 'radio' || input.type.toLowerCase() == 'checkbox') {
Event.observe(input, 'click', this.onChange.bindAsEventListener(this));
} else {
Event.observe(input, 'change', this.onChange.bindAsEventListener(this));
}
}, this);
}
},
onChange : function (ev) {
Validation.isOnChange = true;
Validation.validate(Event.element(ev),{
useTitle : this.options.useTitles,
onElementValidate : this.options.onElementValidate
});
Validation.isOnChange = false;
},
onSubmit : function(ev){
if(!this.validate()) Event.stop(ev);
},
validate : function() {
var result = false;
var useTitles = this.options.useTitles;
var callback = this.options.onElementValidate;
try {
if(this.options.stopOnFirst) {
result = Form.getElements(this.form).all(function(elm) {
if (elm.hasClassName('local-validation') && !this.isElementInForm(elm, this.form)) {
return true;
}
return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback});
}, this);
} else {
result = Form.getElements(this.form).collect(function(elm) {
if (elm.hasClassName('local-validation') && !this.isElementInForm(elm, this.form)) {
return true;
}
return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback});
}, this).all();
}
} catch (e) {
}
if(!result && this.options.focusOnError) {
try{
Form.getElements(this.form).findAll(function(elm){return $(elm).hasClassName('validation-failed')}).first().focus()
}
catch(e){
}
}
this.options.onFormValidate(result, this.form);
return result;
},
reset : function() {
Form.getElements(this.form).each(Validation.reset);
},
isElementInForm : function(elm, form) {
var domForm = elm.up('form');
if (domForm == form) {
return true;
}
return false;
}
}
Object.extend(Validation, {
validate : function(elm, options){
options = Object.extend({
useTitle : false,
onElementValidate : function(result, elm) {}
}, options || {});
elm = $(elm);
var cn = $w(elm.className);
return result = cn.all(function(value) {
var test = Validation.test(value,elm,options.useTitle);
options.onElementValidate(test, elm);
return test;
});
},
insertAdvice : function(elm, advice){
var container = $(elm).up('.field-row');
if(container){
Element.insert(container, {after: advice});
} else if (elm.up('td.value')) {
elm.up('td.value').insert({bottom: advice});
} else if (elm.advaiceContainer && $(elm.advaiceContainer)) {
$(elm.advaiceContainer).update(advice);
}
else {
switch (elm.type.toLowerCase()) {
case 'checkbox':
case 'radio':
var p = elm.parentNode;
if(p) {
Element.insert(p, {'bottom': advice});
} else {
Element.insert(elm, {'after': advice});
}
break;
default:
Element.insert(elm, {'after': advice});
}
}
},
showAdvice : function(elm, advice, adviceName){
if(!elm.advices){
elm.advices = new Hash();
}
else{
elm.advices.each(function(pair){
if (!advice || pair.value.id != advice.id) {
// hide non-current advice after delay
this.hideAdvice(elm, pair.value);
}
}.bind(this));
}
elm.advices.set(adviceName, advice);
if(typeof Effect == 'undefined') {
advice.style.display = 'block';
} else {
if(!advice._adviceAbsolutize) {
new Effect.Appear(advice, {duration : 1 });
} else {
Position.absolutize(advice);
advice.show();
advice.setStyle({
'top':advice._adviceTop,
'left': advice._adviceLeft,
'width': advice._adviceWidth,
'z-index': 1000
});
advice.addClassName('advice-absolute');
}
}
},
hideAdvice : function(elm, advice){
if (advice != null) {
new Effect.Fade(advice, {duration : 1, afterFinishInternal : function() {advice.hide();}});
}
},
updateCallback : function(elm, status) {
if (typeof elm.callbackFunction != 'undefined') {
eval(elm.callbackFunction+'(\''+elm.id+'\',\''+status+'\')');
}
},
ajaxError : function(elm, errorMsg) {
var name = 'validate-ajax';
var advice = Validation.getAdvice(name, elm);
if (advice == null) {
advice = this.createAdvice(name, elm, false, errorMsg);
}
this.showAdvice(elm, advice, 'validate-ajax');
this.updateCallback(elm, 'failed');
elm.addClassName('validation-failed');
elm.addClassName('validate-ajax');
if (Validation.defaultOptions.addClassNameToContainer && Validation.defaultOptions.containerClassName != '') {
var container = elm.up(Validation.defaultOptions.containerClassName);
if (container && this.allowContainerClassName(elm)) {
container.removeClassName('validation-passed');
container.addClassName('validation-error');
}
}
},
allowContainerClassName: function (elm) {
if (elm.type == 'radio' || elm.type == 'checkbox') {
return elm.hasClassName('change-container-classname');
}
return true;
},
test : function(name, elm, useTitle) {
var v = Validation.get(name);
var prop = '__advice'+name.camelize();
try {
if(Validation.isVisible(elm) && !v.test($F(elm), elm)) {
//if(!elm[prop]) {
var advice = Validation.getAdvice(name, elm);
if (advice == null) {
advice = this.createAdvice(name, elm, useTitle);
}
this.showAdvice(elm, advice, name);
this.updateCallback(elm, 'failed');
//}
elm[prop] = 1;
if (!elm.advaiceContainer) {
elm.removeClassName('validation-passed');
elm.addClassName('validation-failed');
}
if (Validation.defaultOptions.addClassNameToContainer && Validation.defaultOptions.containerClassName != '') {
var container = elm.up(Validation.defaultOptions.containerClassName);
if (container && this.allowContainerClassName(elm)) {
container.removeClassName('validation-passed');
container.addClassName('validation-error');
}
}
return false;
} else {
var advice = Validation.getAdvice(name, elm);
this.hideAdvice(elm, advice);
this.updateCallback(elm, 'passed');
elm[prop] = '';
elm.removeClassName('validation-failed');
elm.addClassName('validation-passed');
if (Validation.defaultOptions.addClassNameToContainer && Validation.defaultOptions.containerClassName != '') {
var container = elm.up(Validation.defaultOptions.containerClassName);
if (container && !container.down('.validation-failed') && this.allowContainerClassName(elm)) {
if (!Validation.get('IsEmpty').test(elm.value) || !this.isVisible(elm)) {
container.addClassName('validation-passed');
} else {
container.removeClassName('validation-passed');
}
container.removeClassName('validation-error');
}
}
return true;
}
} catch(e) {
throw(e)
}
},
isVisible : function(elm) {
while(elm.tagName != 'BODY') {
if(!$(elm).visible()) return false;
elm = elm.parentNode;
}
return true;
},
getAdvice : function(name, elm) {
return $('advice-' + name + '-' + Validation.getElmID(elm)) || $('advice-' + Validation.getElmID(elm));
},
createAdvice : function(name, elm, useTitle, customError) {
var v = Validation.get(name);
var errorMsg = useTitle ? ((elm && elm.title) ? elm.title : v.error) : v.error;
if (customError) {
errorMsg = customError;
}
try {
if (Translator){
errorMsg = Translator.translate(errorMsg);
}
}
catch(e){}
advice = '<div class="validation-advice" id="advice-' + name + '-' + Validation.getElmID(elm) +'" style="display:none">' + errorMsg + '</div>'
Validation.insertAdvice(elm, advice);
advice = Validation.getAdvice(name, elm);
if($(elm).hasClassName('absolute-advice')) {
var dimensions = $(elm).getDimensions();
var originalPosition = Position.cumulativeOffset(elm);
advice._adviceTop = (originalPosition[1] + dimensions.height) + 'px';
advice._adviceLeft = (originalPosition[0]) + 'px';
advice._adviceWidth = (dimensions.width) + 'px';
advice._adviceAbsolutize = true;
}
return advice;
},
getElmID : function(elm) {
return elm.id ? elm.id : elm.name;
},
reset : function(elm) {
elm = $(elm);
var cn = $w(elm.className);
cn.each(function(value) {
var prop = '__advice'+value.camelize();
if(elm[prop]) {
var advice = Validation.getAdvice(value, elm);
if (advice) {
advice.hide();
}
elm[prop] = '';
}
elm.removeClassName('validation-failed');
elm.removeClassName('validation-passed');
if (Validation.defaultOptions.addClassNameToContainer && Validation.defaultOptions.containerClassName != '') {
var container = elm.up(Validation.defaultOptions.containerClassName);
if (container) {
container.removeClassName('validation-passed');
container.removeClassName('validation-error');
}
}
});
},
add : function(className, error, test, options) {
var nv = {};
nv[className] = new Validator(className, error, test, options);
Object.extend(Validation.methods, nv);
},
addAllThese : function(validators) {
var nv = {};
$A(validators).each(function(value) {
nv[value[0]] = new Validator(value[0], value[1], value[2], (value.length > 3 ? value[3] : {}));
});
Object.extend(Validation.methods, nv);
},
get : function(name) {
return Validation.methods[name] ? Validation.methods[name] : Validation.methods['_LikeNoIDIEverSaw_'];
},
methods : {
'_LikeNoIDIEverSaw_' : new Validator('_LikeNoIDIEverSaw_','',{})
}
});
Validation.add('IsEmpty', '', function(v) {
return (v == '' || (v == null) || (v.length == 0) || /^\s+$/.test(v));
});
Validation.addAllThese([
['validate-no-html-tags', 'HTML tags are not allowed', function(v) {
return !/<(\/)?\w+/.test(v);
}],
['validate-select', 'Please select an option.', function(v) {
return ((v != "none") && (v != null) && (v.length != 0));
}],
['required-entry', 'This is a required field.', function(v) {
return !Validation.get('IsEmpty').test(v);
}],
['validate-number', 'Please enter a valid number in this field.', function(v) {
return Validation.get('IsEmpty').test(v)
|| (!isNaN(parseNumber(v)) && /^\s*-?\d*(\.\d*)?\s*$/.test(v));
}],
['validate-number-range', 'The value is not within the specified range.', function(v, elm) {
if (Validation.get('IsEmpty').test(v)) {
return true;
}
var numValue = parseNumber(v);
if (isNaN(numValue)) {
return false;
}
var reRange = /^number-range-(-?[\d.,]+)?-(-?[\d.,]+)?$/,
result = true;
$w(elm.className).each(function(name) {
var m = reRange.exec(name);
if (m) {
result = result
&& (m[1] == null || m[1] == '' || numValue >= parseNumber(m[1]))
&& (m[2] == null || m[2] == '' || numValue <= parseNumber(m[2]));
}
});
return result;
}],
['validate-digits', 'Please use numbers only in this field. Please avoid spaces or other characters such as dots or commas.', function(v) {
return Validation.get('IsEmpty').test(v) || !/[^\d]/.test(v);
}],
['validate-digits-range', 'The value is not within the specified range.', function(v, elm) {
if (Validation.get('IsEmpty').test(v)) {
return true;
}
var numValue = parseNumber(v);
if (isNaN(numValue)) {
return false;
}
var reRange = /^digits-range-(-?\d+)?-(-?\d+)?$/,
result = true;
$w(elm.className).each(function(name) {
var m = reRange.exec(name);
if (m) {
result = result
&& (m[1] == null || m[1] == '' || numValue >= parseNumber(m[1]))
&& (m[2] == null || m[2] == '' || numValue <= parseNumber(m[2]));
}
});
return result;
}],
['validate-alpha', 'Please use letters only (a-z or A-Z) in this field.', function (v) {
return Validation.get('IsEmpty').test(v) || /^[a-zA-Z]+$/.test(v)
}],
['validate-code', 'Please use only letters (a-z), numbers (0-9) or underscore(_) in this field, first character should be a letter.', function (v) {
return Validation.get('IsEmpty').test(v) || /^[a-z]+[a-z0-9_]+$/.test(v)
}],
['validate-alphanum', 'Please use only letters (a-z or A-Z) or numbers (0-9) only in this field. No spaces or other characters are allowed.', function(v) {
return Validation.get('IsEmpty').test(v) || /^[a-zA-Z0-9]+$/.test(v)
}],
['validate-alphanum-with-spaces', 'Please use only letters (a-z or A-Z), numbers (0-9) or spaces only in this field.', function(v) {
return Validation.get('IsEmpty').test(v) || /^[a-zA-Z0-9 ]+$/.test(v)
}],
['validate-street', 'Please use only letters (a-z or A-Z) or numbers (0-9) or spaces and # only in this field.', function(v) {
return Validation.get('IsEmpty').test(v) || /^[ \w]{3,}([A-Za-z]\.)?([ \w]*\#\d+)?(\r\n| )[ \w]{3,}/.test(v)
}],
['validate-phoneStrict', 'Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.', function(v) {
return Validation.get('IsEmpty').test(v) || /^(\()?\d{3}(\))?(-|\s)?\d{3}(-|\s)\d{4}$/.test(v);
}],
['validate-phoneLax', 'Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.', function(v) {
return Validation.get('IsEmpty').test(v) || /^((\d[-. ]?)?((\(\d{3}\))|\d{3}))?[-. ]?\d{3}[-. ]?\d{4}$/.test(v);
}],
['validate-fax', 'Please enter a valid fax number. For example (123) 456-7890 or 123-456-7890.', function(v) {
return Validation.get('IsEmpty').test(v) || /^(\()?\d{3}(\))?(-|\s)?\d{3}(-|\s)\d{4}$/.test(v);
}],
['validate-date', 'Please enter a valid date.', function(v) {
var test = new Date(v);
return Validation.get('IsEmpty').test(v) || !isNaN(test);
}],
['validate-date-range', 'The From Date value should be less than or equal to the To Date value.', function(v, elm) {
var m = /\bdate-range-(\w+)-(\w+)\b/.exec(elm.className);
if (!m || m[2] == 'to' || Validation.get('IsEmpty').test(v)) {
return true;
}
var currentYear = new Date().getFullYear() + '';
var normalizedTime = function(v) {
v = v.split(/[.\/]/);
if (v[2] && v[2].length < 4) {
v[2] = currentYear.substr(0, v[2].length) + v[2];
}
return new Date(v.join('/')).getTime();
};
var dependentElements = Element.select(elm.form, '.validate-date-range.date-range-' + m[1] + '-to');
return !dependentElements.length || Validation.get('IsEmpty').test(dependentElements[0].value)
|| normalizedTime(v) <= normalizedTime(dependentElements[0].value);
}],
['validate-email', 'Please enter a valid email address. For example johndoe@domain.com.', function (v) {
//return Validation.get('IsEmpty').test(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v)
//return Validation.get('IsEmpty').test(v) || /^[\!\#$%\*/?|\^\{\}`~&\'\+\-=_a-z0-9][\!\#$%\*/?|\^\{\}`~&\'\+\-=_a-z0-9\.]{1,30}[\!\#$%\*/?|\^\{\}`~&\'\+\-=_a-z0-9]@([a-z0-9_-]{1,30}\.){1,5}[a-z]{2,4}$/i.test(v)
return Validation.get('IsEmpty').test(v) || /^([a-z0-9,!\#\$%&'\*\+\/=\?\^_`\{\|\}~-]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z0-9,!\#\$%&'\*\+\/=\?\^_`\{\|\}~-]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*@([a-z0-9-]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z0-9-]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*\.(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]){2,})$/i.test(v)
}],
['validate-emailSender', 'Please use only visible characters and spaces.', function (v) {
return Validation.get('IsEmpty').test(v) || /^[\S ]+$/.test(v)
}],
['validate-password', 'Please enter 6 or more characters. Leading or trailing spaces will be ignored.', function(v) {
var pass=v.strip(); /*strip leading and trailing spaces*/
return !(pass.length>0 && pass.length < 6);
}],
['validate-admin-password', 'Please enter 7 or more characters. Password should contain both numeric and alphabetic characters.', function(v) {
var pass=v.strip();
if (0 == pass.length) {
return true;
}
if (!(/[a-z]/i.test(v)) || !(/[0-9]/.test(v))) {
return false;
}
return !(pass.length < 7);
}],
['validate-cpassword', 'Please make sure your passwords match.', function(v) {
var conf = $('confirmation') ? $('confirmation') : $$('.validate-cpassword')[0];
var pass = false;
if ($('password')) {
pass = $('password');
}
var passwordElements = $$('.validate-password');
for (var i = 0; i < passwordElements.size(); i++) {
var passwordElement = passwordElements[i];
if (passwordElement.up('form').id == conf.up('form').id) {
pass = passwordElement;
}
}
conf_pass = v;
if ($$('.validate-admin-password').size()) {
pass = $$('.validate-admin-password')[0];
}
// solves IE7 match for confirmation password
return (pass.value == conf_pass);
}],
['validate-both-passwords', 'Please make sure your passwords match.', function(v, input) {
var dependentInput = $(input.form[input.name == 'password' ? 'confirmation' : 'password']),
isEqualValues = input.value == dependentInput.value;
if (isEqualValues && dependentInput.hasClassName('validation-failed')) {
Validation.test(this.className, dependentInput);
}
return dependentInput.value == '' || isEqualValues;
}],
['validate-url', 'Please enter a valid URL. Protocol is required (http://, https:// or ftp://)', function (v) {
v = (v || '').replace(/^\s+/, '').replace(/\s+$/, '');
return Validation.get('IsEmpty').test(v) || /^(https?|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(v)
}],
['validate-clean-url', 'Please enter a valid URL. For example http://www.example.com or www.example.com', function (v) {
return Validation.get('IsEmpty').test(v) || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i.test(v) || /^(www)((\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i.test(v)
}],
['validate-identifier', 'Please enter a valid URL Key. For example "example-page", "example-page.html" or "anotherlevel/example-page".', function (v) {
return Validation.get('IsEmpty').test(v) || /^[a-z0-9][a-z0-9_\/-]+(\.[a-z0-9_-]+)?$/.test(v)
}],
['validate-xml-identifier', 'Please enter a valid XML-identifier. For example something_1, block5, id-4.', function (v) {
return Validation.get('IsEmpty').test(v) || /^[A-Z][A-Z0-9_\/-]*$/i.test(v)
}],
['validate-ssn', 'Please enter a valid social security number. For example 123-45-6789.', function(v) {
return Validation.get('IsEmpty').test(v) || /^\d{3}-?\d{2}-?\d{4}$/.test(v);
}],
['validate-zip', 'Please enter a valid zip code. For example 90602 or 90602-1234.', function(v) {
return Validation.get('IsEmpty').test(v) || /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(v);
}],
['validate-zip-international', 'Please enter a valid zip code.', function(v) {
//return Validation.get('IsEmpty').test(v) || /(^[A-z0-9]{2,10}([\s]{0,1}|[\-]{0,1})[A-z0-9]{2,10}$)/.test(v);
return true;
}],
['validate-date-au', 'Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.', function(v) {
if(Validation.get('IsEmpty').test(v)) return true;
var regex = /^(\d{2})\/(\d{2})\/(\d{4})$/;
if(!regex.test(v)) return false;
var d = new Date(v.replace(regex, '$2/$1/$3'));
return ( parseInt(RegExp.$2, 10) == (1+d.getMonth()) ) &&
(parseInt(RegExp.$1, 10) == d.getDate()) &&
(parseInt(RegExp.$3, 10) == d.getFullYear() );
}],
['validate-currency-dollar', 'Please enter a valid $ amount. For example $100.00.', function(v) {
// [$]1[##][,###]+[.##]
// [$]1###+[.##]
// [$]0.##
// [$].##
return Validation.get('IsEmpty').test(v) || /^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/.test(v)
}],
['validate-one-required', 'Please select one of the above options.', function (v,elm) {
var p = elm.parentNode;
var options = p.getElementsByTagName('INPUT');
return $A(options).any(function(elm) {
return $F(elm);
});
}],
['validate-one-required-by-name', 'Please select one of the options.', function (v,elm) {
var inputs = $$('input[name="' + elm.name.replace(/([\\"])/g, '\\$1') + '"]');
var error = 1;
for(var i=0;i<inputs.length;i++) {
if((inputs[i].type == 'checkbox' || inputs[i].type == 'radio') && inputs[i].checked == true) {
error = 0;
}
if(Validation.isOnChange && (inputs[i].type == 'checkbox' || inputs[i].type == 'radio')) {
Validation.reset(inputs[i]);
}
}
if( error == 0 ) {
return true;
} else {
return false;
}
}],
['validate-not-negative-number', 'Please enter a number 0 or greater in this field.', function(v) {
if (Validation.get('IsEmpty').test(v)) {
return true;
}
v = parseNumber(v);
return !isNaN(v) && v >= 0;
}],
['validate-zero-or-greater', 'Please enter a number 0 or greater in this field.', function(v) {
return Validation.get('validate-not-negative-number').test(v);
}],
['validate-greater-than-zero', 'Please enter a number greater than 0 in this field.', function(v) {
if (Validation.get('IsEmpty').test(v)) {
return true;
}
v = parseNumber(v);
return !isNaN(v) && v > 0;
}],
['validate-state', 'Please select State/Province.', function(v) {
return (v!=0 || v == '');
}],
['validate-new-password', 'Please enter 6 or more characters. Leading or trailing spaces will be ignored.', function(v) {
if (!Validation.get('validate-password').test(v)) return false;
if (Validation.get('IsEmpty').test(v) && v != '') return false;
return true;
}],
['validate-cc-number', 'Please enter a valid credit card number.', function(v, elm) {
// remove non-numerics
var ccTypeContainer = $(elm.id.substr(0,elm.id.indexOf('_cc_number')) + '_cc_type');
if (ccTypeContainer && typeof Validation.creditCartTypes.get(ccTypeContainer.value) != 'undefined'
&& Validation.creditCartTypes.get(ccTypeContainer.value)[2] == false) {
if (!Validation.get('IsEmpty').test(v) && Validation.get('validate-digits').test(v)) {
return true;
} else {
return false;
}
}
return validateCreditCard(v);
}],
['validate-cc-type', 'Credit card number does not match credit card type.', function(v, elm) {
// remove credit card number delimiters such as "-" and space
elm.value = removeDelimiters(elm.value);
v = removeDelimiters(v);
var ccTypeContainer = $(elm.id.substr(0,elm.id.indexOf('_cc_number')) + '_cc_type');
if (!ccTypeContainer) {
return true;
}
var ccType = ccTypeContainer.value;
if (typeof Validation.creditCartTypes.get(ccType) == 'undefined') {
return false;
}
// Other card type or switch or solo card
if (Validation.creditCartTypes.get(ccType)[0]==false) {
return true;
}
var validationFailure = false;
Validation.creditCartTypes.each(function (pair) {
if (pair.key == ccType) {
if (pair.value[0] && !v.match(pair.value[0])) {
validationFailure = true;
}
throw $break;
}
});
if (validationFailure) {
return false;
}
if (ccTypeContainer.hasClassName('validation-failed') && Validation.isOnChange) {
Validation.validate(ccTypeContainer);
}
return true;
}],
['validate-cc-type-select', 'Card type does not match credit card number.', function(v, elm) {
var ccNumberContainer = $(elm.id.substr(0,elm.id.indexOf('_cc_type')) + '_cc_number');
if (Validation.isOnChange && Validation.get('IsEmpty').test(ccNumberContainer.value)) {
return true;
}
if (Validation.get('validate-cc-type').test(ccNumberContainer.value, ccNumberContainer)) {
Validation.validate(ccNumberContainer);
}
return Validation.get('validate-cc-type').test(ccNumberContainer.value, ccNumberContainer);
}],
['validate-cc-exp', 'Incorrect credit card expiration date.', function(v, elm) {
var ccExpMonth = v;
var ccExpYear = $(elm.id.substr(0,elm.id.indexOf('_expiration')) + '_expiration_yr').value;
var currentTime = new Date();
var currentMonth = currentTime.getMonth() + 1;
var currentYear = currentTime.getFullYear();
if (ccExpMonth < currentMonth && ccExpYear == currentYear) {
return false;
}
return true;
}],
['validate-cc-cvn', 'Please enter a valid credit card verification number.', function(v, elm) {
var ccTypeContainer = $(elm.id.substr(0,elm.id.indexOf('_cc_cid')) + '_cc_type');
if (!ccTypeContainer) {
return true;
}
var ccType = ccTypeContainer.value;
if (typeof Validation.creditCartTypes.get(ccType) == 'undefined') {
return false;
}
var re = Validation.creditCartTypes.get(ccType)[1];
if (v.match(re)) {
return true;
}
return false;
}],
['validate-ajax', '', function(v, elm) { return true; }],
['validate-data', 'Please use only letters (a-z or A-Z), numbers (0-9) or underscore(_) in this field, first character should be a letter.', function (v) {
if(v != '' && v) {
return /^[A-Za-z]+[A-Za-z0-9_]+$/.test(v);
}
return true;
}],
['validate-css-length', 'Please input a valid CSS-length. For example 100px or 77pt or 20em or .5ex or 50%.', function (v) {
if (v != '' && v) {
return /^[0-9\.]+(px|pt|em|ex|%)?$/.test(v) && (!(/\..*\./.test(v))) && !(/\.$/.test(v));
}
return true;
}],
['validate-length', 'Text length does not satisfy specified text range.', function (v, elm) {
var reMax = new RegExp(/^maximum-length-[0-9]+$/);
var reMin = new RegExp(/^minimum-length-[0-9]+$/);
var result = true;
$w(elm.className).each(function(name, index) {
if (name.match(reMax) && result) {
var length = name.split('-')[2];
result = (v.length <= length);
}
if (name.match(reMin) && result && !Validation.get('IsEmpty').test(v)) {
var length = name.split('-')[2];
result = (v.length >= length);
}
});
return result;
}],
['validate-percents', 'Please enter a number lower than 100.', {max:100}],
['required-file', 'Please select a file', function(v, elm) {
var result = !Validation.get('IsEmpty').test(v);
if (result === false) {
ovId = elm.id + '_value';
if ($(ovId)) {
result = !Validation.get('IsEmpty').test($(ovId).value);
}
}
return result;
}],
['validate-cc-ukss', 'Please enter issue number or start date for switch/solo card type.', function(v,elm) {
var endposition;
if (elm.id.match(/(.)+_cc_issue$/)) {
endposition = elm.id.indexOf('_cc_issue');
} else if (elm.id.match(/(.)+_start_month$/)) {
endposition = elm.id.indexOf('_start_month');
} else {
endposition = elm.id.indexOf('_start_year');
}
var prefix = elm.id.substr(0,endposition);
var ccTypeContainer = $(prefix + '_cc_type');
if (!ccTypeContainer) {
return true;
}
var ccType = ccTypeContainer.value;
if(['SS','SM','SO'].indexOf(ccType) == -1){
return true;
}
$(prefix + '_cc_issue').advaiceContainer
= $(prefix + '_start_month').advaiceContainer
= $(prefix + '_start_year').advaiceContainer
= $(prefix + '_cc_type_ss_div').down('ul li.adv-container');
var ccIssue = $(prefix + '_cc_issue').value;
var ccSMonth = $(prefix + '_start_month').value;
var ccSYear = $(prefix + '_start_year').value;
var ccStartDatePresent = (ccSMonth && ccSYear) ? true : false;
if (!ccStartDatePresent && !ccIssue){
return false;
}
return true;
}]
]);
function removeDelimiters (v) {
v = v.replace(/\s/g, '');
v = v.replace(/\-/g, '');
return v;
}
function parseNumber(v)
{
if (typeof v != 'string') {
return parseFloat(v);
}
var isDot = v.indexOf('.');
var isComa = v.indexOf(',');
if (isDot != -1 && isComa != -1) {
if (isComa > isDot) {
v = v.replace('.', '').replace(',', '.');
}
else {
v = v.replace(',', '');
}
}
else if (isComa != -1) {
v = v.replace(',', '.');
}
return parseFloat(v);
}
/**
* Hash with credit card types which can be simply extended in payment modules
* 0 - regexp for card number
* 1 - regexp for cvn
* 2 - check or not credit card number trough Luhn algorithm by
* function validateCreditCard which you can find above in this file
*/
Validation.creditCartTypes = $H({
'SS': [new RegExp('^((6759[0-9]{12})|(5018|5020|5038|6304|6759|6761|6763[0-9]{12,19})|(49[013][1356][0-9]{12})|(6333[0-9]{12})|(6334[0-4]\d{11})|(633110[0-9]{10})|(564182[0-9]{10}))([0-9]{2,3})?$'), new RegExp('^([0-9]{3}|[0-9]{4})?$'), true],
'SO': [new RegExp('^(6334[5-9]([0-9]{11}|[0-9]{13,14}))|(6767([0-9]{12}|[0-9]{14,15}))$'), new RegExp('^([0-9]{3}|[0-9]{4})?$'), true],
'VI': [new RegExp('^4[0-9]{12}([0-9]{3})?$'), new RegExp('^[0-9]{3}$'), true],
'MC': [new RegExp('^5[1-5][0-9]{14}$'), new RegExp('^[0-9]{3}$'), true],
'AE': [new RegExp('^3[47][0-9]{13}$'), new RegExp('^[0-9]{4}$'), true],
'DI': [new RegExp('^(30[0-5][0-9]{13}|3095[0-9]{12}|35(2[8-9][0-9]{12}|[3-8][0-9]{13})|36[0-9]{12}|3[8-9][0-9]{14}|6011(0[0-9]{11}|[2-4][0-9]{11}|74[0-9]{10}|7[7-9][0-9]{10}|8[6-9][0-9]{10}|9[0-9]{11})|62(2(12[6-9][0-9]{10}|1[3-9][0-9]{11}|[2-8][0-9]{12}|9[0-1][0-9]{11}|92[0-5][0-9]{10})|[4-6][0-9]{13}|8[2-8][0-9]{12})|6(4[4-9][0-9]{13}|5[0-9]{14}))$'), new RegExp('^[0-9]{3}$'), true],
'JCB': [new RegExp('^(30[0-5][0-9]{13}|3095[0-9]{12}|35(2[8-9][0-9]{12}|[3-8][0-9]{13})|36[0-9]{12}|3[8-9][0-9]{14}|6011(0[0-9]{11}|[2-4][0-9]{11}|74[0-9]{10}|7[7-9][0-9]{10}|8[6-9][0-9]{10}|9[0-9]{11})|62(2(12[6-9][0-9]{10}|1[3-9][0-9]{11}|[2-8][0-9]{12}|9[0-1][0-9]{11}|92[0-5][0-9]{10})|[4-6][0-9]{13}|8[2-8][0-9]{12})|6(4[4-9][0-9]{13}|5[0-9]{14}))$'), new RegExp('^[0-9]{3,4}$'), true],
'DICL': [new RegExp('^(30[0-5][0-9]{13}|3095[0-9]{12}|35(2[8-9][0-9]{12}|[3-8][0-9]{13})|36[0-9]{12}|3[8-9][0-9]{14}|6011(0[0-9]{11}|[2-4][0-9]{11}|74[0-9]{10}|7[7-9][0-9]{10}|8[6-9][0-9]{10}|9[0-9]{11})|62(2(12[6-9][0-9]{10}|1[3-9][0-9]{11}|[2-8][0-9]{12}|9[0-1][0-9]{11}|92[0-5][0-9]{10})|[4-6][0-9]{13}|8[2-8][0-9]{12})|6(4[4-9][0-9]{13}|5[0-9]{14}))$'), new RegExp('^[0-9]{3}$'), true],
'SM': [new RegExp('(^(5[0678])[0-9]{11,18}$)|(^(6[^05])[0-9]{11,18}$)|(^(601)[^1][0-9]{9,16}$)|(^(6011)[0-9]{9,11}$)|(^(6011)[0-9]{13,16}$)|(^(65)[0-9]{11,13}$)|(^(65)[0-9]{15,18}$)|(^(49030)[2-9]([0-9]{10}$|[0-9]{12,13}$))|(^(49033)[5-9]([0-9]{10}$|[0-9]{12,13}$))|(^(49110)[1-2]([0-9]{10}$|[0-9]{12,13}$))|(^(49117)[4-9]([0-9]{10}$|[0-9]{12,13}$))|(^(49118)[0-2]([0-9]{10}$|[0-9]{12,13}$))|(^(4936)([0-9]{12}$|[0-9]{14,15}$))'), new RegExp('^([0-9]{3}|[0-9]{4})?$'), true],
'OT': [false, new RegExp('^([0-9]{3}|[0-9]{4})?$'), false]
});
// script.aculo.us builder.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008
// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
var Builder = {
NODEMAP: {
AREA: 'map',
CAPTION: 'table',
COL: 'table',
COLGROUP: 'table',
LEGEND: 'fieldset',
OPTGROUP: 'select',
OPTION: 'select',
PARAM: 'object',
TBODY: 'table',
TD: 'table',
TFOOT: 'table',
TH: 'table',
THEAD: 'table',
TR: 'table'
},
// note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken,
// due to a Firefox bug
node: function(elementName) {
elementName = elementName.toUpperCase();
// try innerHTML approach
var parentTag = this.NODEMAP[elementName] || 'div';
var parentElement = document.createElement(parentTag);
try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
parentElement.innerHTML = "<" + elementName + "></" + elementName + ">";
} catch(e) {}
var element = parentElement.firstChild || null;
// see if browser added wrapping tags
if(element && (element.tagName.toUpperCase() != elementName))
element = element.getElementsByTagName(elementName)[0];
// fallback to createElement approach
if(!element) element = document.createElement(elementName);
// abort if nothing could be created
if(!element) return;
// attributes (or text)
if(arguments[1])
if(this._isStringOrNumber(arguments[1]) ||
(arguments[1] instanceof Array) ||
arguments[1].tagName) {
this._children(element, arguments[1]);
} else {
var attrs = this._attributes(arguments[1]);
if(attrs.length) {
try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
parentElement.innerHTML = "<" +elementName + " " +
attrs + "></" + elementName + ">";
} catch(e) {}
element = parentElement.firstChild || null;
// workaround firefox 1.0.X bug
if(!element) {
element = document.createElement(elementName);
for(attr in arguments[1])
element[attr == 'class' ? 'className' : attr] = arguments[1][attr];
}
if(element.tagName.toUpperCase() != elementName)
element = parentElement.getElementsByTagName(elementName)[0];
}
}
// text, or array of children
if(arguments[2])
this._children(element, arguments[2]);
return $(element);
},
_text: function(text) {
return document.createTextNode(text);
},
ATTR_MAP: {
'className': 'class',
'htmlFor': 'for'
},
_attributes: function(attributes) {
var attrs = [];
for(attribute in attributes)
attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) +
'="' + attributes[attribute].toString().escapeHTML().gsub(/"/,'"') + '"');
return attrs.join(" ");
},
_children: function(element, children) {
if(children.tagName) {
element.appendChild(children);
return;
}
if(typeof children=='object') { // array can hold nodes and text
children.flatten().each( function(e) {
if(typeof e=='object')
element.appendChild(e);
else
if(Builder._isStringOrNumber(e))
element.appendChild(Builder._text(e));
});
} else
if(Builder._isStringOrNumber(children))
element.appendChild(Builder._text(children));
},
_isStringOrNumber: function(param) {
return(typeof param=='string' || typeof param=='number');
},
build: function(html) {
var element = this.node('div');
$(element).update(html.strip());
return element.down();
},
dump: function(scope) {
if(typeof scope != 'object' && typeof scope != 'function') scope = window; //global scope
var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " +
"BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " +
"FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+
"KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+
"PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+
"TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/);
tags.each( function(tag){
scope[tag] = function() {
return Builder.node.apply(Builder, [tag].concat($A(arguments)));
};
});
}
};
// script.aculo.us effects.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008
// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// Contributors:
// Justin Palmer (http://encytemedia.com/)
// Mark Pilgrim (http://diveintomark.org/)
// Martin Bialasinki
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
// converts rgb() and #xxx to #xxxxxx format,
// returns self (or first argument) if not convertable
String.prototype.parseColor = function() {
var color = '#';
if (this.slice(0,4) == 'rgb(') {
var cols = this.slice(4,this.length-1).split(',');
var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);
} else {
if (this.slice(0,1) == '#') {
if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();
if (this.length==7) color = this.toLowerCase();
}
}
return (color.length==7 ? color : (arguments[0] || this));
};
/*--------------------------------------------------------------------------*/
Element.collectTextNodes = function(element) {
return $A($(element).childNodes).collect( function(node) {
return (node.nodeType==3 ? node.nodeValue :
(node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
}).flatten().join('');
};
Element.collectTextNodesIgnoreClass = function(element, className) {
return $A($(element).childNodes).collect( function(node) {
return (node.nodeType==3 ? node.nodeValue :
((node.hasChildNodes() && !Element.hasClassName(node,className)) ?
Element.collectTextNodesIgnoreClass(node, className) : ''));
}).flatten().join('');
};
Element.setContentZoom = function(element, percent) {
element = $(element);
element.setStyle({fontSize: (percent/100) + 'em'});
if (Prototype.Browser.WebKit) window.scrollBy(0,0);
return element;
};
Element.getInlineOpacity = function(element){
return $(element).style.opacity || '';
};
Element.forceRerendering = function(element) {
try {
element = $(element);
var n = document.createTextNode(' ');
element.appendChild(n);
element.removeChild(n);
} catch(e) { }
};
/*--------------------------------------------------------------------------*/
var Effect = {
_elementDoesNotExistError: {
name: 'ElementDoesNotExistError',
message: 'The specified DOM element does not exist, but is required for this effect to operate'
},
Transitions: {
linear: Prototype.K,
sinoidal: function(pos) {
return (-Math.cos(pos*Math.PI)/2) + .5;
},
reverse: function(pos) {
return 1-pos;
},
flicker: function(pos) {
var pos = ((-Math.cos(pos*Math.PI)/4) + .75) + Math.random()/4;
return pos > 1 ? 1 : pos;
},
wobble: function(pos) {
return (-Math.cos(pos*Math.PI*(9*pos))/2) + .5;
},
pulse: function(pos, pulses) {
return (-Math.cos((pos*((pulses||5)-.5)*2)*Math.PI)/2) + .5;
},
spring: function(pos) {
return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6));
},
none: function(pos) {
return 0;
},
full: function(pos) {
return 1;
}
},
DefaultOptions: {
duration: 1.0, // seconds
fps: 100, // 100= assume 66fps max.
sync: false, // true for combining
from: 0.0,
to: 1.0,
delay: 0.0,
queue: 'parallel'
},
tagifyText: function(element) {
var tagifyStyle = 'position:relative';
if (Prototype.Browser.IE) tagifyStyle += ';zoom:1';
element = $(element);
$A(element.childNodes).each( function(child) {
if (child.nodeType==3) {
child.nodeValue.toArray().each( function(character) {
element.insertBefore(
new Element('span', {style: tagifyStyle}).update(
character == ' ' ? String.fromCharCode(160) : character),
child);
});
Element.remove(child);
}
});
},
multiple: function(element, effect) {
var elements;
if (((typeof element == 'object') ||
Object.isFunction(element)) &&
(element.length))
elements = element;
else
elements = $(element).childNodes;
var options = Object.extend({
speed: 0.1,
delay: 0.0
}, arguments[2] || { });
var masterDelay = options.delay;
$A(elements).each( function(element, index) {
new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
});
},
PAIRS: {
'slide': ['SlideDown','SlideUp'],
'blind': ['BlindDown','BlindUp'],
'appear': ['Appear','Fade']
},
toggle: function(element, effect) {
element = $(element);
effect = (effect || 'appear').toLowerCase();
var options = Object.extend({
queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
}, arguments[2] || { });
Effect[element.visible() ?
Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
}
};
Effect.DefaultOptions.transition = Effect.Transitions.sinoidal;
/* ------------- core effects ------------- */
Effect.ScopedQueue = Class.create(Enumerable, {
initialize: function() {
this.effects = [];
this.interval = null;
},
_each: function(iterator) {
this.effects._each(iterator);
},
add: function(effect) {
var timestamp = new Date().getTime();
var position = Object.isString(effect.options.queue) ?
effect.options.queue : effect.options.queue.position;
switch(position) {
case 'front':
// move unstarted effects after this effect
this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
e.startOn += effect.finishOn;
e.finishOn += effect.finishOn;
});
break;
case 'with-last':
timestamp = this.effects.pluck('startOn').max() || timestamp;
break;
case 'end':
// start effect after last queued effect has finished
timestamp = this.effects.pluck('finishOn').max() || timestamp;
break;
}
effect.startOn += timestamp;
effect.finishOn += timestamp;
if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
this.effects.push(effect);
if (!this.interval)
this.interval = setInterval(this.loop.bind(this), 15);
},
remove: function(effect) {
this.effects = this.effects.reject(function(e) { return e==effect });
if (this.effects.length == 0) {
clearInterval(this.interval);
this.interval = null;
}
},
loop: function() {
var timePos = new Date().getTime();
for(var i=0, len=this.effects.length;i<len;i++)
this.effects[i] && this.effects[i].loop(timePos);
}
});
Effect.Queues = {
instances: $H(),
get: function(queueName) {
if (!Object.isString(queueName)) return queueName;
return this.instances.get(queueName) ||
this.instances.set(queueName, new Effect.ScopedQueue());
}
};
Effect.Queue = Effect.Queues.get('global');
Effect.Base = Class.create({
position: null,
start: function(options) {
function codeForEvent(options,eventName){
return (
(options[eventName+'Internal'] ? 'this.options.'+eventName+'Internal(this);' : '') +
(options[eventName] ? 'this.options.'+eventName+'(this);' : '')
);
}
if (options && options.transition === false) options.transition = Effect.Transitions.linear;
this.options = Object.extend(Object.extend({ },Effect.DefaultOptions), options || { });
this.currentFrame = 0;
this.state = 'idle';
this.startOn = this.options.delay*1000;
this.finishOn = this.startOn+(this.options.duration*1000);
this.fromToDelta = this.options.to-this.options.from;
this.totalTime = this.finishOn-this.startOn;
this.totalFrames = this.options.fps*this.options.duration;
this.render = (function() {
function dispatch(effect, eventName) {
if (effect.options[eventName + 'Internal'])
effect.options[eventName + 'Internal'](effect);
if (effect.options[eventName])
effect.options[eventName](effect);
}
return function(pos) {
if (this.state === "idle") {
this.state = "running";
dispatch(this, 'beforeSetup');
if (this.setup) this.setup();
dispatch(this, 'afterSetup');
}
if (this.state === "running") {
pos = (this.options.transition(pos) * this.fromToDelta) + this.options.from;
this.position = pos;
dispatch(this, 'beforeUpdate');
if (this.update) this.update(pos);
dispatch(this, 'afterUpdate');
}
};
})();
this.event('beforeStart');
if (!this.options.sync)
Effect.Queues.get(Object.isString(this.options.queue) ?
'global' : this.options.queue.scope).add(this);
},
loop: function(timePos) {
if (timePos >= this.startOn) {
if (timePos >= this.finishOn) {
this.render(1.0);
this.cancel();
this.event('beforeFinish');
if (this.finish) this.finish();
this.event('afterFinish');
return;
}
var pos = (timePos - this.startOn) / this.totalTime,
frame = (pos * this.totalFrames).round();
if (frame > this.currentFrame) {
this.render(pos);
this.currentFrame = frame;
}
}
},
cancel: function() {
if (!this.options.sync)
Effect.Queues.get(Object.isString(this.options.queue) ?
'global' : this.options.queue.scope).remove(this);
this.state = 'finished';
},
event: function(eventName) {
if (this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
if (this.options[eventName]) this.options[eventName](this);
},
inspect: function() {
var data = $H();
for(property in this)
if (!Object.isFunction(this[property])) data.set(property, this[property]);
return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';
}
});
Effect.Parallel = Class.create(Effect.Base, {
initialize: function(effects) {
this.effects = effects || [];
this.start(arguments[1]);
},
update: function(position) {
this.effects.invoke('render', position);
},
finish: function(position) {
this.effects.each( function(effect) {
effect.render(1.0);
effect.cancel();
effect.event('beforeFinish');
if (effect.finish) effect.finish(position);
effect.event('afterFinish');
});
}
});
Effect.Tween = Class.create(Effect.Base, {
initialize: function(object, from, to) {
object = Object.isString(object) ? $(object) : object;
var args = $A(arguments), method = args.last(),
options = args.length == 5 ? args[3] : null;
this.method = Object.isFunction(method) ? method.bind(object) :
Object.isFunction(object[method]) ? object[method].bind(object) :
function(value) { object[method] = value };
this.start(Object.extend({ from: from, to: to }, options || { }));
},
update: function(position) {
this.method(position);
}
});
Effect.Event = Class.create(Effect.Base, {
initialize: function() {
this.start(Object.extend({ duration: 0 }, arguments[0] || { }));
},
update: Prototype.emptyFunction
});
Effect.Opacity = Class.create(Effect.Base, {
initialize: function(element) {
this.element = $(element);
if (!this.element) throw(Effect._elementDoesNotExistError);
// make this work on IE on elements without 'layout'
if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
this.element.setStyle({zoom: 1});
var options = Object.extend({
from: this.element.getOpacity() || 0.0,
to: 1.0
}, arguments[1] || { });
this.start(options);
},
update: function(position) {
this.element.setOpacity(position);
}
});
Effect.Move = Class.create(Effect.Base, {
initialize: function(element) {
this.element = $(element);
if (!this.element) throw(Effect._elementDoesNotExistError);
var options = Object.extend({
x: 0,
y: 0,
mode: 'relative'
}, arguments[1] || { });
this.start(options);
},
setup: function() {
this.element.makePositioned();
this.originalLeft = parseFloat(this.element.getStyle('left') || '0');
this.originalTop = parseFloat(this.element.getStyle('top') || '0');
if (this.options.mode == 'absolute') {
this.options.x = this.options.x - this.originalLeft;
this.options.y = this.options.y - this.originalTop;
}
},
update: function(position) {
this.element.setStyle({
left: (this.options.x * position + this.originalLeft).round() + 'px',
top: (this.options.y * position + this.originalTop).round() + 'px'
});
}
});
// for backwards compatibility
Effect.MoveBy = function(element, toTop, toLeft) {
return new Effect.Move(element,
Object.extend({ x: toLeft, y: toTop }, arguments[3] || { }));
};
Effect.Scale = Class.create(Effect.Base, {
initialize: function(element, percent) {
this.element = $(element);
if (!this.element) throw(Effect._elementDoesNotExistError);
var options = Object.extend({
scaleX: true,
scaleY: true,
scaleContent: true,
scaleFromCenter: false,
scaleMode: 'box', // 'box' or 'contents' or { } with provided values
scaleFrom: 100.0,
scaleTo: percent
}, arguments[2] || { });
this.start(options);
},
setup: function() {
this.restoreAfterFinish = this.options.restoreAfterFinish || false;
this.elementPositioning = this.element.getStyle('position');
this.originalStyle = { };
['top','left','width','height','fontSize'].each( function(k) {
this.originalStyle[k] = this.element.style[k];
}.bind(this));
this.originalTop = this.element.offsetTop;
this.originalLeft = this.element.offsetLeft;
var fontSize = this.element.getStyle('font-size') || '100%';
['em','px','%','pt'].each( function(fontSizeType) {
if (fontSize.indexOf(fontSizeType)>0) {
this.fontSize = parseFloat(fontSize);
this.fontSizeType = fontSizeType;
}
}.bind(this));
this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
this.dims = null;
if (this.options.scaleMode=='box')
this.dims = [this.element.offsetHeight, this.element.offsetWidth];
if (/^content/.test(this.options.scaleMode))
this.dims = [this.element.scrollHeight, this.element.scrollWidth];
if (!this.dims)
this.dims = [this.options.scaleMode.originalHeight,
this.options.scaleMode.originalWidth];
},
update: function(position) {
var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
if (this.options.scaleContent && this.fontSize)
this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
},
finish: function(position) {
if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
},
setDimensions: function(height, width) {
var d = { };
if (this.options.scaleX) d.width = width.round() + 'px';
if (this.options.scaleY) d.height = height.round() + 'px';
if (this.options.scaleFromCenter) {
var topd = (height - this.dims[0])/2;
var leftd = (width - this.dims[1])/2;
if (this.elementPositioning == 'absolute') {
if (this.options.scaleY) d.top = this.originalTop-topd + 'px';
if (this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
} else {
if (this.options.scaleY) d.top = -topd + 'px';
if (this.options.scaleX) d.left = -leftd + 'px';
}
}
this.element.setStyle(d);
}
});
Effect.Highlight = Class.create(Effect.Base, {
initialize: function(element) {
this.element = $(element);
if (!this.element) throw(Effect._elementDoesNotExistError);
var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || { });
this.start(options);
},
setup: function() {
// Prevent executing on elements not in the layout flow
if (this.element.getStyle('display')=='none') { this.cancel(); return; }
// Disable background image during the effect
this.oldStyle = { };
if (!this.options.keepBackgroundImage) {
this.oldStyle.backgroundImage = this.element.getStyle('background-image');
this.element.setStyle({backgroundImage: 'none'});
}
if (!this.options.endcolor)
this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
if (!this.options.restorecolor)
this.options.restorecolor = this.element.getStyle('background-color');
// init color calculations
this._base = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
},
update: function(position) {
this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart()); }.bind(this)) });
},
finish: function() {
this.element.setStyle(Object.extend(this.oldStyle, {
backgroundColor: this.options.restorecolor
}));
}
});
Effect.ScrollTo = function(element) {
var options = arguments[1] || { },
scrollOffsets = document.viewport.getScrollOffsets(),
elementOffsets = $(element).cumulativeOffset();
if (options.offset) elementOffsets[1] += options.offset;
return new Effect.Tween(null,
scrollOffsets.top,
elementOffsets[1],
options,
function(p){ scrollTo(scrollOffsets.left, p.round()); }
);
};
/* ------------- combination effects ------------- */
Effect.Fade = function(element) {
element = $(element);
var oldOpacity = element.getInlineOpacity();
var options = Object.extend({
from: element.getOpacity() || 1.0,
to: 0.0,
afterFinishInternal: function(effect) {
if (effect.options.to!=0) return;
effect.element.hide().setStyle({opacity: oldOpacity});
}
}, arguments[1] || { });
return new Effect.Opacity(element,options);
};
Effect.Appear = function(element) {
element = $(element);
var options = Object.extend({
from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
to: 1.0,
// force Safari to render floated elements properly
afterFinishInternal: function(effect) {
effect.element.forceRerendering();
},
beforeSetup: function(effect) {
effect.element.setOpacity(effect.options.from).show();
}}, arguments[1] || { });
return new Effect.Opacity(element,options);
};
Effect.Puff = function(element) {
element = $(element);
var oldStyle = {
opacity: element.getInlineOpacity(),
position: element.getStyle('position'),
top: element.style.top,
left: element.style.left,
width: element.style.width,
height: element.style.height
};
return new Effect.Parallel(
[ new Effect.Scale(element, 200,
{ sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }),
new Effect.Opacity(element, { sync: true, to: 0.0 } ) ],
Object.extend({ duration: 1.0,
beforeSetupInternal: function(effect) {
Position.absolutize(effect.effects[0].element);
},
afterFinishInternal: function(effect) {
effect.effects[0].element.hide().setStyle(oldStyle); }
}, arguments[1] || { })
);
};
Effect.BlindUp = function(element) {
element = $(element);
element.makeClipping();
return new Effect.Scale(element, 0,
Object.extend({ scaleContent: false,
scaleX: false,
restoreAfterFinish: true,
afterFinishInternal: function(effect) {
effect.element.hide().undoClipping();
}
}, arguments[1] || { })
);
};
Effect.BlindDown = function(element) {
element = $(element);
var elementDimensions = element.getDimensions();
return new Effect.Scale(element, 100, Object.extend({
scaleContent: false,
scaleX: false,
scaleFrom: 0,
scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
restoreAfterFinish: true,
afterSetup: function(effect) {
effect.element.makeClipping().setStyle({height: '0px'}).show();
},
afterFinishInternal: function(effect) {
effect.element.undoClipping();
}
}, arguments[1] || { }));
};
Effect.SwitchOff = function(element) {
element = $(element);
var oldOpacity = element.getInlineOpacity();
return new Effect.Appear(element, Object.extend({
duration: 0.4,
from: 0,
transition: Effect.Transitions.flicker,
afterFinishInternal: function(effect) {
new Effect.Scale(effect.element, 1, {
duration: 0.3, scaleFromCenter: true,
scaleX: false, scaleContent: false, restoreAfterFinish: true,
beforeSetup: function(effect) {
effect.element.makePositioned().makeClipping();
},
afterFinishInternal: function(effect) {
effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
}
});
}
}, arguments[1] || { }));
};
Effect.DropOut = function(element) {
element = $(element);
var oldStyle = {
top: element.getStyle('top'),
left: element.getStyle('left'),
opacity: element.getInlineOpacity() };
return new Effect.Parallel(
[ new Effect.Move(element, {x: 0, y: 100, sync: true }),
new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
Object.extend(
{ duration: 0.5,
beforeSetup: function(effect) {
effect.effects[0].element.makePositioned();
},
afterFinishInternal: function(effect) {
effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
}
}, arguments[1] || { }));
};
Effect.Shake = function(element) {
element = $(element);
var options = Object.extend({
distance: 20,
duration: 0.5
}, arguments[1] || {});
var distance = parseFloat(options.distance);
var split = parseFloat(options.duration) / 10.0;
var oldStyle = {
top: element.getStyle('top'),
left: element.getStyle('left') };
return new Effect.Move(element,
{ x: distance, y: 0, duration: split, afterFinishInternal: function(effect) {
new Effect.Move(effect.element,
{ x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
new Effect.Move(effect.element,
{ x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
new Effect.Move(effect.element,
{ x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
new Effect.Move(effect.element,
{ x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
new Effect.Move(effect.element,
{ x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) {
effect.element.undoPositioned().setStyle(oldStyle);
}}); }}); }}); }}); }}); }});
};
Effect.SlideDown = function(element) {
element = $(element).cleanWhitespace();
// SlideDown need to have the content of the element wrapped in a container element with fixed height!
var oldInnerBottom = element.down().getStyle('bottom');
var elementDimensions = element.getDimensions();
return new Effect.Scale(element, 100, Object.extend({
scaleContent: false,
scaleX: false,
scaleFrom: window.opera ? 0 : 1,
scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
restoreAfterFinish: true,
afterSetup: function(effect) {
effect.element.makePositioned();
effect.element.down().makePositioned();
if (window.opera) effect.element.setStyle({top: ''});
effect.element.makeClipping().setStyle({height: '0px'}).show();
},
afterUpdateInternal: function(effect) {
effect.element.down().setStyle({bottom:
(effect.dims[0] - effect.element.clientHeight) + 'px' });
},
afterFinishInternal: function(effect) {
effect.element.undoClipping().undoPositioned();
effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
}, arguments[1] || { })
);
};
Effect.SlideUp = function(element) {
element = $(element).cleanWhitespace();
var oldInnerBottom = element.down().getStyle('bottom');
var elementDimensions = element.getDimensions();
return new Effect.Scale(element, window.opera ? 0 : 1,
Object.extend({ scaleContent: false,
scaleX: false,
scaleMode: 'box',
scaleFrom: 100,
scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
restoreAfterFinish: true,
afterSetup: function(effect) {
effect.element.makePositioned();
effect.element.down().makePositioned();
if (window.opera) effect.element.setStyle({top: ''});
effect.element.makeClipping().show();
},
afterUpdateInternal: function(effect) {
effect.element.down().setStyle({bottom:
(effect.dims[0] - effect.element.clientHeight) + 'px' });
},
afterFinishInternal: function(effect) {
effect.element.hide().undoClipping().undoPositioned();
effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom});
}
}, arguments[1] || { })
);
};
// Bug in opera makes the TD containing this element expand for a instance after finish
Effect.Squish = function(element) {
return new Effect.Scale(element, window.opera ? 1 : 0, {
restoreAfterFinish: true,
beforeSetup: function(effect) {
effect.element.makeClipping();
},
afterFinishInternal: function(effect) {
effect.element.hide().undoClipping();
}
});
};
Effect.Grow = function(element) {
element = $(element);
var options = Object.extend({
direction: 'center',
moveTransition: Effect.Transitions.sinoidal,
scaleTransition: Effect.Transitions.sinoidal,
opacityTransition: Effect.Transitions.full
}, arguments[1] || { });
var oldStyle = {
top: element.style.top,
left: element.style.left,
height: element.style.height,
width: element.style.width,
opacity: element.getInlineOpacity() };
var dims = element.getDimensions();
var initialMoveX, initialMoveY;
var moveX, moveY;
switch (options.direction) {
case 'top-left':
initialMoveX = initialMoveY = moveX = moveY = 0;
break;
case 'top-right':
initialMoveX = dims.width;
initialMoveY = moveY = 0;
moveX = -dims.width;
break;
case 'bottom-left':
initialMoveX = moveX = 0;
initialMoveY = dims.height;
moveY = -dims.height;
break;
case 'bottom-right':
initialMoveX = dims.width;
initialMoveY = dims.height;
moveX = -dims.width;
moveY = -dims.height;
break;
case 'center':
initialMoveX = dims.width / 2;
initialMoveY = dims.height / 2;
moveX = -dims.width / 2;
moveY = -dims.height / 2;
break;
}
return new Effect.Move(element, {
x: initialMoveX,
y: initialMoveY,
duration: 0.01,
beforeSetup: function(effect) {
effect.element.hide().makeClipping().makePositioned();
},
afterFinishInternal: function(effect) {
new Effect.Parallel(
[ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
new Effect.Scale(effect.element, 100, {
scaleMode: { originalHeight: dims.height, originalWidth: dims.width },
sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
], Object.extend({
beforeSetup: function(effect) {
effect.effects[0].element.setStyle({height: '0px'}).show();
},
afterFinishInternal: function(effect) {
effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);
}
}, options)
);
}
});
};
Effect.Shrink = function(element) {
element = $(element);
var options = Object.extend({
direction: 'center',
moveTransition: Effect.Transitions.sinoidal,
scaleTransition: Effect.Transitions.sinoidal,
opacityTransition: Effect.Transitions.none
}, arguments[1] || { });
var oldStyle = {
top: element.style.top,
left: element.style.left,
height: element.style.height,
width: element.style.width,
opacity: element.getInlineOpacity() };
var dims = element.getDimensions();
var moveX, moveY;
switch (options.direction) {
case 'top-left':
moveX = moveY = 0;
break;
case 'top-right':
moveX = dims.width;
moveY = 0;
break;
case 'bottom-left':
moveX = 0;
moveY = dims.height;
break;
case 'bottom-right':
moveX = dims.width;
moveY = dims.height;
break;
case 'center':
moveX = dims.width / 2;
moveY = dims.height / 2;
break;
}
return new Effect.Parallel(
[ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
], Object.extend({
beforeStartInternal: function(effect) {
effect.effects[0].element.makePositioned().makeClipping();
},
afterFinishInternal: function(effect) {
effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
}, options)
);
};
Effect.Pulsate = function(element) {
element = $(element);
var options = arguments[1] || { },
oldOpacity = element.getInlineOpacity(),
transition = options.transition || Effect.Transitions.linear,
reverser = function(pos){
return 1 - transition((-Math.cos((pos*(options.pulses||5)*2)*Math.PI)/2) + .5);
};
return new Effect.Opacity(element,
Object.extend(Object.extend({ duration: 2.0, from: 0,
afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
}, options), {transition: reverser}));
};
Effect.Fold = function(element) {
element = $(element);
var oldStyle = {
top: element.style.top,
left: element.style.left,
width: element.style.width,
height: element.style.height };
element.makeClipping();
return new Effect.Scale(element, 5, Object.extend({
scaleContent: false,
scaleX: false,
afterFinishInternal: function(effect) {
new Effect.Scale(element, 1, {
scaleContent: false,
scaleY: false,
afterFinishInternal: function(effect) {
effect.element.hide().undoClipping().setStyle(oldStyle);
} });
}}, arguments[1] || { }));
};
Effect.Morph = Class.create(Effect.Base, {
initialize: function(element) {
this.element = $(element);
if (!this.element) throw(Effect._elementDoesNotExistError);
var options = Object.extend({
style: { }
}, arguments[1] || { });
if (!Object.isString(options.style)) this.style = $H(options.style);
else {
if (options.style.include(':'))
this.style = options.style.parseStyle();
else {
this.element.addClassName(options.style);
this.style = $H(this.element.getStyles());
this.element.removeClassName(options.style);
var css = this.element.getStyles();
this.style = this.style.reject(function(style) {
return style.value == css[style.key];
});
options.afterFinishInternal = function(effect) {
effect.element.addClassName(effect.options.style);
effect.transforms.each(function(transform) {
effect.element.style[transform.style] = '';
});
};
}
}
this.start(options);
},
setup: function(){
function parseColor(color){
if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
color = color.parseColor();
return $R(0,2).map(function(i){
return parseInt( color.slice(i*2+1,i*2+3), 16 );
});
}
this.transforms = this.style.map(function(pair){
var property = pair[0], value = pair[1], unit = null;
if (value.parseColor('#zzzzzz') != '#zzzzzz') {
value = value.parseColor();
unit = 'color';
} else if (property == 'opacity') {
value = parseFloat(value);
if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
this.element.setStyle({zoom: 1});
} else if (Element.CSS_LENGTH.test(value)) {
var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/);
value = parseFloat(components[1]);
unit = (components.length == 3) ? components[2] : null;
}
var originalValue = this.element.getStyle(property);
return {
style: property.camelize(),
originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0),
targetValue: unit=='color' ? parseColor(value) : value,
unit: unit
};
}.bind(this)).reject(function(transform){
return (
(transform.originalValue == transform.targetValue) ||
(
transform.unit != 'color' &&
(isNaN(transform.originalValue) || isNaN(transform.targetValue))
)
);
});
},
update: function(position) {
var style = { }, transform, i = this.transforms.length;
while(i--)
style[(transform = this.transforms[i]).style] =
transform.unit=='color' ? '#'+
(Math.round(transform.originalValue[0]+
(transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() +
(Math.round(transform.originalValue[1]+
(transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() +
(Math.round(transform.originalValue[2]+
(transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() :
(transform.originalValue +
(transform.targetValue - transform.originalValue) * position).toFixed(3) +
(transform.unit === null ? '' : transform.unit);
this.element.setStyle(style, true);
}
});
Effect.Transform = Class.create({
initialize: function(tracks){
this.tracks = [];
this.options = arguments[1] || { };
this.addTracks(tracks);
},
addTracks: function(tracks){
tracks.each(function(track){
track = $H(track);
var data = track.values().first();
this.tracks.push($H({
ids: track.keys().first(),
effect: Effect.Morph,
options: { style: data }
}));
}.bind(this));
return this;
},
play: function(){
return new Effect.Parallel(
this.tracks.map(function(track){
var ids = track.get('ids'), effect = track.get('effect'), options = track.get('options');
var elements = [$(ids) || $$(ids)].flatten();
return elements.map(function(e){ return new effect(e, Object.extend({ sync:true }, options)) });
}).flatten(),
this.options
);
}
});
Element.CSS_PROPERTIES = $w(
'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' +
'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
'fontSize fontWeight height left letterSpacing lineHeight ' +
'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
'right textIndent top width wordSpacing zIndex');
Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;
String.__parseStyleElement = document.createElement('div');
String.prototype.parseStyle = function(){
var style, styleRules = $H();
if (Prototype.Browser.WebKit)
style = new Element('div',{style:this}).style;
else {
String.__parseStyleElement.innerHTML = '<div style="' + this + '"></div>';
style = String.__parseStyleElement.childNodes[0].style;
}
Element.CSS_PROPERTIES.each(function(property){
if (style[property]) styleRules.set(property, style[property]);
});
if (Prototype.Browser.IE && this.include('opacity'))
styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);
return styleRules;
};
if (document.defaultView && document.defaultView.getComputedStyle) {
Element.getStyles = function(element) {
var css = document.defaultView.getComputedStyle($(element), null);
return Element.CSS_PROPERTIES.inject({ }, function(styles, property) {
styles[property] = css[property];
return styles;
});
};
} else {
Element.getStyles = function(element) {
element = $(element);
var css = element.currentStyle, styles;
styles = Element.CSS_PROPERTIES.inject({ }, function(results, property) {
results[property] = css[property];
return results;
});
if (!styles.opacity) styles.opacity = element.getOpacity();
return styles;
};
}
Effect.Methods = {
morph: function(element, style) {
element = $(element);
new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || { }));
return element;
},
visualEffect: function(element, effect, options) {
element = $(element);
var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1);
new Effect[klass](element, options);
return element;
},
highlight: function(element, options) {
element = $(element);
new Effect.Highlight(element, options);
return element;
}
};
$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+
'pulsate shake puff squish switchOff dropOut').each(
function(effect) {
Effect.Methods[effect] = function(element, options){
element = $(element);
Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options);
return element;
};
}
);
$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each(
function(f) { Effect.Methods[f] = Element[f]; }
);
Element.addMethods(Effect.Methods);
// script.aculo.us dragdrop.js v1.9.0, Thu Dec 23 16:54:48 -0500 2010
// Copyright (c) 2005-2010 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
if(Object.isUndefined(Effect))
throw("dragdrop.js requires including script.aculo.us' effects.js library");
var Droppables = {
drops: [],
remove: function(element) {
this.drops = this.drops.reject(function(d) { return d.element==$(element) });
},
add: function(element) {
element = $(element);
var options = Object.extend({
greedy: true,
hoverclass: null,
tree: false
}, arguments[1] || { });
// cache containers
if(options.containment) {
options._containers = [];
var containment = options.containment;
if(Object.isArray(containment)) {
containment.each( function(c) { options._containers.push($(c)) });
} else {
options._containers.push($(containment));
}
}
if(options.accept) options.accept = [options.accept].flatten();
Element.makePositioned(element); // fix IE
options.element = element;
this.drops.push(options);
},
findDeepestChild: function(drops) {
deepest = drops[0];
for (i = 1; i < drops.length; ++i)
if (Element.isParent(drops[i].element, deepest.element))
deepest = drops[i];
return deepest;
},
isContained: function(element, drop) {
var containmentNode;
if(drop.tree) {
containmentNode = element.treeNode;
} else {
containmentNode = element.parentNode;
}
return drop._containers.detect(function(c) { return containmentNode == c });
},
isAffected: function(point, element, drop) {
return (
(drop.element!=element) &&
((!drop._containers) ||
this.isContained(element, drop)) &&
((!drop.accept) ||
(Element.classNames(element).detect(
function(v) { return drop.accept.include(v) } ) )) &&
Position.within(drop.element, point[0], point[1]) );
},
deactivate: function(drop) {
if(drop.hoverclass)
Element.removeClassName(drop.element, drop.hoverclass);
this.last_active = null;
},
activate: function(drop) {
if(drop.hoverclass)
Element.addClassName(drop.element, drop.hoverclass);
this.last_active = drop;
},
show: function(point, element) {
if(!this.drops.length) return;
var drop, affected = [];
this.drops.each( function(drop) {
if(Droppables.isAffected(point, element, drop))
affected.push(drop);
});
if(affected.length>0)
drop = Droppables.findDeepestChild(affected);
if(this.last_active && this.last_active != drop) this.deactivate(this.last_active);
if (drop) {
Position.within(drop.element, point[0], point[1]);
if(drop.onHover)
drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
if (drop != this.last_active) Droppables.activate(drop);
}
},
fire: function(event, element) {
if(!this.last_active) return;
Position.prepare();
if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
if (this.last_active.onDrop) {
this.last_active.onDrop(element, this.last_active.element, event);
return true;
}
},
reset: function() {
if(this.last_active)
this.deactivate(this.last_active);
}
};
var Draggables = {
drags: [],
observers: [],
register: function(draggable) {
if(this.drags.length == 0) {
this.eventMouseUp = this.endDrag.bindAsEventListener(this);
this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
this.eventKeypress = this.keyPress.bindAsEventListener(this);
Event.observe(document, "mouseup", this.eventMouseUp);
Event.observe(document, "mousemove", this.eventMouseMove);
Event.observe(document, "keypress", this.eventKeypress);
}
this.drags.push(draggable);
},
unregister: function(draggable) {
this.drags = this.drags.reject(function(d) { return d==draggable });
if(this.drags.length == 0) {
Event.stopObserving(document, "mouseup", this.eventMouseUp);
Event.stopObserving(document, "mousemove", this.eventMouseMove);
Event.stopObserving(document, "keypress", this.eventKeypress);
}
},
activate: function(draggable) {
if(draggable.options.delay) {
this._timeout = setTimeout(function() {
Draggables._timeout = null;
window.focus();
Draggables.activeDraggable = draggable;
}.bind(this), draggable.options.delay);
} else {
window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
this.activeDraggable = draggable;
}
},
deactivate: function() {
this.activeDraggable = null;
},
updateDrag: function(event) {
if(!this.activeDraggable) return;
var pointer = [Event.pointerX(event), Event.pointerY(event)];
// Mozilla-based browsers fire successive mousemove events with
// the same coordinates, prevent needless redrawing (moz bug?)
if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
this._lastPointer = pointer;
this.activeDraggable.updateDrag(event, pointer);
},
endDrag: function(event) {
if(this._timeout) {
clearTimeout(this._timeout);
this._timeout = null;
}
if(!this.activeDraggable) return;
this._lastPointer = null;
this.activeDraggable.endDrag(event);
this.activeDraggable = null;
},
keyPress: function(event) {
if(this.activeDraggable)
this.activeDraggable.keyPress(event);
},
addObserver: function(observer) {
this.observers.push(observer);
this._cacheObserverCallbacks();
},
removeObserver: function(element) { // element instead of observer fixes mem leaks
this.observers = this.observers.reject( function(o) { return o.element==element });
this._cacheObserverCallbacks();
},
notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag'
if(this[eventName+'Count'] > 0)
this.observers.each( function(o) {
if(o[eventName]) o[eventName](eventName, draggable, event);
});
if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
},
_cacheObserverCallbacks: function() {
['onStart','onEnd','onDrag'].each( function(eventName) {
Draggables[eventName+'Count'] = Draggables.observers.select(
function(o) { return o[eventName]; }
).length;
});
}
};
/*--------------------------------------------------------------------------*/
var Draggable = Class.create({
initialize: function(element) {
var defaults = {
handle: false,
reverteffect: function(element, top_offset, left_offset) {
var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur,
queue: {scope:'_draggable', position:'end'}
});
},
endeffect: function(element) {
var toOpacity = Object.isNumber(element._opacity) ? element._opacity : 1.0;
new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
queue: {scope:'_draggable', position:'end'},
afterFinish: function(){
Draggable._dragging[element] = false
}
});
},
zindex: 1000,
revert: false,
quiet: false,
scroll: false,
scrollSensitivity: 20,
scrollSpeed: 15,
snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] }
delay: 0
};
if(!arguments[1] || Object.isUndefined(arguments[1].endeffect))
Object.extend(defaults, {
starteffect: function(element) {
element._opacity = Element.getOpacity(element);
Draggable._dragging[element] = true;
new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
}
});
var options = Object.extend(defaults, arguments[1] || { });
this.element = $(element);
if(options.handle && Object.isString(options.handle))
this.handle = this.element.down('.'+options.handle, 0);
if(!this.handle) this.handle = $(options.handle);
if(!this.handle) this.handle = this.element;
if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) {
options.scroll = $(options.scroll);
this._isScrollChild = Element.childOf(this.element, options.scroll);
}
Element.makePositioned(this.element); // fix IE
this.options = options;
this.dragging = false;
this.eventMouseDown = this.initDrag.bindAsEventListener(this);
Event.observe(this.handle, "mousedown", this.eventMouseDown);
Draggables.register(this);
},
destroy: function() {
Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
Draggables.unregister(this);
},
currentDelta: function() {
return([
parseInt(Element.getStyle(this.element,'left') || '0'),
parseInt(Element.getStyle(this.element,'top') || '0')]);
},
initDrag: function(event) {
if(!Object.isUndefined(Draggable._dragging[this.element]) &&
Draggable._dragging[this.element]) return;
if(Event.isLeftClick(event)) {
// abort on form elements, fixes a Firefox issue
var src = Event.element(event);
if((tag_name = src.tagName.toUpperCase()) && (
tag_name=='INPUT' ||
tag_name=='SELECT' ||
tag_name=='OPTION' ||
tag_name=='BUTTON' ||
tag_name=='TEXTAREA')) return;
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var pos = this.element.cumulativeOffset();
this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
Draggables.activate(this);
Event.stop(event);
}
},
startDrag: function(event) {
this.dragging = true;
if(!this.delta)
this.delta = this.currentDelta();
if(this.options.zindex) {
this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
this.element.style.zIndex = this.options.zindex;
}
if(this.options.ghosting) {
this._clone = this.element.cloneNode(true);
this._originallyAbsolute = (this.element.getStyle('position') == 'absolute');
if (!this._originallyAbsolute)
Position.absolutize(this.element);
this.element.parentNode.insertBefore(this._clone, this.element);
}
if(this.options.scroll) {
if (this.options.scroll == window) {
var where = this._getWindowScroll(this.options.scroll);
this.originalScrollLeft = where.left;
this.originalScrollTop = where.top;
} else {
this.originalScrollLeft = this.options.scroll.scrollLeft;
this.originalScrollTop = this.options.scroll.scrollTop;
}
}
Draggables.notify('onStart', this, event);
if(this.options.starteffect) this.options.starteffect(this.element);
},
updateDrag: function(event, pointer) {
if(!this.dragging) this.startDrag(event);
if(!this.options.quiet){
Position.prepare();
Droppables.show(pointer, this.element);
}
Draggables.notify('onDrag', this, event);
this.draw(pointer);
if(this.options.change) this.options.change(this);
if(this.options.scroll) {
this.stopScrolling();
var p;
if (this.options.scroll == window) {
with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
} else {
p = Position.page(this.options.scroll).toArray();
p[0] += this.options.scroll.scrollLeft + Position.deltaX;
p[1] += this.options.scroll.scrollTop + Position.deltaY;
p.push(p[0]+this.options.scroll.offsetWidth);
p.push(p[1]+this.options.scroll.offsetHeight);
}
var speed = [0,0];
if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity);
if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity);
if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity);
if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
this.startScrolling(speed);
}
// fix AppleWebKit rendering
if(Prototype.Browser.WebKit) window.scrollBy(0,0);
Event.stop(event);
},
finishDrag: function(event, success) {
this.dragging = false;
if(this.options.quiet){
Position.prepare();
var pointer = [Event.pointerX(event), Event.pointerY(event)];
Droppables.show(pointer, this.element);
}
if(this.options.ghosting) {
if (!this._originallyAbsolute)
Position.relativize(this.element);
delete this._originallyAbsolute;
Element.remove(this._clone);
this._clone = null;
}
var dropped = false;
if(success) {
dropped = Droppables.fire(event, this.element);
if (!dropped) dropped = false;
}
if(dropped && this.options.onDropped) this.options.onDropped(this.element);
Draggables.notify('onEnd', this, event);
var revert = this.options.revert;
if(revert && Object.isFunction(revert)) revert = revert(this.element);
var d = this.currentDelta();
if(revert && this.options.reverteffect) {
if (dropped == 0 || revert != 'failure')
this.options.reverteffect(this.element,
d[1]-this.delta[1], d[0]-this.delta[0]);
} else {
this.delta = d;
}
if(this.options.zindex)
this.element.style.zIndex = this.originalZ;
if(this.options.endeffect)
this.options.endeffect(this.element);
Draggables.deactivate(this);
Droppables.reset();
},
keyPress: function(event) {
if(event.keyCode!=Event.KEY_ESC) return;
this.finishDrag(event, false);
Event.stop(event);
},
endDrag: function(event) {
if(!this.dragging) return;
this.stopScrolling();
this.finishDrag(event, true);
Event.stop(event);
},
draw: function(point) {
var pos = this.element.cumulativeOffset();
if(this.options.ghosting) {
var r = Position.realOffset(this.element);
pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
}
var d = this.currentDelta();
pos[0] -= d[0]; pos[1] -= d[1];
if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
}
var p = [0,1].map(function(i){
return (point[i]-pos[i]-this.offset[i])
}.bind(this));
if(this.options.snap) {
if(Object.isFunction(this.options.snap)) {
p = this.options.snap(p[0],p[1],this);
} else {
if(Object.isArray(this.options.snap)) {
p = p.map( function(v, i) {
return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this));
} else {
p = p.map( function(v) {
return (v/this.options.snap).round()*this.options.snap }.bind(this));
}
}}
var style = this.element.style;
if((!this.options.constraint) || (this.options.constraint=='horizontal'))
style.left = p[0] + "px";
if((!this.options.constraint) || (this.options.constraint=='vertical'))
style.top = p[1] + "px";
if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
},
stopScrolling: function() {
if(this.scrollInterval) {
clearInterval(this.scrollInterval);
this.scrollInterval = null;
Draggables._lastScrollPointer = null;
}
},
startScrolling: function(speed) {
if(!(speed[0] || speed[1])) return;
this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
this.lastScrolled = new Date();
this.scrollInterval = setInterval(this.scroll.bind(this), 10);
},
scroll: function() {
var current = new Date();
var delta = current - this.lastScrolled;
this.lastScrolled = current;
if(this.options.scroll == window) {
with (this._getWindowScroll(this.options.scroll)) {
if (this.scrollSpeed[0] || this.scrollSpeed[1]) {
var d = delta / 1000;
this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] );
}
}
} else {
this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000;
}
Position.prepare();
Droppables.show(Draggables._lastPointer, this.element);
Draggables.notify('onDrag', this);
if (this._isScrollChild) {
Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
if (Draggables._lastScrollPointer[0] < 0)
Draggables._lastScrollPointer[0] = 0;
if (Draggables._lastScrollPointer[1] < 0)
Draggables._lastScrollPointer[1] = 0;
this.draw(Draggables._lastScrollPointer);
}
if(this.options.change) this.options.change(this);
},
_getWindowScroll: function(w) {
var T, L, W, H;
with (w.document) {
if (w.document.documentElement && documentElement.scrollTop) {
T = documentElement.scrollTop;
L = documentElement.scrollLeft;
} else if (w.document.body) {
T = body.scrollTop;
L = body.scrollLeft;
}
if (w.innerWidth) {
W = w.innerWidth;
H = w.innerHeight;
} else if (w.document.documentElement && documentElement.clientWidth) {
W = documentElement.clientWidth;
H = documentElement.clientHeight;
} else {
W = body.offsetWidth;
H = body.offsetHeight;
}
}
return { top: T, left: L, width: W, height: H };
}
});
Draggable._dragging = { };
/*--------------------------------------------------------------------------*/
var SortableObserver = Class.create({
initialize: function(element, observer) {
this.element = $(element);
this.observer = observer;
this.lastValue = Sortable.serialize(this.element);
},
onStart: function() {
this.lastValue = Sortable.serialize(this.element);
},
onEnd: function() {
Sortable.unmark();
if(this.lastValue != Sortable.serialize(this.element))
this.observer(this.element)
}
});
var Sortable = {
SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
sortables: { },
_findRootElement: function(element) {
while (element.tagName.toUpperCase() != "BODY") {
if(element.id && Sortable.sortables[element.id]) return element;
element = element.parentNode;
}
},
options: function(element) {
element = Sortable._findRootElement($(element));
if(!element) return;
return Sortable.sortables[element.id];
},
destroy: function(element){
element = $(element);
var s = Sortable.sortables[element.id];
if(s) {
Draggables.removeObserver(s.element);
s.droppables.each(function(d){ Droppables.remove(d) });
s.draggables.invoke('destroy');
delete Sortable.sortables[s.element.id];
}
},
create: function(element) {
element = $(element);
var options = Object.extend({
element: element,
tag: 'li', // assumes li children, override with tag: 'tagname'
dropOnEmpty: false,
tree: false,
treeTag: 'ul',
overlap: 'vertical', // one of 'vertical', 'horizontal'
constraint: 'vertical', // one of 'vertical', 'horizontal', false
containment: element, // also takes array of elements (or id's); or false
handle: false, // or a CSS class
only: false,
delay: 0,
hoverclass: null,
ghosting: false,
quiet: false,
scroll: false,
scrollSensitivity: 20,
scrollSpeed: 15,
format: this.SERIALIZE_RULE,
// these take arrays of elements or ids and can be
// used for better initialization performance
elements: false,
handles: false,
onChange: Prototype.emptyFunction,
onUpdate: Prototype.emptyFunction
}, arguments[1] || { });
// clear any old sortable with same element
this.destroy(element);
// build options for the draggables
var options_for_draggable = {
revert: true,
quiet: options.quiet,
scroll: options.scroll,
scrollSpeed: options.scrollSpeed,
scrollSensitivity: options.scrollSensitivity,
delay: options.delay,
ghosting: options.ghosting,
constraint: options.constraint,
handle: options.handle };
if(options.starteffect)
options_for_draggable.starteffect = options.starteffect;
if(options.reverteffect)
options_for_draggable.reverteffect = options.reverteffect;
else
if(options.ghosting) options_for_draggable.reverteffect = function(element) {
element.style.top = 0;
element.style.left = 0;
};
if(options.endeffect)
options_for_draggable.endeffect = options.endeffect;
if(options.zindex)
options_for_draggable.zindex = options.zindex;
// build options for the droppables
var options_for_droppable = {
overlap: options.overlap,
containment: options.containment,
tree: options.tree,
hoverclass: options.hoverclass,
onHover: Sortable.onHover
};
var options_for_tree = {
onHover: Sortable.onEmptyHover,
overlap: options.overlap,
containment: options.containment,
hoverclass: options.hoverclass
};
// fix for gecko engine
Element.cleanWhitespace(element);
options.draggables = [];
options.droppables = [];
// drop on empty handling
if(options.dropOnEmpty || options.tree) {
Droppables.add(element, options_for_tree);
options.droppables.push(element);
}
(options.elements || this.findElements(element, options) || []).each( function(e,i) {
var handle = options.handles ? $(options.handles[i]) :
(options.handle ? $(e).select('.' + options.handle)[0] : e);
options.draggables.push(
new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
Droppables.add(e, options_for_droppable);
if(options.tree) e.treeNode = element;
options.droppables.push(e);
});
if(options.tree) {
(Sortable.findTreeElements(element, options) || []).each( function(e) {
Droppables.add(e, options_for_tree);
e.treeNode = element;
options.droppables.push(e);
});
}
// keep reference
this.sortables[element.identify()] = options;
// for onupdate
Draggables.addObserver(new SortableObserver(element, options.onUpdate));
},
// return all suitable-for-sortable elements in a guaranteed order
findElements: function(element, options) {
return Element.findChildren(
element, options.only, options.tree ? true : false, options.tag);
},
findTreeElements: function(element, options) {
return Element.findChildren(
element, options.only, options.tree ? true : false, options.treeTag);
},
onHover: function(element, dropon, overlap) {
if(Element.isParent(dropon, element)) return;
if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) {
return;
} else if(overlap>0.5) {
Sortable.mark(dropon, 'before');
if(dropon.previousSibling != element) {
var oldParentNode = element.parentNode;
element.style.visibility = "hidden"; // fix gecko rendering
dropon.parentNode.insertBefore(element, dropon);
if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);
Sortable.options(dropon.parentNode).onChange(element);
}
} else {
Sortable.mark(dropon, 'after');
var nextElement = dropon.nextSibling || null;
if(nextElement != element) {
var oldParentNode = element.parentNode;
element.style.visibility = "hidden"; // fix gecko rendering
dropon.parentNode.insertBefore(element, nextElement);
if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);
Sortable.options(dropon.parentNode).onChange(element);
}
}
},
onEmptyHover: function(element, dropon, overlap) {
var oldParentNode = element.parentNode;
var droponOptions = Sortable.options(dropon);
if(!Element.isParent(dropon, element)) {
var index;
var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
var child = null;
if(children) {
var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);
for (index = 0; index < children.length; index += 1) {
if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
offset -= Element.offsetSize (children[index], droponOptions.overlap);
} else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) {
child = index + 1 < children.length ? children[index + 1] : null;
break;
} else {
child = children[index];
break;
}
}
}
dropon.insertBefore(element, child);
Sortable.options(oldParentNode).onChange(element);
droponOptions.onChange(element);
}
},
unmark: function() {
if(Sortable._marker) Sortable._marker.hide();
},
mark: function(dropon, position) {
// mark on ghosting only
var sortable = Sortable.options(dropon.parentNode);
if(sortable && !sortable.ghosting) return;
if(!Sortable._marker) {
Sortable._marker =
($('dropmarker') || Element.extend(document.createElement('DIV'))).
hide().addClassName('dropmarker').setStyle({position:'absolute'});
document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
}
var offsets = dropon.cumulativeOffset();
Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
if(position=='after')
if(sortable.overlap == 'horizontal')
Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
else
Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
Sortable._marker.show();
},
_tree: function(element, options, parent) {
var children = Sortable.findElements(element, options) || [];
for (var i = 0; i < children.length; ++i) {
var match = children[i].id.match(options.format);
if (!match) continue;
var child = {
id: encodeURIComponent(match ? match[1] : null),
element: element,
parent: parent,
children: [],
position: parent.children.length,
container: $(children[i]).down(options.treeTag)
};
/* Get the element containing the children and recurse over it */
if (child.container)
this._tree(child.container, options, child);
parent.children.push (child);
}
return parent;
},
tree: function(element) {
element = $(element);
var sortableOptions = this.options(element);
var options = Object.extend({
tag: sortableOptions.tag,
treeTag: sortableOptions.treeTag,
only: sortableOptions.only,
name: element.id,
format: sortableOptions.format
}, arguments[1] || { });
var root = {
id: null,
parent: null,
children: [],
container: element,
position: 0
};
return Sortable._tree(element, options, root);
},
/* Construct a [i] index for a particular node */
_constructIndex: function(node) {
var index = '';
do {
if (node.id) index = '[' + node.position + ']' + index;
} while ((node = node.parent) != null);
return index;
},
sequence: function(element) {
element = $(element);
var options = Object.extend(this.options(element), arguments[1] || { });
return $(this.findElements(element, options) || []).map( function(item) {
return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
});
},
setSequence: function(element, new_sequence) {
element = $(element);
var options = Object.extend(this.options(element), arguments[2] || { });
var nodeMap = { };
this.findElements(element, options).each( function(n) {
if (n.id.match(options.format))
nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
n.parentNode.removeChild(n);
});
new_sequence.each(function(ident) {
var n = nodeMap[ident];
if (n) {
n[1].appendChild(n[0]);
delete nodeMap[ident];
}
});
},
serialize: function(element) {
element = $(element);
var options = Object.extend(Sortable.options(element), arguments[1] || { });
var name = encodeURIComponent(
(arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
if (options.tree) {
return Sortable.tree(element, arguments[1]).children.map( function (item) {
return [name + Sortable._constructIndex(item) + "[id]=" +
encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
}).flatten().join('&');
} else {
return Sortable.sequence(element, arguments[1]).map( function(item) {
return name + "[]=" + encodeURIComponent(item);
}).join('&');
}
}
};
// Returns true if child is contained within element
Element.isParent = function(child, element) {
if (!child.parentNode || child == element) return false;
if (child.parentNode == element) return true;
return Element.isParent(child.parentNode, element);
};
Element.findChildren = function(element, only, recursive, tagName) {
if(!element.hasChildNodes()) return null;
tagName = tagName.toUpperCase();
if(only) only = [only].flatten();
var elements = [];
$A(element.childNodes).each( function(e) {
if(e.tagName && e.tagName.toUpperCase()==tagName &&
(!only || (Element.classNames(e).detect(function(v) { return only.include(v) }))))
elements.push(e);
if(recursive) {
var grandchildren = Element.findChildren(e, only, recursive, tagName);
if(grandchildren) elements.push(grandchildren);
}
});
return (elements.length>0 ? elements.flatten() : []);
};
Element.offsetSize = function (element, type) {
return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
};
// script.aculo.us controls.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008
// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// (c) 2005-2008 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
// (c) 2005-2008 Jon Tirsen (http://www.tirsen.com)
// Contributors:
// Richard Livsey
// Rahul Bhargava
// Rob Wills
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
// Autocompleter.Base handles all the autocompletion functionality
// that's independent of the data source for autocompletion. This
// includes drawing the autocompletion menu, observing keyboard
// and mouse events, and similar.
//
// Specific autocompleters need to provide, at the very least,
// a getUpdatedChoices function that will be invoked every time
// the text inside the monitored textbox changes. This method
// should get the text for which to provide autocompletion by
// invoking this.getToken(), NOT by directly accessing
// this.element.value. This is to allow incremental tokenized
// autocompletion. Specific auto-completion logic (AJAX, etc)
// belongs in getUpdatedChoices.
//
// Tokenized incremental autocompletion is enabled automatically
// when an autocompleter is instantiated with the 'tokens' option
// in the options parameter, e.g.:
// new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
// will incrementally autocomplete with a comma as the token.
// Additionally, ',' in the above example can be replaced with
// a token array, e.g. { tokens: [',', '\n'] } which
// enables autocompletion on multiple tokens. This is most
// useful when one of the tokens is \n (a newline), as it
// allows smart autocompletion after linebreaks.
if(typeof Effect == 'undefined')
throw("controls.js requires including script.aculo.us' effects.js library");
var Autocompleter = { };
Autocompleter.Base = Class.create({
baseInitialize: function(element, update, options) {
element = $(element);
this.element = element;
this.update = $(update);
this.hasFocus = false;
this.changed = false;
this.active = false;
this.index = 0;
this.entryCount = 0;
this.oldElementValue = this.element.value;
if(this.setOptions)
this.setOptions(options);
else
this.options = options || { };
this.options.paramName = this.options.paramName || this.element.name;
this.options.tokens = this.options.tokens || [];
this.options.frequency = this.options.frequency || 0.4;
this.options.minChars = this.options.minChars || 1;
this.options.onShow = this.options.onShow ||
function(element, update){
if(!update.style.position || update.style.position=='absolute') {
update.style.position = 'absolute';
Position.clone(element, update, {
setHeight: false,
offsetTop: element.offsetHeight
});
}
Effect.Appear(update,{duration:0.15});
};
this.options.onHide = this.options.onHide ||
function(element, update){ new Effect.Fade(update,{duration:0.15}) };
if(typeof(this.options.tokens) == 'string')
this.options.tokens = new Array(this.options.tokens);
// Force carriage returns as token delimiters anyway
if (!this.options.tokens.include('\n'))
this.options.tokens.push('\n');
this.observer = null;
this.element.setAttribute('autocomplete','off');
Element.hide(this.update);
Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
},
show: function() {
if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
if(!this.iefix &&
(Prototype.Browser.IE) &&
(Element.getStyle(this.update, 'position')=='absolute')) {
new Insertion.After(this.update,
'<iframe id="' + this.update.id + '_iefix" '+
'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
this.iefix = $(this.update.id+'_iefix');
}
if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
},
fixIEOverlapping: function() {
Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
this.iefix.style.zIndex = 1;
this.update.style.zIndex = 2;
Element.show(this.iefix);
},
hide: function() {
this.stopIndicator();
if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
if(this.iefix) Element.hide(this.iefix);
},
startIndicator: function() {
if(this.options.indicator) Element.show(this.options.indicator);
},
stopIndicator: function() {
if(this.options.indicator) Element.hide(this.options.indicator);
},
onKeyPress: function(event) {
if(this.active)
switch(event.keyCode) {
case Event.KEY_TAB:
case Event.KEY_RETURN:
this.selectEntry();
Event.stop(event);
case Event.KEY_ESC:
this.hide();
this.active = false;
Event.stop(event);
return;
case Event.KEY_LEFT:
case Event.KEY_RIGHT:
return;
case Event.KEY_UP:
this.markPrevious();
this.render();
Event.stop(event);
return;
case Event.KEY_DOWN:
this.markNext();
this.render();
Event.stop(event);
return;
}
else
if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
(Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
this.changed = true;
this.hasFocus = true;
if(this.observer) clearTimeout(this.observer);
this.observer =
setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
},
activate: function() {
this.changed = false;
this.hasFocus = true;
this.getUpdatedChoices();
},
onHover: function(event) {
var element = Event.findElement(event, 'LI');
if(this.index != element.autocompleteIndex)
{
this.index = element.autocompleteIndex;
this.render();
}
Event.stop(event);
},
onClick: function(event) {
var element = Event.findElement(event, 'LI');
this.index = element.autocompleteIndex;
this.selectEntry();
this.hide();
},
onBlur: function(event) {
// needed to make click events working
setTimeout(this.hide.bind(this), 250);
this.hasFocus = false;
this.active = false;
},
render: function() {
if(this.entryCount > 0) {
for (var i = 0; i < this.entryCount; i++)
this.index==i ?
Element.addClassName(this.getEntry(i),"selected") :
Element.removeClassName(this.getEntry(i),"selected");
if(this.hasFocus) {
this.show();
this.active = true;
}
} else {
this.active = false;
this.hide();
}
},
markPrevious: function() {
if(this.index > 0) this.index--;
else this.index = this.entryCount-1;
//this.getEntry(this.index).scrollIntoView(true); useless
},
markNext: function() {
if(this.index < this.entryCount-1) this.index++;
else this.index = 0;
this.getEntry(this.index).scrollIntoView(false);
},
getEntry: function(index) {
return this.update.firstChild.childNodes[index];
},
getCurrentEntry: function() {
return this.getEntry(this.index);
},
selectEntry: function() {
this.active = false;
this.updateElement(this.getCurrentEntry());
},
updateElement: function(selectedElement) {
if (this.options.updateElement) {
this.options.updateElement(selectedElement);
return;
}
var value = '';
if (this.options.select) {
var nodes = $(selectedElement).select('.' + this.options.select) || [];
if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
} else
value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
var bounds = this.getTokenBounds();
if (bounds[0] != -1) {
var newValue = this.element.value.substr(0, bounds[0]);
var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
if (whitespace)
newValue += whitespace[0];
this.element.value = newValue + value + this.element.value.substr(bounds[1]);
} else {
this.element.value = value;
}
this.oldElementValue = this.element.value;
this.element.focus();
if (this.options.afterUpdateElement)
this.options.afterUpdateElement(this.element, selectedElement);
},
updateChoices: function(choices) {
if(!this.changed && this.hasFocus) {
this.update.innerHTML = choices;
Element.cleanWhitespace(this.update);
Element.cleanWhitespace(this.update.down());
if(this.update.firstChild && this.update.down().childNodes) {
this.entryCount =
this.update.down().childNodes.length;
for (var i = 0; i < this.entryCount; i++) {
var entry = this.getEntry(i);
entry.autocompleteIndex = i;
this.addObservers(entry);
}
} else {
this.entryCount = 0;
}
this.stopIndicator();
this.index = 0;
if(this.entryCount==1 && this.options.autoSelect) {
this.selectEntry();
this.hide();
} else {
this.render();
}
}
},
addObservers: function(element) {
Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
Event.observe(element, "click", this.onClick.bindAsEventListener(this));
},
onObserverEvent: function() {
this.changed = false;
this.tokenBounds = null;
if(this.getToken().length>=this.options.minChars) {
this.getUpdatedChoices();
} else {
this.active = false;
this.hide();
}
this.oldElementValue = this.element.value;
},
getToken: function() {
var bounds = this.getTokenBounds();
return this.element.value.substring(bounds[0], bounds[1]).strip();
},
getTokenBounds: function() {
if (null != this.tokenBounds) return this.tokenBounds;
var value = this.element.value;
if (value.strip().empty()) return [-1, 0];
var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
var offset = (diff == this.oldElementValue.length ? 1 : 0);
var prevTokenPos = -1, nextTokenPos = value.length;
var tp;
for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
if (tp > prevTokenPos) prevTokenPos = tp;
tp = value.indexOf(this.options.tokens[index], diff + offset);
if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
}
return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
}
});
Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
var boundary = Math.min(newS.length, oldS.length);
for (var index = 0; index < boundary; ++index)
if (newS[index] != oldS[index])
return index;
return boundary;
};
Ajax.Autocompleter = Class.create(Autocompleter.Base, {
initialize: function(element, update, url, options) {
this.baseInitialize(element, update, options);
this.options.asynchronous = true;
this.options.onComplete = this.onComplete.bind(this);
this.options.defaultParams = this.options.parameters || null;
this.url = url;
},
getUpdatedChoices: function() {
this.startIndicator();
var entry = encodeURIComponent(this.options.paramName) + '=' +
encodeURIComponent(this.getToken());
this.options.parameters = this.options.callback ?
this.options.callback(this.element, entry) : entry;
if(this.options.defaultParams)
this.options.parameters += '&' + this.options.defaultParams;
new Ajax.Request(this.url, this.options);
},
onComplete: function(request) {
this.updateChoices(request.responseText);
}
});
// The local array autocompleter. Used when you'd prefer to
// inject an array of autocompletion options into the page, rather
// than sending out Ajax queries, which can be quite slow sometimes.
//
// The constructor takes four parameters. The first two are, as usual,
// the id of the monitored textbox, and id of the autocompletion menu.
// The third is the array you want to autocomplete from, and the fourth
// is the options block.
//
// Extra local autocompletion options:
// - choices - How many autocompletion choices to offer
//
// - partialSearch - If false, the autocompleter will match entered
// text only at the beginning of strings in the
// autocomplete array. Defaults to true, which will
// match text at the beginning of any *word* in the
// strings in the autocomplete array. If you want to
// search anywhere in the string, additionally set
// the option fullSearch to true (default: off).
//
// - fullSsearch - Search anywhere in autocomplete array strings.
//
// - partialChars - How many characters to enter before triggering
// a partial match (unlike minChars, which defines
// how many characters are required to do any match
// at all). Defaults to 2.
//
// - ignoreCase - Whether to ignore case when autocompleting.
// Defaults to true.
//
// It's possible to pass in a custom function as the 'selector'
// option, if you prefer to write your own autocompletion logic.
// In that case, the other options above will not apply unless
// you support them.
Autocompleter.Local = Class.create(Autocompleter.Base, {
initialize: function(element, update, array, options) {
this.baseInitialize(element, update, options);
this.options.array = array;
},
getUpdatedChoices: function() {
this.updateChoices(this.options.selector(this));
},
setOptions: function(options) {
this.options = Object.extend({
choices: 10,
partialSearch: true,
partialChars: 2,
ignoreCase: true,
fullSearch: false,
selector: function(instance) {
var ret = []; // Beginning matches
var partial = []; // Inside matches
var entry = instance.getToken();
var count = 0;
for (var i = 0; i < instance.options.array.length &&
ret.length < instance.options.choices ; i++) {
var elem = instance.options.array[i];
var foundPos = instance.options.ignoreCase ?
elem.toLowerCase().indexOf(entry.toLowerCase()) :
elem.indexOf(entry);
while (foundPos != -1) {
if (foundPos == 0 && elem.length != entry.length) {
ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
elem.substr(entry.length) + "</li>");
break;
} else if (entry.length >= instance.options.partialChars &&
instance.options.partialSearch && foundPos != -1) {
if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
foundPos + entry.length) + "</li>");
break;
}
}
foundPos = instance.options.ignoreCase ?
elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
elem.indexOf(entry, foundPos + 1);
}
}
if (partial.length)
ret = ret.concat(partial.slice(0, instance.options.choices - ret.length));
return "<ul>" + ret.join('') + "</ul>";
}
}, options || { });
}
});
// AJAX in-place editor and collection editor
// Full rewrite by Christophe Porteneuve <tdd@tddsworld.com> (April 2007).
// Use this if you notice weird scrolling problems on some browsers,
// the DOM might be a bit confused when this gets called so do this
// waits 1 ms (with setTimeout) until it does the activation
Field.scrollFreeActivate = function(field) {
setTimeout(function() {
Field.activate(field);
}, 1);
};
Ajax.InPlaceEditor = Class.create({
initialize: function(element, url, options) {
this.url = url;
this.element = element = $(element);
this.prepareOptions();
this._controls = { };
arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!!
Object.extend(this.options, options || { });
if (!this.options.formId && this.element.id) {
this.options.formId = this.element.id + '-inplaceeditor';
if ($(this.options.formId))
this.options.formId = '';
}
if (this.options.externalControl)
this.options.externalControl = $(this.options.externalControl);
if (!this.options.externalControl)
this.options.externalControlOnly = false;
this._originalBackground = this.element.getStyle('background-color') || 'transparent';
this.element.title = this.options.clickToEditText;
this._boundCancelHandler = this.handleFormCancellation.bind(this);
this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
this._boundFailureHandler = this.handleAJAXFailure.bind(this);
this._boundSubmitHandler = this.handleFormSubmission.bind(this);
this._boundWrapperHandler = this.wrapUp.bind(this);
this.registerListeners();
},
checkForEscapeOrReturn: function(e) {
if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return;
if (Event.KEY_ESC == e.keyCode)
this.handleFormCancellation(e);
else if (Event.KEY_RETURN == e.keyCode)
this.handleFormSubmission(e);
},
createControl: function(mode, handler, extraClasses) {
var control = this.options[mode + 'Control'];
var text = this.options[mode + 'Text'];
if ('button' == control) {
var btn = document.createElement('input');
btn.type = 'submit';
btn.value = text;
btn.className = 'editor_' + mode + '_button';
if ('cancel' == mode)
btn.onclick = this._boundCancelHandler;
this._form.appendChild(btn);
this._controls[mode] = btn;
} else if ('link' == control) {
var link = document.createElement('a');
link.href = '#';
link.appendChild(document.createTextNode(text));
link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
link.className = 'editor_' + mode + '_link';
if (extraClasses)
link.className += ' ' + extraClasses;
this._form.appendChild(link);
this._controls[mode] = link;
}
},
createEditField: function() {
var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
var fld;
if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) {
fld = document.createElement('input');
fld.type = 'text';
var size = this.options.size || this.options.cols || 0;
if (0 < size) fld.size = size;
} else {
fld = document.createElement('textarea');
fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows);
fld.cols = this.options.cols || 40;
}
fld.name = this.options.paramName;
fld.value = text; // No HTML breaks conversion anymore
fld.className = 'editor_field';
if (this.options.submitOnBlur)
fld.onblur = this._boundSubmitHandler;
this._controls.editor = fld;
if (this.options.loadTextURL)
this.loadExternalText();
this._form.appendChild(this._controls.editor);
},
createForm: function() {
var ipe = this;
function addText(mode, condition) {
var text = ipe.options['text' + mode + 'Controls'];
if (!text || condition === false) return;
ipe._form.appendChild(document.createTextNode(text));
};
this._form = $(document.createElement('form'));
this._form.id = this.options.formId;
this._form.addClassName(this.options.formClassName);
this._form.onsubmit = this._boundSubmitHandler;
this.createEditField();
if ('textarea' == this._controls.editor.tagName.toLowerCase())
this._form.appendChild(document.createElement('br'));
if (this.options.onFormCustomization)
this.options.onFormCustomization(this, this._form);
addText('Before', this.options.okControl || this.options.cancelControl);
this.createControl('ok', this._boundSubmitHandler);
addText('Between', this.options.okControl && this.options.cancelControl);
this.createControl('cancel', this._boundCancelHandler, 'editor_cancel');
addText('After', this.options.okControl || this.options.cancelControl);
},
destroy: function() {
if (this._oldInnerHTML)
this.element.innerHTML = this._oldInnerHTML;
this.leaveEditMode();
this.unregisterListeners();
},
enterEditMode: function(e) {
if (this._saving || this._editing) return;
this._editing = true;
this.triggerCallback('onEnterEditMode');
if (this.options.externalControl)
this.options.externalControl.hide();
this.element.hide();
this.createForm();
this.element.parentNode.insertBefore(this._form, this.element);
if (!this.options.loadTextURL)
this.postProcessEditField();
if (e) Event.stop(e);
},
enterHover: function(e) {
if (this.options.hoverClassName)
this.element.addClassName(this.options.hoverClassName);
if (this._saving) return;
this.triggerCallback('onEnterHover');
},
getText: function() {
return this.element.innerHTML.unescapeHTML();
},
handleAJAXFailure: function(transport) {
this.triggerCallback('onFailure', transport);
if (this._oldInnerHTML) {
this.element.innerHTML = this._oldInnerHTML;
this._oldInnerHTML = null;
}
},
handleFormCancellation: function(e) {
this.wrapUp();
if (e) Event.stop(e);
},
handleFormSubmission: function(e) {
var form = this._form;
var value = $F(this._controls.editor);
this.prepareSubmission();
var params = this.options.callback(form, value) || '';
if (Object.isString(params))
params = params.toQueryParams();
params.editorId = this.element.id;
if (this.options.htmlResponse) {
var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions);
Object.extend(options, {
parameters: params,
onComplete: this._boundWrapperHandler,
onFailure: this._boundFailureHandler
});
new Ajax.Updater({ success: this.element }, this.url, options);
} else {
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: params,
onComplete: this._boundWrapperHandler,
onFailure: this._boundFailureHandler
});
new Ajax.Request(this.url, options);
}
if (e) Event.stop(e);
},
leaveEditMode: function() {
this.element.removeClassName(this.options.savingClassName);
this.removeForm();
this.leaveHover();
this.element.style.backgroundColor = this._originalBackground;
this.element.show();
if (this.options.externalControl)
this.options.externalControl.show();
this._saving = false;
this._editing = false;
this._oldInnerHTML = null;
this.triggerCallback('onLeaveEditMode');
},
leaveHover: function(e) {
if (this.options.hoverClassName)
this.element.removeClassName(this.options.hoverClassName);
if (this._saving) return;
this.triggerCallback('onLeaveHover');
},
loadExternalText: function() {
this._form.addClassName(this.options.loadingClassName);
this._controls.editor.disabled = true;
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: 'editorId=' + encodeURIComponent(this.element.id),
onComplete: Prototype.emptyFunction,
onSuccess: function(transport) {
this._form.removeClassName(this.options.loadingClassName);
var text = transport.responseText;
if (this.options.stripLoadedTextTags)
text = text.stripTags();
this._controls.editor.value = text;
this._controls.editor.disabled = false;
this.postProcessEditField();
}.bind(this),
onFailure: this._boundFailureHandler
});
new Ajax.Request(this.options.loadTextURL, options);
},
postProcessEditField: function() {
var fpc = this.options.fieldPostCreation;
if (fpc)
$(this._controls.editor)['focus' == fpc ? 'focus' : 'activate']();
},
prepareOptions: function() {
this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions);
Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks);
[this._extraDefaultOptions].flatten().compact().each(function(defs) {
Object.extend(this.options, defs);
}.bind(this));
},
prepareSubmission: function() {
this._saving = true;
this.removeForm();
this.leaveHover();
this.showSaving();
},
registerListeners: function() {
this._listeners = { };
var listener;
$H(Ajax.InPlaceEditor.Listeners).each(function(pair) {
listener = this[pair.value].bind(this);
this._listeners[pair.key] = listener;
if (!this.options.externalControlOnly)
this.element.observe(pair.key, listener);
if (this.options.externalControl)
this.options.externalControl.observe(pair.key, listener);
}.bind(this));
},
removeForm: function() {
if (!this._form) return;
this._form.remove();
this._form = null;
this._controls = { };
},
showSaving: function() {
this._oldInnerHTML = this.element.innerHTML;
this.element.innerHTML = this.options.savingText;
this.element.addClassName(this.options.savingClassName);
this.element.style.backgroundColor = this._originalBackground;
this.element.show();
},
triggerCallback: function(cbName, arg) {
if ('function' == typeof this.options[cbName]) {
this.options[cbName](this, arg);
}
},
unregisterListeners: function() {
$H(this._listeners).each(function(pair) {
if (!this.options.externalControlOnly)
this.element.stopObserving(pair.key, pair.value);
if (this.options.externalControl)
this.options.externalControl.stopObserving(pair.key, pair.value);
}.bind(this));
},
wrapUp: function(transport) {
this.leaveEditMode();
// Can't use triggerCallback due to backward compatibility: requires
// binding + direct element
this._boundComplete(transport, this.element);
}
});
Object.extend(Ajax.InPlaceEditor.prototype, {
dispose: Ajax.InPlaceEditor.prototype.destroy
});
Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
initialize: function($super, element, url, options) {
this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions;
$super(element, url, options);
},
createEditField: function() {
var list = document.createElement('select');
list.name = this.options.paramName;
list.size = 1;
this._controls.editor = list;
this._collection = this.options.collection || [];
if (this.options.loadCollectionURL)
this.loadCollection();
else
this.checkForExternalText();
this._form.appendChild(this._controls.editor);
},
loadCollection: function() {
this._form.addClassName(this.options.loadingClassName);
this.showLoadingText(this.options.loadingCollectionText);
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: 'editorId=' + encodeURIComponent(this.element.id),
onComplete: Prototype.emptyFunction,
onSuccess: function(transport) {
var js = transport.responseText.strip();
if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
throw('Server returned an invalid collection representation.');
this._collection = eval(js);
this.checkForExternalText();
}.bind(this),
onFailure: this.onFailure
});
new Ajax.Request(this.options.loadCollectionURL, options);
},
showLoadingText: function(text) {
this._controls.editor.disabled = true;
var tempOption = this._controls.editor.firstChild;
if (!tempOption) {
tempOption = document.createElement('option');
tempOption.value = '';
this._controls.editor.appendChild(tempOption);
tempOption.selected = true;
}
tempOption.update((text || '').stripScripts().stripTags());
},
checkForExternalText: function() {
this._text = this.getText();
if (this.options.loadTextURL)
this.loadExternalText();
else
this.buildOptionList();
},
loadExternalText: function() {
this.showLoadingText(this.options.loadingText);
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: 'editorId=' + encodeURIComponent(this.element.id),
onComplete: Prototype.emptyFunction,
onSuccess: function(transport) {
this._text = transport.responseText.strip();
this.buildOptionList();
}.bind(this),
onFailure: this.onFailure
});
new Ajax.Request(this.options.loadTextURL, options);
},
buildOptionList: function() {
this._form.removeClassName(this.options.loadingClassName);
this._collection = this._collection.map(function(entry) {
return 2 === entry.length ? entry : [entry, entry].flatten();
});
var marker = ('value' in this.options) ? this.options.value : this._text;
var textFound = this._collection.any(function(entry) {
return entry[0] == marker;
}.bind(this));
this._controls.editor.update('');
var option;
this._collection.each(function(entry, index) {
option = document.createElement('option');
option.value = entry[0];
option.selected = textFound ? entry[0] == marker : 0 == index;
option.appendChild(document.createTextNode(entry[1]));
this._controls.editor.appendChild(option);
}.bind(this));
this._controls.editor.disabled = false;
Field.scrollFreeActivate(this._controls.editor);
}
});
//**** DEPRECATION LAYER FOR InPlace[Collection]Editor! ****
//**** This only exists for a while, in order to let ****
//**** users adapt to the new API. Read up on the new ****
//**** API and convert your code to it ASAP! ****
Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) {
if (!options) return;
function fallback(name, expr) {
if (name in options || expr === undefined) return;
options[name] = expr;
};
fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' :
options.cancelLink == options.cancelButton == false ? false : undefined)));
fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' :
options.okLink == options.okButton == false ? false : undefined)));
fallback('highlightColor', options.highlightcolor);
fallback('highlightEndColor', options.highlightendcolor);
};
Object.extend(Ajax.InPlaceEditor, {
DefaultOptions: {
ajaxOptions: { },
autoRows: 3, // Use when multi-line w/ rows == 1
cancelControl: 'link', // 'link'|'button'|false
cancelText: 'cancel',
clickToEditText: 'Click to edit',
externalControl: null, // id|elt
externalControlOnly: false,
fieldPostCreation: 'activate', // 'activate'|'focus'|false
formClassName: 'inplaceeditor-form',
formId: null, // id|elt
highlightColor: '#ffff99',
highlightEndColor: '#ffffff',
hoverClassName: '',
htmlResponse: true,
loadingClassName: 'inplaceeditor-loading',
loadingText: 'Loading...',
okControl: 'button', // 'link'|'button'|false
okText: 'ok',
paramName: 'value',
rows: 1, // If 1 and multi-line, uses autoRows
savingClassName: 'inplaceeditor-saving',
savingText: 'Saving...',
size: 0,
stripLoadedTextTags: false,
submitOnBlur: false,
textAfterControls: '',
textBeforeControls: '',
textBetweenControls: ''
},
DefaultCallbacks: {
callback: function(form) {
return Form.serialize(form);
},
onComplete: function(transport, element) {
// For backward compatibility, this one is bound to the IPE, and passes
// the element directly. It was too often customized, so we don't break it.
new Effect.Highlight(element, {
startcolor: this.options.highlightColor, keepBackgroundImage: true });
},
onEnterEditMode: null,
onEnterHover: function(ipe) {
ipe.element.style.backgroundColor = ipe.options.highlightColor;
if (ipe._effect)
ipe._effect.cancel();
},
onFailure: function(transport, ipe) {
alert('Error communication with the server: ' + transport.responseText.stripTags());
},
onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls.
onLeaveEditMode: null,
onLeaveHover: function(ipe) {
ipe._effect = new Effect.Highlight(ipe.element, {
startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor,
restorecolor: ipe._originalBackground, keepBackgroundImage: true
});
}
},
Listeners: {
click: 'enterEditMode',
keydown: 'checkForEscapeOrReturn',
mouseover: 'enterHover',
mouseout: 'leaveHover'
}
});
Ajax.InPlaceCollectionEditor.DefaultOptions = {
loadingCollectionText: 'Loading options...'
};
// Delayed observer, like Form.Element.Observer,
// but waits for delay after last key input
// Ideal for live-search fields
Form.Element.DelayedObserver = Class.create({
initialize: function(element, delay, callback) {
this.delay = delay || 0.5;
this.element = $(element);
this.callback = callback;
this.timer = null;
this.lastValue = $F(this.element);
Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
},
delayedListener: function(event) {
if(this.lastValue == $F(this.element)) return;
if(this.timer) clearTimeout(this.timer);
this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
this.lastValue = $F(this.element);
},
onTimerEvent: function() {
this.timer = null;
this.callback(this.element, $F(this.element));
}
});
// script.aculo.us slider.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008
// Copyright (c) 2005-2008 Marty Haught, Thomas Fuchs
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
if (!Control) var Control = { };
// options:
// axis: 'vertical', or 'horizontal' (default)
//
// callbacks:
// onChange(value)
// onSlide(value)
Control.Slider = Class.create({
initialize: function(handle, track, options) {
var slider = this;
if (Object.isArray(handle)) {
this.handles = handle.collect( function(e) { return $(e) });
} else {
this.handles = [$(handle)];
}
this.track = $(track);
this.options = options || { };
this.axis = this.options.axis || 'horizontal';
this.increment = this.options.increment || 1;
this.step = parseInt(this.options.step || '1');
this.range = this.options.range || $R(0,1);
this.value = 0; // assure backwards compat
this.values = this.handles.map( function() { return 0 });
this.spans = this.options.spans ? this.options.spans.map(function(s){ return $(s) }) : false;
this.options.startSpan = $(this.options.startSpan || null);
this.options.endSpan = $(this.options.endSpan || null);
this.restricted = this.options.restricted || false;
this.maximum = this.options.maximum || this.range.end;
this.minimum = this.options.minimum || this.range.start;
// Will be used to align the handle onto the track, if necessary
this.alignX = parseInt(this.options.alignX || '0');
this.alignY = parseInt(this.options.alignY || '0');
this.trackLength = this.maximumOffset() - this.minimumOffset();
this.handleLength = this.isVertical() ?
(this.handles[0].offsetHeight != 0 ?
this.handles[0].offsetHeight : this.handles[0].style.height.replace(/px$/,"")) :
(this.handles[0].offsetWidth != 0 ? this.handles[0].offsetWidth :
this.handles[0].style.width.replace(/px$/,""));
this.active = false;
this.dragging = false;
this.disabled = false;
if (this.options.disabled) this.setDisabled();
// Allowed values array
this.allowedValues = this.options.values ? this.options.values.sortBy(Prototype.K) : false;
if (this.allowedValues) {
this.minimum = this.allowedValues.min();
this.maximum = this.allowedValues.max();
}
this.eventMouseDown = this.startDrag.bindAsEventListener(this);
this.eventMouseUp = this.endDrag.bindAsEventListener(this);
this.eventMouseMove = this.update.bindAsEventListener(this);
// Initialize handles in reverse (make sure first handle is active)
this.handles.each( function(h,i) {
i = slider.handles.length-1-i;
slider.setValue(parseFloat(
(Object.isArray(slider.options.sliderValue) ?
slider.options.sliderValue[i] : slider.options.sliderValue) ||
slider.range.start), i);
h.makePositioned().observe("mousedown", slider.eventMouseDown);
});
this.track.observe("mousedown", this.eventMouseDown);
document.observe("mouseup", this.eventMouseUp);
$(this.track.parentNode.parentNode).observe("mousemove", this.eventMouseMove);
this.initialized = true;
},
dispose: function() {
var slider = this;
Event.stopObserving(this.track, "mousedown", this.eventMouseDown);
Event.stopObserving(document, "mouseup", this.eventMouseUp);
Event.stopObserving(this.track.parentNode.parentNode, "mousemove", this.eventMouseMove);
this.handles.each( function(h) {
Event.stopObserving(h, "mousedown", slider.eventMouseDown);
});
},
setDisabled: function(){
this.disabled = true;
this.track.parentNode.className = this.track.parentNode.className + ' disabled';
},
setEnabled: function(){
this.disabled = false;
},
getNearestValue: function(value){
if (this.allowedValues){
if (value >= this.allowedValues.max()) return(this.allowedValues.max());
if (value <= this.allowedValues.min()) return(this.allowedValues.min());
var offset = Math.abs(this.allowedValues[0] - value);
var newValue = this.allowedValues[0];
this.allowedValues.each( function(v) {
var currentOffset = Math.abs(v - value);
if (currentOffset <= offset){
newValue = v;
offset = currentOffset;
}
});
return newValue;
}
if (value > this.range.end) return this.range.end;
if (value < this.range.start) return this.range.start;
return value;
},
setValue: function(sliderValue, handleIdx){
if (!this.active) {
this.activeHandleIdx = handleIdx || 0;
this.activeHandle = this.handles[this.activeHandleIdx];
this.updateStyles();
}
handleIdx = handleIdx || this.activeHandleIdx || 0;
if (this.initialized && this.restricted) {
if ((handleIdx>0) && (sliderValue<this.values[handleIdx-1]))
sliderValue = this.values[handleIdx-1];
if ((handleIdx < (this.handles.length-1)) && (sliderValue>this.values[handleIdx+1]))
sliderValue = this.values[handleIdx+1];
}
sliderValue = this.getNearestValue(sliderValue);
this.values[handleIdx] = sliderValue;
this.value = this.values[0]; // assure backwards compat
this.handles[handleIdx].style[this.isVertical() ? 'top' : 'left'] =
this.translateToPx(sliderValue);
this.drawSpans();
if (!this.dragging || !this.event) this.updateFinished();
},
setValueBy: function(delta, handleIdx) {
this.setValue(this.values[handleIdx || this.activeHandleIdx || 0] + delta,
handleIdx || this.activeHandleIdx || 0);
},
translateToPx: function(value) {
return Math.round(
((this.trackLength-this.handleLength)/(this.range.end-this.range.start)) *
(value - this.range.start)) + "px";
},
translateToValue: function(offset) {
return ((offset/(this.trackLength-this.handleLength) *
(this.range.end-this.range.start)) + this.range.start);
},
getRange: function(range) {
var v = this.values.sortBy(Prototype.K);
range = range || 0;
return $R(v[range],v[range+1]);
},
minimumOffset: function(){
return(this.isVertical() ? this.alignY : this.alignX);
},
maximumOffset: function(){
return(this.isVertical() ?
(this.track.offsetHeight != 0 ? this.track.offsetHeight :
this.track.style.height.replace(/px$/,"")) - this.alignY :
(this.track.offsetWidth != 0 ? this.track.offsetWidth :
this.track.style.width.replace(/px$/,"")) - this.alignX);
},
isVertical: function(){
return (this.axis == 'vertical');
},
drawSpans: function() {
var slider = this;
if (this.spans)
$R(0, this.spans.length-1).each(function(r) { slider.setSpan(slider.spans[r], slider.getRange(r)) });
if (this.options.startSpan)
this.setSpan(this.options.startSpan,
$R(0, this.values.length>1 ? this.getRange(0).min() : this.value ));
if (this.options.endSpan)
this.setSpan(this.options.endSpan,
$R(this.values.length>1 ? this.getRange(this.spans.length-1).max() : this.value, this.maximum));
},
setSpan: function(span, range) {
if (this.isVertical()) {
span.style.top = this.translateToPx(range.start);
span.style.height = this.translateToPx(range.end - range.start + this.range.start);
} else {
span.style.left = this.translateToPx(range.start);
span.style.width = this.translateToPx(range.end - range.start + this.range.start);
}
},
updateStyles: function() {
this.handles.each( function(h){ Element.removeClassName(h, 'selected') });
Element.addClassName(this.activeHandle, 'selected');
},
startDrag: function(event) {
if (Event.isLeftClick(event)) {
if (!this.disabled){
this.active = true;
var handle = Event.element(event);
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var track = handle;
if (track==this.track) {
var offsets = Position.cumulativeOffset(this.track);
this.event = event;
this.setValue(this.translateToValue(
(this.isVertical() ? pointer[1]-offsets[1] : pointer[0]-offsets[0])-(this.handleLength/2)
));
var offsets = Position.cumulativeOffset(this.activeHandle);
this.offsetX = (pointer[0] - offsets[0]);
this.offsetY = (pointer[1] - offsets[1]);
} else {
// find the handle (prevents issues with Safari)
while((this.handles.indexOf(handle) == -1) && handle.parentNode)
handle = handle.parentNode;
if (this.handles.indexOf(handle)!=-1) {
this.activeHandle = handle;
this.activeHandleIdx = this.handles.indexOf(this.activeHandle);
this.updateStyles();
var offsets = Position.cumulativeOffset(this.activeHandle);
this.offsetX = (pointer[0] - offsets[0]);
this.offsetY = (pointer[1] - offsets[1]);
}
}
}
Event.stop(event);
}
},
update: function(event) {
if (this.active) {
if (!this.dragging) this.dragging = true;
this.draw(event);
if (Prototype.Browser.WebKit) window.scrollBy(0,0);
Event.stop(event);
}
},
draw: function(event) {
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var offsets = Position.cumulativeOffset(this.track);
pointer[0] -= this.offsetX + offsets[0];
pointer[1] -= this.offsetY + offsets[1];
this.event = event;
this.setValue(this.translateToValue( this.isVertical() ? pointer[1] : pointer[0] ));
if (this.initialized && this.options.onSlide)
this.options.onSlide(this.values.length>1 ? this.values : this.value, this);
},
endDrag: function(event) {
if (this.active && this.dragging) {
this.finishDrag(event, true);
Event.stop(event);
}
this.active = false;
this.dragging = false;
},
finishDrag: function(event, success) {
this.active = false;
this.dragging = false;
this.updateFinished();
},
updateFinished: function() {
if (this.initialized && this.options.onChange)
this.options.onChange(this.values.length>1 ? this.values : this.value, this);
this.event = null;
}
});
/**
* Magento Enterprise Edition
*
* NOTICE OF LICENSE
*
* This source file is subject to the Magento Enterprise Edition End User License Agreement
* that is bundled with this package in the file LICENSE_EE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.magento.com/license/enterprise-edition
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Varien
* @package js
* @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
* @license http://www.magento.com/license/enterprise-edition
*/
function popWin(url,win,para) {
var win = window.open(url,win,para);
win.focus();
}
function setLocation(url){
window.location.href = url;
}
function setPLocation(url, setFocus){
if( setFocus ) {
window.opener.focus();
}
window.opener.location.href = url;
}
function setLanguageCode(code, fromCode){
//TODO: javascript cookies have different domain and path than php cookies
var href = window.location.href;
var after = '', dash;
if (dash = href.match(/\#(.*)$/)) {
href = href.replace(/\#(.*)$/, '');
after = dash[0];
}
if (href.match(/[?]/)) {
var re = /([?&]store=)[a-z0-9_]*/;
if (href.match(re)) {
href = href.replace(re, '$1'+code);
} else {
href += '&store='+code;
}
var re = /([?&]from_store=)[a-z0-9_]*/;
if (href.match(re)) {
href = href.replace(re, '');
}
} else {
href += '?store='+code;
}
if (typeof(fromCode) != 'undefined') {
href += '&from_store='+fromCode;
}
href += after;
setLocation(href);
}
/**
* Add classes to specified elements.
* Supported classes are: 'odd', 'even', 'first', 'last'
*
* @param elements - array of elements to be decorated
* [@param decorateParams] - array of classes to be set. If omitted, all available will be used
*/
function decorateGeneric(elements, decorateParams)
{
var allSupportedParams = ['odd', 'even', 'first', 'last'];
var _decorateParams = {};
var total = elements.length;
if (total) {
// determine params called
if (typeof(decorateParams) == 'undefined') {
decorateParams = allSupportedParams;
}
if (!decorateParams.length) {
return;
}
for (var k in allSupportedParams) {
_decorateParams[allSupportedParams[k]] = false;
}
for (var k in decorateParams) {
_decorateParams[decorateParams[k]] = true;
}
// decorate elements
// elements[0].addClassName('first'); // will cause bug in IE (#5587)
if (_decorateParams.first) {
Element.addClassName(elements[0], 'first');
}
if (_decorateParams.last) {
Element.addClassName(elements[total-1], 'last');
}
for (var i = 0; i < total; i++) {
if ((i + 1) % 2 == 0) {
if (_decorateParams.even) {
Element.addClassName(elements[i], 'even');
}
}
else {
if (_decorateParams.odd) {
Element.addClassName(elements[i], 'odd');
}
}
}
}
}
/**
* Decorate table rows and cells, tbody etc
* @see decorateGeneric()
*/
function decorateTable(table, options) {
var table = $(table);
if (table) {
// set default options
var _options = {
'tbody' : false,
'tbody tr' : ['odd', 'even', 'first', 'last'],
'thead tr' : ['first', 'last'],
'tfoot tr' : ['first', 'last'],
'tr td' : ['last']
};
// overload options
if (typeof(options) != 'undefined') {
for (var k in options) {
_options[k] = options[k];
}
}
// decorate
if (_options['tbody']) {
decorateGeneric(table.select('tbody'), _options['tbody']);
}
if (_options['tbody tr']) {
decorateGeneric(table.select('tbody tr'), _options['tbody tr']);
}
if (_options['thead tr']) {
decorateGeneric(table.select('thead tr'), _options['thead tr']);
}
if (_options['tfoot tr']) {
decorateGeneric(table.select('tfoot tr'), _options['tfoot tr']);
}
if (_options['tr td']) {
var allRows = table.select('tr');
if (allRows.length) {
for (var i = 0; i < allRows.length; i++) {
decorateGeneric(allRows[i].getElementsByTagName('TD'), _options['tr td']);
}
}
}
}
}
/**
* Set "odd", "even" and "last" CSS classes for list items
* @see decorateGeneric()
*/
function decorateList(list, nonRecursive) {
if ($(list)) {
if (typeof(nonRecursive) == 'undefined') {
var items = $(list).select('li')
}
else {
var items = $(list).childElements();
}
decorateGeneric(items, ['odd', 'even', 'last']);
}
}
/**
* Set "odd", "even" and "last" CSS classes for list items
* @see decorateGeneric()
*/
function decorateDataList(list) {
list = $(list);
if (list) {
decorateGeneric(list.select('dt'), ['odd', 'even', 'last']);
decorateGeneric(list.select('dd'), ['odd', 'even', 'last']);
}
}
/**
* Parse SID and produces the correct URL
*/
function parseSidUrl(baseUrl, urlExt) {
var sidPos = baseUrl.indexOf('/?SID=');
var sid = '';
urlExt = (urlExt != undefined) ? urlExt : '';
if(sidPos > -1) {
sid = '?' + baseUrl.substring(sidPos + 2);
baseUrl = baseUrl.substring(0, sidPos + 1);
}
return baseUrl+urlExt+sid;
}
/**
* Formats currency using patern
* format - JSON (pattern, decimal, decimalsDelimeter, groupsDelimeter)
* showPlus - true (always show '+'or '-'),
* false (never show '-' even if number is negative)
* null (show '-' if number is negative)
*/
function formatCurrency(price, format, showPlus){
var precision = isNaN(format.precision = Math.abs(format.precision)) ? 2 : format.precision;
var requiredPrecision = isNaN(format.requiredPrecision = Math.abs(format.requiredPrecision)) ? 2 : format.requiredPrecision;
//precision = (precision > requiredPrecision) ? precision : requiredPrecision;
//for now we don't need this difference so precision is requiredPrecision
precision = requiredPrecision;
var integerRequired = isNaN(format.integerRequired = Math.abs(format.integerRequired)) ? 1 : format.integerRequired;
var decimalSymbol = format.decimalSymbol == undefined ? "," : format.decimalSymbol;
var groupSymbol = format.groupSymbol == undefined ? "." : format.groupSymbol;
var groupLength = format.groupLength == undefined ? 3 : format.groupLength;
var s = '';
if (showPlus == undefined || showPlus == true) {
s = price < 0 ? "-" : ( showPlus ? "+" : "");
} else if (showPlus == false) {
s = '';
}
var i = parseInt(price = Math.abs(+price || 0).toFixed(precision)) + "";
var pad = (i.length < integerRequired) ? (integerRequired - i.length) : 0;
while (pad) { i = '0' + i; pad--; }
j = (j = i.length) > groupLength ? j % groupLength : 0;
re = new RegExp("(\\d{" + groupLength + "})(?=\\d)", "g");
/**
* replace(/-/, 0) is only for fixing Safari bug which appears
* when Math.abs(0).toFixed() executed on "0" number.
* Result is "0.-0" :(
*/
var r = (j ? i.substr(0, j) + groupSymbol : "") + i.substr(j).replace(re, "$1" + groupSymbol) + (precision ? decimalSymbol + Math.abs(price - i).toFixed(precision).replace(/-/, 0).slice(2) : "")
var pattern = '';
if (format.pattern.indexOf('{sign}') == -1) {
pattern = s + format.pattern;
} else {
pattern = format.pattern.replace('{sign}', s);
}
return pattern.replace('%s', r).replace(/^\s\s*/, '').replace(/\s\s*$/, '');
};
function expandDetails(el, childClass) {
if (Element.hasClassName(el,'show-details')) {
$$(childClass).each(function(item){item.hide()});
Element.removeClassName(el,'show-details');
}
else {
$$(childClass).each(function(item){item.show()});
Element.addClassName(el,'show-details');
}
}
// Version 1.0
var isIE = navigator.appVersion.match(/MSIE/) == "MSIE";
if (!window.Varien)
var Varien = new Object();
Varien.showLoading = function(){
var loader = $('loading-process');
loader && loader.show();
}
Varien.hideLoading = function(){
var loader = $('loading-process');
loader && loader.hide();
}
Varien.GlobalHandlers = {
onCreate: function() {
Varien.showLoading();
},
onComplete: function() {
if(Ajax.activeRequestCount == 0) {
Varien.hideLoading();
}
}
};
Ajax.Responders.register(Varien.GlobalHandlers);
/**
* Quick Search form client model
*/
Varien.searchForm = Class.create();
Varien.searchForm.prototype = {
initialize : function(form, field, emptyText){
this.form = $(form);
this.field = $(field);
this.emptyText = emptyText;
Event.observe(this.form, 'submit', this.submit.bind(this));
Event.observe(this.field, 'focus', this.focus.bind(this));
Event.observe(this.field, 'blur', this.blur.bind(this));
this.blur();
},
submit : function(event){
if (this.field.value == this.emptyText || this.field.value == ''){
Event.stop(event);
return false;
}
return true;
},
focus : function(event){
if(this.field.value==this.emptyText){
this.field.value='';
}
},
blur : function(event){
if(this.field.value==''){
this.field.value=this.emptyText;
}
},
initAutocomplete : function(url, destinationElement){
new Ajax.Autocompleter(
this.field,
destinationElement,
url,
{
paramName: this.field.name,
method: 'get',
minChars: 2,
updateElement: this._selectAutocompleteItem.bind(this),
onShow : function(element, update) {
if(!update.style.position || update.style.position=='absolute') {
update.style.position = 'absolute';
Position.clone(element, update, {
setHeight: false,
offsetTop: element.offsetHeight
});
}
Effect.Appear(update,{duration:0});
}
}
);
},
_selectAutocompleteItem : function(element){
if(element.title){
this.field.value = element.title;
}
this.form.submit();
}
}
Varien.Tabs = Class.create();
Varien.Tabs.prototype = {
initialize: function(selector) {
var self=this;
$$(selector+' a').each(this.initTab.bind(this));
},
initTab: function(el) {
el.href = 'javascript:void(0)';
if ($(el.parentNode).hasClassName('active')) {
this.showContent(el);
}
el.observe('click', this.showContent.bind(this, el));
},
showContent: function(a) {
var li = $(a.parentNode), ul = $(li.parentNode);
ul.getElementsBySelector('li', 'ol').each(function(el){
var contents = $(el.id+'_contents');
if (el==li) {
el.addClassName('active');
contents.show();
} else {
el.removeClassName('active');
contents.hide();
}
});
}
}
Varien.DateElement = Class.create();
Varien.DateElement.prototype = {
initialize: function(type, content, required, format) {
if (type == 'id') {
// id prefix
this.day = $(content + 'day');
this.month = $(content + 'month');
this.year = $(content + 'year');
this.full = $(content + 'full');
this.advice = $(content + 'date-advice');
} else if (type == 'container') {
// content must be container with data
this.day = content.day;
this.month = content.month;
this.year = content.year;
this.full = content.full;
this.advice = content.advice;
} else {
return;
}
this.required = required;
this.format = format;
this.day.addClassName('validate-custom');
this.day.validate = this.validate.bind(this);
this.month.addClassName('validate-custom');
this.month.validate = this.validate.bind(this);
this.year.addClassName('validate-custom');
this.year.validate = this.validate.bind(this);
this.setDateRange(false, false);
this.year.setAttribute('autocomplete','off');
this.advice.hide();
},
validate: function() {
var error = false,
day = parseInt(this.day.value, 10) || 0,
month = parseInt(this.month.value, 10) || 0,
year = parseInt(this.year.value, 10) || 0;
if (this.day.value.strip().empty()
&& this.month.value.strip().empty()
&& this.year.value.strip().empty()
) {
if (this.required) {
error = 'This date is a required value.';
} else {
this.full.value = '';
}
} else if (!day || !month || !year) {
error = 'Please enter a valid full date.';
} else {
var date = new Date, countDaysInMonth = 0, errorType = null;
date.setYear(year);date.setMonth(month-1);date.setDate(32);
countDaysInMonth = 32 - date.getDate();
if(!countDaysInMonth || countDaysInMonth>31) countDaysInMonth = 31;
if (day<1 || day>countDaysInMonth) {
errorType = 'day';
error = 'Please enter a valid day (1-%d).';
} else if (month<1 || month>12) {
errorType = 'month';
error = 'Please enter a valid month (1-12).';
} else {
if(day % 10 == day) this.day.value = '0'+day;
if(month % 10 == month) this.month.value = '0'+month;
this.full.value = this.format.replace(/%[mb]/i, this.month.value).replace(/%[de]/i, this.day.value).replace(/%y/i, this.year.value);
var testFull = this.month.value + '/' + this.day.value + '/'+ this.year.value;
var test = new Date(testFull);
if (isNaN(test)) {
error = 'Please enter a valid date.';
} else {
this.setFullDate(test);
}
}
var valueError = false;
if (!error && !this.validateData()){//(year<1900 || year>curyear) {
errorType = this.validateDataErrorType;//'year';
valueError = this.validateDataErrorText;//'Please enter a valid year (1900-%d).';
error = valueError;
}
}
if (error !== false) {
try {
error = Translator.translate(error);
}
catch (e) {}
if (!valueError) {
this.advice.innerHTML = error.replace('%d', countDaysInMonth);
} else {
this.advice.innerHTML = this.errorTextModifier(error);
}
this.advice.show();
return false;
}
// fixing elements class
this.day.removeClassName('validation-failed');
this.month.removeClassName('validation-failed');
this.year.removeClassName('validation-failed');
this.advice.hide();
return true;
},
validateData: function() {
var year = this.fullDate.getFullYear();
var date = new Date;
this.curyear = date.getFullYear();
return (year>=1900 && year<=this.curyear);
},
validateDataErrorType: 'year',
validateDataErrorText: 'Please enter a valid year (1900-%d).',
errorTextModifier: function(text) {
return text.replace('%d', this.curyear);
},
setDateRange: function(minDate, maxDate) {
this.minDate = minDate;
this.maxDate = maxDate;
},
setFullDate: function(date) {
this.fullDate = date;
}
};
Varien.DOB = Class.create();
Varien.DOB.prototype = {
initialize: function(selector, required, format) {
var el = $$(selector)[0];
var container = {};
container.day = Element.select(el, '.dob-day input')[0];
container.month = Element.select(el, '.dob-month input')[0];
container.year = Element.select(el, '.dob-year input')[0];
container.full = Element.select(el, '.dob-full input')[0];
container.advice = Element.select(el, '.validation-advice')[0];
new Varien.DateElement('container', container, required, format);
}
};
Varien.dateRangeDate = Class.create();
Varien.dateRangeDate.prototype = Object.extend(new Varien.DateElement(), {
validateData: function() {
var validate = true;
if (this.minDate || this.maxValue) {
if (this.minDate) {
this.minDate = new Date(this.minDate);
this.minDate.setHours(0);
if (isNaN(this.minDate)) {
this.minDate = new Date('1/1/1900');
}
validate = validate && (this.fullDate >= this.minDate)
}
if (this.maxDate) {
this.maxDate = new Date(this.maxDate)
this.minDate.setHours(0);
if (isNaN(this.maxDate)) {
this.maxDate = new Date();
}
validate = validate && (this.fullDate <= this.maxDate)
}
if (this.maxDate && this.minDate) {
this.validateDataErrorText = 'Please enter a valid date between %s and %s';
} else if (this.maxDate) {
this.validateDataErrorText = 'Please enter a valid date less than or equal to %s';
} else if (this.minDate) {
this.validateDataErrorText = 'Please enter a valid date equal to or greater than %s';
} else {
this.validateDataErrorText = '';
}
}
return validate;
},
validateDataErrorText: 'Date should be between %s and %s',
errorTextModifier: function(text) {
if (this.minDate) {
text = text.sub('%s', this.dateFormat(this.minDate));
}
if (this.maxDate) {
text = text.sub('%s', this.dateFormat(this.maxDate));
}
return text;
},
dateFormat: function(date) {
return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
}
});
Varien.FileElement = Class.create();
Varien.FileElement.prototype = {
initialize: function (id) {
this.fileElement = $(id);
this.hiddenElement = $(id + '_value');
this.fileElement.observe('change', this.selectFile.bind(this));
},
selectFile: function(event) {
this.hiddenElement.value = this.fileElement.getValue();
}
};
Validation.addAllThese([
['validate-custom', ' ', function(v,elm) {
return elm.validate();
}]
]);
function truncateOptions() {
$$('.truncated').each(function(element){
Event.observe(element, 'mouseover', function(){
if (element.down('div.truncated_full_value')) {
element.down('div.truncated_full_value').addClassName('show')
}
});
Event.observe(element, 'mouseout', function(){
if (element.down('div.truncated_full_value')) {
element.down('div.truncated_full_value').removeClassName('show')
}
});
});
}
Event.observe(window, 'load', function(){
truncateOptions();
});
Element.addMethods({
getInnerText: function(element)
{
element = $(element);
if(element.innerText && !Prototype.Browser.Opera) {
return element.innerText
}
return element.innerHTML.stripScripts().unescapeHTML().replace(/[\n\r\s]+/g, ' ').strip();
}
});
/*
if (!("console" in window) || !("firebug" in console))
{
var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
"group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
window.console = {};
for (var i = 0; i < names.length; ++i)
window.console[names[i]] = function() {}
}
*/
/**
* Executes event handler on the element. Works with event handlers attached by Prototype,
* in a browser-agnostic fashion.
* @param element The element object
* @param event Event name, like 'change'
*
* @example fireEvent($('my-input', 'click'));
*/
function fireEvent(element, event) {
if (document.createEvent) {
// dispatch for all browsers except IE before version 9
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true ); // event type, bubbling, cancelable
return element.dispatchEvent(evt);
} else {
// dispatch for IE before version 9
var evt = document.createEventObject();
return element.fireEvent('on' + event, evt)
}
}
/**
* Returns more accurate results of floating-point modulo division
* E.g.:
* 0.6 % 0.2 = 0.19999999999999996
* modulo(0.6, 0.2) = 0
*
* @param dividend
* @param divisor
*/
function modulo(dividend, divisor)
{
var epsilon = divisor / 10000;
var remainder = dividend % divisor;
if (Math.abs(remainder - divisor) < epsilon || Math.abs(remainder) < epsilon) {
remainder = 0;
}
return remainder;
}
/**
* createContextualFragment is not supported in IE9. Adding its support.
*/
if ((typeof Range != "undefined") && !Range.prototype.createContextualFragment)
{
Range.prototype.createContextualFragment = function(html)
{
var frag = document.createDocumentFragment(),
div = document.createElement("div");
frag.appendChild(div);
div.outerHTML = html;
return frag;
};
}
/**
* Magento Enterprise Edition
*
* NOTICE OF LICENSE
*
* This source file is subject to the Magento Enterprise Edition End User License Agreement
* that is bundled with this package in the file LICENSE_EE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.magento.com/license/enterprise-edition
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Varien
* @package js
* @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
* @license http://www.magento.com/license/enterprise-edition
*/
VarienForm = Class.create();
VarienForm.prototype = {
initialize: function(formId, firstFieldFocus){
this.form = $(formId);
if (!this.form) {
return;
}
this.cache = $A();
this.currLoader = false;
this.currDataIndex = false;
this.validator = new Validation(this.form);
this.elementFocus = this.elementOnFocus.bindAsEventListener(this);
this.elementBlur = this.elementOnBlur.bindAsEventListener(this);
this.childLoader = this.onChangeChildLoad.bindAsEventListener(this);
this.highlightClass = 'highlight';
this.extraChildParams = '';
this.firstFieldFocus= firstFieldFocus || false;
this.bindElements();
if(this.firstFieldFocus){
try{
Form.Element.focus(Form.findFirstElement(this.form))
}
catch(e){}
}
},
submit : function(url){
if(this.validator && this.validator.validate()){
this.form.submit();
}
return false;
},
bindElements:function (){
var elements = Form.getElements(this.form);
for (var row in elements) {
if (elements[row].id) {
Event.observe(elements[row],'focus',this.elementFocus);
Event.observe(elements[row],'blur',this.elementBlur);
}
}
},
elementOnFocus: function(event){
var element = Event.findElement(event, 'fieldset');
if(element){
Element.addClassName(element, this.highlightClass);
}
},
elementOnBlur: function(event){
var element = Event.findElement(event, 'fieldset');
if(element){
Element.removeClassName(element, this.highlightClass);
}
},
setElementsRelation: function(parent, child, dataUrl, first){
if (parent=$(parent)) {
// TODO: array of relation and caching
if (!this.cache[parent.id]){
this.cache[parent.id] = $A();
this.cache[parent.id]['child'] = child;
this.cache[parent.id]['dataUrl'] = dataUrl;
this.cache[parent.id]['data'] = $A();
this.cache[parent.id]['first'] = first || false;
}
Event.observe(parent,'change',this.childLoader);
}
},
onChangeChildLoad: function(event){
element = Event.element(event);
this.elementChildLoad(element);
},
elementChildLoad: function(element, callback){
this.callback = callback || false;
if (element.value) {
this.currLoader = element.id;
this.currDataIndex = element.value;
if (this.cache[element.id]['data'][element.value]) {
this.setDataToChild(this.cache[element.id]['data'][element.value]);
}
else{
new Ajax.Request(this.cache[this.currLoader]['dataUrl'],{
method: 'post',
parameters: {"parent":element.value},
onComplete: this.reloadChildren.bind(this)
});
}
}
},
reloadChildren: function(transport){
var data = eval('(' + transport.responseText + ')');
this.cache[this.currLoader]['data'][this.currDataIndex] = data;
this.setDataToChild(data);
},
setDataToChild: function(data){
if (data.length) {
var child = $(this.cache[this.currLoader]['child']);
if (child){
var html = '<select name="'+child.name+'" id="'+child.id+'" class="'+child.className+'" title="'+child.title+'" '+this.extraChildParams+'>';
if(this.cache[this.currLoader]['first']){
html+= '<option value="">'+this.cache[this.currLoader]['first']+'</option>';
}
for (var i in data){
if(data[i].value) {
html+= '<option value="'+data[i].value+'"';
if(child.value && (child.value == data[i].value || child.value == data[i].label)){
html+= ' selected';
}
html+='>'+data[i].label+'</option>';
}
}
html+= '</select>';
Element.insert(child, {before: html});
Element.remove(child);
}
}
else{
var child = $(this.cache[this.currLoader]['child']);
if (child){
var html = '<input type="text" name="'+child.name+'" id="'+child.id+'" class="'+child.className+'" title="'+child.title+'" '+this.extraChildParams+'>';
Element.insert(child, {before: html});
Element.remove(child);
}
}
this.bindElements();
if (this.callback) {
this.callback();
}
}
}
RegionUpdater = Class.create();
RegionUpdater.prototype = {
initialize: function (countryEl, regionTextEl, regionSelectEl, regions, disableAction, zipEl)
{
this.countryEl = $(countryEl);
this.regionTextEl = $(regionTextEl);
this.regionSelectEl = $(regionSelectEl);
this.zipEl = $(zipEl);
this.config = regions['config'];
delete regions.config;
this.regions = regions;
this.disableAction = (typeof disableAction=='undefined') ? 'hide' : disableAction;
this.zipOptions = (typeof zipOptions=='undefined') ? false : zipOptions;
if (this.regionSelectEl.options.length<=1) {
this.update();
}
Event.observe(this.countryEl, 'change', this.update.bind(this));
},
_checkRegionRequired: function()
{
var label, wildCard;
var elements = [this.regionTextEl, this.regionSelectEl];
var that = this;
if (typeof this.config == 'undefined') {
return;
}
var regionRequired = this.config.regions_required.indexOf(this.countryEl.value) >= 0;
elements.each(function(currentElement) {
Validation.reset(currentElement);
label = $$('label[for="' + currentElement.id + '"]')[0];
if (label) {
wildCard = label.down('em') || label.down('span.required');
if (!that.config.show_all_regions) {
if (regionRequired) {
label.up().show();
} else {
label.up().hide();
}
}
}
if (label && wildCard) {
if (!regionRequired) {
wildCard.hide();
if (label.hasClassName('required')) {
label.removeClassName('required');
}
} else if (regionRequired) {
wildCard.show();
if (!label.hasClassName('required')) {
label.addClassName('required')
}
}
}
if (!regionRequired) {
if (currentElement.hasClassName('required-entry')) {
currentElement.removeClassName('required-entry');
}
if ('select' == currentElement.tagName.toLowerCase() &&
currentElement.hasClassName('validate-select')) {
currentElement.removeClassName('validate-select');
}
} else {
if (!currentElement.hasClassName('required-entry')) {
currentElement.addClassName('required-entry');
}
if ('select' == currentElement.tagName.toLowerCase() &&
!currentElement.hasClassName('validate-select')) {
currentElement.addClassName('validate-select');
}
}
});
},
update: function()
{
if (this.regions[this.countryEl.value]) {
var i, option, region, def;
def = this.regionSelectEl.getAttribute('defaultValue');
if (this.regionTextEl) {
if (!def) {
def = this.regionTextEl.value.toLowerCase();
}
this.regionTextEl.value = '';
}
this.regionSelectEl.options.length = 1;
for (regionId in this.regions[this.countryEl.value]) {
region = this.regions[this.countryEl.value][regionId];
option = document.createElement('OPTION');
option.value = regionId;
option.text = region.name.stripTags();
option.title = region.name;
if (this.regionSelectEl.options.add) {
this.regionSelectEl.options.add(option);
} else {
this.regionSelectEl.appendChild(option);
}
if (regionId == def || (region.name && region.name.toLowerCase() == def)
|| (region.name && region.code.toLowerCase() == def)
) {
this.regionSelectEl.value = regionId;
}
}
this.sortSelect();
if (this.disableAction == 'hide') {
if (this.regionTextEl) {
this.regionTextEl.style.display = 'none';
}
this.regionSelectEl.style.display = '';
} else if (this.disableAction == 'disable') {
if (this.regionTextEl) {
this.regionTextEl.disabled = true;
}
this.regionSelectEl.disabled = false;
}
this.setMarkDisplay(this.regionSelectEl, true);
} else {
this.regionSelectEl.options.length = 1;
this.sortSelect();
if (this.disableAction == 'hide') {
if (this.regionTextEl) {
this.regionTextEl.style.display = '';
}
this.regionSelectEl.style.display = 'none';
Validation.reset(this.regionSelectEl);
} else if (this.disableAction == 'disable') {
if (this.regionTextEl) {
this.regionTextEl.disabled = false;
}
this.regionSelectEl.disabled = true;
} else if (this.disableAction == 'nullify') {
this.regionSelectEl.options.length = 1;
this.regionSelectEl.value = '';
this.regionSelectEl.selectedIndex = 0;
this.lastCountryId = '';
}
this.setMarkDisplay(this.regionSelectEl, false);
}
this._checkRegionRequired();
// Make Zip and its label required/optional
var zipUpdater = new ZipUpdater(this.countryEl.value, this.zipEl);
zipUpdater.update();
},
setMarkDisplay: function(elem, display){
elem = $(elem);
var labelElement = elem.up(0).down('label > span.required') ||
elem.up(1).down('label > span.required') ||
elem.up(0).down('label.required > em') ||
elem.up(1).down('label.required > em');
if(labelElement) {
inputElement = labelElement.up().next('input');
if (display) {
labelElement.show();
if (inputElement) {
inputElement.addClassName('required-entry');
}
} else {
labelElement.hide();
if (inputElement) {
inputElement.removeClassName('required-entry');
}
}
}
},
sortSelect : function () {
var elem = this.regionSelectEl;
var tmpArray = new Array();
var currentVal = $(elem).value;
for (var i = 0; i < $(elem).options.length; i++) {
if (i == 0) {
continue;
}
tmpArray[i-1] = new Array();
tmpArray[i-1][0] = $(elem).options[i].text;
tmpArray[i-1][1] = $(elem).options[i].value;
}
tmpArray.sort();
for (var i = 1; i <= tmpArray.length; i++) {
var op = new Option(tmpArray[i-1][0], tmpArray[i-1][1]);
$(elem).options[i] = op;
}
$(elem).value = currentVal;
return;
}
}
ZipUpdater = Class.create();
ZipUpdater.prototype = {
initialize: function(country, zipElement)
{
this.country = country;
this.zipElement = $(zipElement);
},
update: function()
{
// Country ISO 2-letter codes must be pre-defined
if (typeof optionalZipCountries == 'undefined') {
return false;
}
// Ajax-request and normal content load compatibility
if (this.zipElement != undefined) {
Validation.reset(this.zipElement)
this._setPostcodeOptional();
} else {
Event.observe(window, "load", this._setPostcodeOptional.bind(this));
}
},
_setPostcodeOptional: function()
{
this.zipElement = $(this.zipElement);
if (this.zipElement == undefined) {
return false;
}
// find label
var label = $$('label[for="' + this.zipElement.id + '"]')[0];
if (label != undefined) {
var wildCard = label.down('em') || label.down('span.required');
}
// Make Zip and its label required/optional
if (optionalZipCountries.indexOf(this.country) != -1) {
while (this.zipElement.hasClassName('required-entry')) {
this.zipElement.removeClassName('required-entry');
}
if (wildCard != undefined) {
wildCard.hide();
}
} else {
this.zipElement.addClassName('required-entry');
if (wildCard != undefined) {
wildCard.show();
}
}
}
}
/**
* Magento Enterprise Edition
*
* NOTICE OF LICENSE
*
* This source file is subject to the Magento Enterprise Edition End User License Agreement
* that is bundled with this package in the file LICENSE_EE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.magento.com/license/enterprise-edition
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package js
* @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
* @license http://www.magento.com/license/enterprise-edition
*/
var Translate = Class.create();
Translate.prototype = {
initialize: function(data){
this.data = $H(data);
},
translate : function(){
var args = arguments;
var text = arguments[0];
if(this.data.get(text)){
return this.data.get(text);
}
return text;
},
add : function() {
if (arguments.length > 1) {
this.data.set(arguments[0], arguments[1]);
} else if (typeof arguments[0] =='object') {
$H(arguments[0]).each(function (pair){
this.data.set(pair.key, pair.value);
}.bind(this));
}
}
}
/**
* Magento Enterprise Edition
*
* NOTICE OF LICENSE
*
* This source file is subject to the Magento Enterprise Edition End User License Agreement
* that is bundled with this package in the file LICENSE_EE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.magento.com/license/enterprise-edition
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package js
* @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
* @license http://www.magento.com/license/enterprise-edition
*/
// old school cookie functions grabbed off the web
if (!window.Mage) var Mage = {};
Mage.Cookies = {};
Mage.Cookies.expires = null;
Mage.Cookies.path = '/';
Mage.Cookies.domain = null;
Mage.Cookies.secure = false;
Mage.Cookies.set = function(name, value){
var argv = arguments;
var argc = arguments.length;
var expires = (argc > 2) ? argv[2] : Mage.Cookies.expires;
var path = (argc > 3) ? argv[3] : Mage.Cookies.path;
var domain = (argc > 4) ? argv[4] : Mage.Cookies.domain;
var secure = (argc > 5) ? argv[5] : Mage.Cookies.secure;
document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
};
Mage.Cookies.get = function(name){
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
var j = 0;
while(i < clen){
j = i + alen;
if (document.cookie.substring(i, j) == arg)
return Mage.Cookies.getCookieVal(j);
i = document.cookie.indexOf(" ", i) + 1;
if(i == 0)
break;
}
return null;
};
Mage.Cookies.clear = function(name) {
if(Mage.Cookies.get(name)){
document.cookie = name + "=" +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
};
Mage.Cookies.getCookieVal = function(offset){
var endstr = document.cookie.indexOf(";", offset);
if(endstr == -1){
endstr = document.cookie.length;
}
return unescape(document.cookie.substring(offset, endstr));
};
//flag - we already updated Product.Config
var extendProductConfigformatPriceTrigged = false;
//calling this function will update Product.Config to our formatPrice
function extendProductConfigformatPrice() {
if (typeof(Product) != "undefined") {
if (!extendProductConfigformatPriceTrigged) {
extendProductConfigformatPriceTrigged = true;
Product.Config.prototype = Object.extend(Product.Config.prototype, {
formatPrice:function (price, showSign) {
var str = '';
price = parseFloat(price);
if (showSign) {
if (price < 0) {
str += '-';
price = -price;
}
else {
str += '+';
}
}
var roundedPrice = (Math.round(price * 100) / 100).toString();
if (this.prices && this.prices[roundedPrice]) {
str += this.prices[roundedPrice];
} else {
precision = 2;
if (typeof(etCurrencyManagerJsConfig) != "undefined") {
if (typeof(etCurrencyManagerJsConfig.precision) != "undefined") {
precision = etCurrencyManagerJsConfig.precision;
}
}
if (typeof(optionsPrice) != "undefined") {
if (typeof(optionsPrice.priceFormat) != "undefined") {
precision = optionsPrice.priceFormat.requiredPrecision;
}
}
if (typeof(etCurrencyManagerJsConfig) != "undefined") {
if (typeof(etCurrencyManagerJsConfig.cutzerodecimal) != "undefined") {
if (etCurrencyManagerJsConfig.cutzerodecimal != 0) {
if (price - Math.round(price) == 0) {
precision = 0;
}
}
}
}
if (typeof(etCurrencyManagerJsConfig) != "undefined") {
if (typeof(etCurrencyManagerJsConfig.min_decimal_count) != "undefined") {
if (etCurrencyManagerJsConfig.min_decimal_count < precision) {
for (var testPrecision = etCurrencyManagerJsConfig.min_decimal_count;
testPrecision < precision; testPrecision++) {
//abs for 0.00199999999 or 1.1000000000001 fix
if (Math.abs(Math.round(price * Math.pow(10, testPrecision))
- price * Math.pow(10, testPrecision)) < 0.0000001) {
precision = testPrecision;
break;
}
}
}
}
}
if (precision > 0) {
str += this.priceTemplate.evaluate({price:price.toFixed(precision)});
}
else {
price = price.toFixed(0);
if (typeof(etCurrencyManagerJsConfig) != "undefined") {
if (typeof(etCurrencyManagerJsConfig.cutzerodecimal) != "undefined") {
if (etCurrencyManagerJsConfig.cutzerodecimal != 0) {
if (typeof(etCurrencyManagerJsConfig.cutzerodecimal_suffix) != "undefined") {
if (etCurrencyManagerJsConfig.cutzerodecimal_suffix.length > 0) {
price = price + "" + etCurrencyManagerJsConfig.cutzerodecimal_suffix;
}
}
}
}
}
str += this.priceTemplate.evaluate({price:price});
}
}
return str;
}
});
if (etCurrencyManagerJsConfig.cutzerodecimal > 0) {
Product.OptionsPrice.prototype = Object.extend(Product.OptionsPrice.prototype, {formatPrice:function (price) {
var tmpPriceFormat = Object.clone(this.priceFormat);
if (price - parseInt(price) == 0) {
tmpPriceFormat.precision = 0;
tmpPriceFormat.requiredPrecision = 0;
}
if (tmpPriceFormat.precision < 0) {
tmpPriceFormat.precision = 0;
}
if (tmpPriceFormat.requiredPrecision < 0) {
tmpPriceFormat.requiredPrecision = 0;
}
var price2return = formatCurrency(price, tmpPriceFormat);
return price2return;
}});
}
}
}
}
try {
extendProductConfigformatPrice();
} catch (e) {
extendProductConfigformatPriceTrigged = false;
}
try {
originalFormatCurrency = window.formatCurrency;
window.formatCurrency = function (price, originalFormat, showPlus) {
var format = Object.clone(originalFormat);
//zeroSymbol
//JS round fix
price = Math.round(price * Math.pow(10, format.precision)) / Math.pow(10, format.precision);
if (price - Math.round(price) != 0) {
if (Math.abs(price - Math.round(price)) < 0.00000001) {
price = 0;
}
}
if (typeof(etCurrencyManagerJsConfig) != "undefined") {
if (price == 0) {
if (typeof(etCurrencyManagerJsConfig.zerotext) != "undefined") {
return etCurrencyManagerJsConfig.zerotext;
}
}
}
//cut zero decimal
if (price - Math.round(price) == 0) {
if (typeof(etCurrencyManagerJsConfig) != "undefined") {
if (typeof(etCurrencyManagerJsConfig.cutzerodecimal) != "undefined") {
if (etCurrencyManagerJsConfig.cutzerodecimal != 0) {
format.precision = 0;
format.requiredPrecision = 0;
var for_replace = originalFormatCurrency(price, format, showPlus);
format.pattern = "%s";
var replaced_part = originalFormatCurrency(price, format, showPlus);
format.pattern = originalFormat.pattern;
if (typeof(etCurrencyManagerJsConfig.cutzerodecimal_suffix) != "undefined") {
if (etCurrencyManagerJsConfig.cutzerodecimal_suffix.length > 0) {
return for_replace.replace(replaced_part, replaced_part + ""
+ etCurrencyManagerJsConfig.cutzerodecimal_suffix);
}
}
}
}
}
}
if (typeof(etCurrencyManagerJsConfig) != "undefined") {
if (typeof(etCurrencyManagerJsConfig.min_decimal_count) != "undefined") {
etCurrencyManagerJsConfig.min_decimal_count = parseInt(etCurrencyManagerJsConfig.min_decimal_count);
if (etCurrencyManagerJsConfig.min_decimal_count < format.precision) {
for (var testPrecision = etCurrencyManagerJsConfig.min_decimal_count;
testPrecision < format.precision; testPrecision++) {
//abs for 0.00199999999 or 1.1000000000001 fix
if (Math.abs(Math.round(price * Math.pow(10, testPrecision))
- price * Math.pow(10, testPrecision)) < 0.0000001) {
format.precision = testPrecision;
format.requiredPrecision = testPrecision;
break;
}
}
}
}
}
return formatCurrencyET(price, format, showPlus);
//if(format.precision<0)format.precision=0;
//if(format.requiredPrecision<0)format.requiredPrecision=0;
/*return originalFormatCurrency(price, format, showPlus);*/
};
function formatCurrencyET(price, format, showPlus) {
var precision = isNaN(format.precision = (format.precision)) ? 2 : format.precision;
var requiredPrecision = isNaN(format.requiredPrecision = (format.requiredPrecision)) ? 2 : format.requiredPrecision;
//precision = (precision > requiredPrecision) ? precision : requiredPrecision;
//for now we don't need this difference so precision is requiredPrecision
precision = requiredPrecision;
var integerRequired = isNaN(format.integerRequired = Math.abs(format.integerRequired)) ? 1 : format.integerRequired;
var decimalSymbol = format.decimalSymbol == undefined ? "," : format.decimalSymbol;
var groupSymbol = format.groupSymbol == undefined ? "." : format.groupSymbol;
var groupLength = format.groupLength == undefined ? 3 : format.groupLength;
var s = '';
if (showPlus == undefined || showPlus == true) {
s = price < 0 ? "-" : ( showPlus ? "+" : "");
} else if (showPlus == false) {
s = '';
}
/**
* replace(/-/, 0) is only for fixing Safari, Chrome, IE bug which appears
* when Math.abs(0).toFixed() executed on "0" number.
* Result is "0.-0" :(
*/
if (precision < 0) {
precision = 0;
}
var i = parseInt(price = Math.abs(+price || 0).toFixed(precision)) + "";
var pad = (i.length < integerRequired) ? (integerRequired - i.length) : 0;
while (pad) {
i = '0' + i;
pad--;
}
j = (j = i.length) > groupLength ? j % groupLength : 0;
re = new RegExp("(\\d{" + groupLength + "})(?=\\d)", "g");
var r = (j ? i.substr(0, j) + groupSymbol : "") + i.substr(j).replace(re, "$1" + groupSymbol) + (precision ? decimalSymbol + Math.abs(price - i).toFixed(precision).replace(/-/, 0).slice(2) : "")
var pattern = '';
if (format.pattern.indexOf('{sign}') == -1) {
pattern = s + format.pattern;
} else {
pattern = format.pattern.replace('{sign}', s);
}
return pattern.replace('%s', r).replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
}
catch (e) {
//do nothing
}
/*! jQuery v2.2.4 | (c) jQuery Foundation | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=a.document,e=c.slice,f=c.concat,g=c.push,h=c.indexOf,i={},j=i.toString,k=i.hasOwnProperty,l={},m="2.2.4",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return e.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:e.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a){return n.each(this,a)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(e.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:g,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){var b=a&&a.toString();return!n.isArray(a)&&b-parseFloat(b)+1>=0},isPlainObject:function(a){var b;if("object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;if(a.constructor&&!k.call(a,"constructor")&&!k.call(a.constructor.prototype||{},"isPrototypeOf"))return!1;for(b in a);return void 0===b||k.call(a,b)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?i[j.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=n.trim(a),a&&(1===a.indexOf("use strict")?(b=d.createElement("script"),b.text=a,d.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b){var c,d=0;if(s(a)){for(c=a.length;c>d;d++)if(b.call(a[d],d,a[d])===!1)break}else for(d in a)if(b.call(a[d],d,a[d])===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):g.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:h.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,g=0,h=[];if(s(a))for(d=a.length;d>g;g++)e=b(a[g],g,c),null!=e&&h.push(e);else for(g in a)e=b(a[g],g,c),null!=e&&h.push(e);return f.apply([],h)},guid:1,proxy:function(a,b){var c,d,f;return"string"==typeof b&&(c=a[b],b=a,a=c),n.isFunction(a)?(d=e.call(arguments,2),f=function(){return a.apply(b||this,d.concat(e.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:l}),"function"==typeof Symbol&&(n.fn[Symbol.iterator]=c[Symbol.iterator]),n.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){i["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=!!a&&"length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ga(),z=ga(),A=ga(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+M+"))|)"+L+"*\\]",O=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+N+")*)|.*)\\)|)",P=new RegExp(L+"+","g"),Q=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),R=new RegExp("^"+L+"*,"+L+"*"),S=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),T=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),U=new RegExp(O),V=new RegExp("^"+M+"$"),W={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M+"|[*])"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},X=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,$=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,_=/[+~]/,aa=/'|\\/g,ba=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),ca=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},da=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(ea){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fa(a,b,d,e){var f,h,j,k,l,o,r,s,w=b&&b.ownerDocument,x=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==x&&9!==x&&11!==x)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==x&&(o=$.exec(a)))if(f=o[1]){if(9===x){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(w&&(j=w.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(o[2])return H.apply(d,b.getElementsByTagName(a)),d;if((f=o[3])&&c.getElementsByClassName&&b.getElementsByClassName)return H.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==x)w=b,s=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(aa,"\\$&"):b.setAttribute("id",k=u),r=g(a),h=r.length,l=V.test(k)?"#"+k:"[id='"+k+"']";while(h--)r[h]=l+" "+qa(r[h]);s=r.join(","),w=_.test(a)&&oa(b.parentNode)||b}if(s)try{return H.apply(d,w.querySelectorAll(s)),d}catch(y){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(Q,"$1"),b,d,e)}function ga(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ha(a){return a[u]=!0,a}function ia(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ja(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function ka(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function la(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function na(a){return ha(function(b){return b=+b,ha(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function oa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=fa.support={},f=fa.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fa.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ia(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ia(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Z.test(n.getElementsByClassName),c.getById=ia(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return"undefined"!=typeof b.getElementsByClassName&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=Z.test(n.querySelectorAll))&&(ia(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\r\\' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ia(function(a){var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Z.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ia(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",O)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Z.test(o.compareDocumentPosition),t=b||Z.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return ka(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?ka(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},fa.matches=function(a,b){return fa(a,null,null,b)},fa.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(T,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fa(b,n,null,[a]).length>0},fa.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fa.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fa.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fa.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fa.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fa.selectors={cacheLength:50,createPseudo:ha,match:W,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ba,ca),a[3]=(a[3]||a[4]||a[5]||"").replace(ba,ca),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fa.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fa.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return W.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&U.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ba,ca).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fa.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(P," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fa.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ha(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ha(function(a){var b=[],c=[],d=h(a.replace(Q,"$1"));return d[u]?ha(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ha(function(a){return function(b){return fa(a,b).length>0}}),contains:ha(function(a){return a=a.replace(ba,ca),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ha(function(a){return V.test(a||"")||fa.error("unsupported lang: "+a),a=a.replace(ba,ca).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Y.test(a.nodeName)},input:function(a){return X.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:na(function(){return[0]}),last:na(function(a,b){return[b-1]}),eq:na(function(a,b,c){return[0>c?c+b:c]}),even:na(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:na(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:na(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:na(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=la(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=ma(b);function pa(){}pa.prototype=d.filters=d.pseudos,d.setFilters=new pa,g=fa.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){c&&!(e=R.exec(h))||(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=S.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(Q," ")}),h=h.slice(c.length));for(g in d.filter)!(e=W[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fa.error(a):z(a,i).slice(0)};function qa(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function ra(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j,k=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(j=b[u]||(b[u]={}),i=j[b.uniqueID]||(j[b.uniqueID]={}),(h=i[d])&&h[0]===w&&h[1]===f)return k[2]=h[2];if(i[d]=k,k[2]=a(b,c,g))return!0}}}function sa(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ta(a,b,c){for(var d=0,e=b.length;e>d;d++)fa(a,b[d],c);return c}function ua(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(c&&!c(f,d,e)||(g.push(f),j&&b.push(h)));return g}function va(a,b,c,d,e,f){return d&&!d[u]&&(d=va(d)),e&&!e[u]&&(e=va(e,f)),ha(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ta(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ua(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ua(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ua(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function wa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ra(function(a){return a===b},h,!0),l=ra(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[ra(sa(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return va(i>1&&sa(m),i>1&&qa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(Q,"$1"),c,e>i&&wa(a.slice(i,e)),f>e&&wa(a=a.slice(e)),f>e&&qa(a))}m.push(c)}return sa(m)}function xa(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=F.call(i));u=ua(u)}H.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&fa.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ha(f):f}return h=fa.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xa(e,d)),f.selector=a}return f},i=fa.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ba,ca),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=W.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ba,ca),_.test(j[0].type)&&oa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qa(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,!b||_.test(a)&&oa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ia(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ia(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ja("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ia(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ja("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ia(function(a){return null==a.getAttribute("disabled")})||ja(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fa}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.uniqueSort=n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},v=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},w=n.expr.match.needsContext,x=/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/,y=/^.[^:#\[\.,]*$/;function z(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(y.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return h.call(b,a)>-1!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0}));for(b=0;c>b;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(z(this,a||[],!1))},not:function(a){return this.pushStack(z(this,a||[],!0))},is:function(a){return!!z(this,"string"==typeof a&&w.test(a)?n(a):a||[],!1).length}});var A,B=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=n.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||A,"string"==typeof a){if(e="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:B.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),x.test(e[1])&&n.isPlainObject(b))for(e in b)n.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}return f=d.getElementById(e[2]),f&&f.parentNode&&(this.length=1,this[0]=f),this.context=d,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?void 0!==c.ready?c.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};C.prototype=n.fn,A=n(d);var D=/^(?:parents|prev(?:Until|All))/,E={children:!0,contents:!0,next:!0,prev:!0};n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=w.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?h.call(n(a),this[0]):h.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.uniqueSort(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function F(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return u(a,"parentNode")},parentsUntil:function(a,b,c){return u(a,"parentNode",c)},next:function(a){return F(a,"nextSibling")},prev:function(a){return F(a,"previousSibling")},nextAll:function(a){return u(a,"nextSibling")},prevAll:function(a){return u(a,"previousSibling")},nextUntil:function(a,b,c){return u(a,"nextSibling",c)},prevUntil:function(a,b,c){return u(a,"previousSibling",c)},siblings:function(a){return v((a.parentNode||{}).firstChild,a)},children:function(a){return v(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(E[a]||n.uniqueSort(e),D.test(a)&&e.reverse()),this.pushStack(e)}});var G=/\S+/g;function H(a){var b={};return n.each(a.match(G)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?H(a):n.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h<f.length)f[h].apply(c[0],c[1])===!1&&a.stopOnFalse&&(h=f.length,c=!1)}a.memory||(c=!1),b=!1,e&&(f=c?[]:"")},j={add:function(){return f&&(c&&!b&&(h=f.length-1,g.push(c)),function d(b){n.each(b,function(b,c){n.isFunction(c)?a.unique&&j.has(c)||f.push(c):c&&c.length&&"string"!==n.type(c)&&d(c)})}(arguments),c&&!b&&i()),this},remove:function(){return n.each(arguments,function(a,b){var c;while((c=n.inArray(b,f,c))>-1)f.splice(c,1),h>=c&&h--}),this},has:function(a){return a?n.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=g=[],c||(f=c=""),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().progress(c.notify).done(c.resolve).fail(c.reject):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=e.call(arguments),d=c.length,f=1!==d||a&&n.isFunction(a.promise)?d:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?e.call(arguments):d,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(d>1)for(i=new Array(d),j=new Array(d),k=new Array(d);d>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().progress(h(b,j,i)).done(h(b,k,c)).fail(g.reject):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(d,[n]),n.fn.triggerHandler&&(n(d).triggerHandler("ready"),n(d).off("ready"))))}});function J(){d.removeEventListener("DOMContentLoaded",J),a.removeEventListener("load",J),n.ready()}n.ready.promise=function(b){return I||(I=n.Deferred(),"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll?a.setTimeout(n.ready):(d.addEventListener("DOMContentLoaded",J),a.addEventListener("load",J))),I.promise(b)},n.ready.promise();var K=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)K(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},L=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function M(){this.expando=n.expando+M.uid++}M.uid=1,M.prototype={register:function(a,b){var c=b||{};return a.nodeType?a[this.expando]=c:Object.defineProperty(a,this.expando,{value:c,writable:!0,configurable:!0}),a[this.expando]},cache:function(a){if(!L(a))return{};var b=a[this.expando];return b||(b={},L(a)&&(a.nodeType?a[this.expando]=b:Object.defineProperty(a,this.expando,{value:b,configurable:!0}))),b},set:function(a,b,c){var d,e=this.cache(a);if("string"==typeof b)e[b]=c;else for(d in b)e[d]=b[d];return e},get:function(a,b){return void 0===b?this.cache(a):a[this.expando]&&a[this.expando][b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=a[this.expando];if(void 0!==f){if(void 0===b)this.register(a);else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in f?d=[b,e]:(d=e,d=d in f?[d]:d.match(G)||[])),c=d.length;while(c--)delete f[d[c]]}(void 0===b||n.isEmptyObject(f))&&(a.nodeType?a[this.expando]=void 0:delete a[this.expando])}},hasData:function(a){var b=a[this.expando];return void 0!==b&&!n.isEmptyObject(b)}};var N=new M,O=new M,P=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Q=/[A-Z]/g;function R(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(Q,"-$&").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:P.test(c)?n.parseJSON(c):c;
}catch(e){}O.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return O.hasData(a)||N.hasData(a)},data:function(a,b,c){return O.access(a,b,c)},removeData:function(a,b){O.remove(a,b)},_data:function(a,b,c){return N.access(a,b,c)},_removeData:function(a,b){N.remove(a,b)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=O.get(f),1===f.nodeType&&!N.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),R(f,d,e[d])));N.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){O.set(this,a)}):K(this,function(b){var c,d;if(f&&void 0===b){if(c=O.get(f,a)||O.get(f,a.replace(Q,"-$&").toLowerCase()),void 0!==c)return c;if(d=n.camelCase(a),c=O.get(f,d),void 0!==c)return c;if(c=R(f,d,void 0),void 0!==c)return c}else d=n.camelCase(a),this.each(function(){var c=O.get(this,d);O.set(this,d,b),a.indexOf("-")>-1&&void 0!==c&&O.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){O.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=N.get(a,b),c&&(!d||n.isArray(c)?d=N.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return N.get(a,c)||N.access(a,c,{empty:n.Callbacks("once memory").add(function(){N.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=N.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)};function W(a,b,c,d){var e,f=1,g=20,h=d?function(){return d.cur()}:function(){return n.css(a,b,"")},i=h(),j=c&&c[3]||(n.cssNumber[b]?"":"px"),k=(n.cssNumber[b]||"px"!==j&&+i)&&T.exec(n.css(a,b));if(k&&k[3]!==j){j=j||k[3],c=c||[],k=+i||1;do f=f||".5",k/=f,n.style(a,b,k+j);while(f!==(f=h()/i)&&1!==f&&--g)}return c&&(k=+k||+i||0,e=c[1]?k+(c[1]+1)*c[2]:+c[2],d&&(d.unit=j,d.start=k,d.end=e)),e}var X=/^(?:checkbox|radio)$/i,Y=/<([\w:-]+)/,Z=/^$|\/(?:java|ecma)script/i,$={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};$.optgroup=$.option,$.tbody=$.tfoot=$.colgroup=$.caption=$.thead,$.th=$.td;function _(a,b){var c="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function aa(a,b){for(var c=0,d=a.length;d>c;c++)N.set(a[c],"globalEval",!b||N.get(b[c],"globalEval"))}var ba=/<|&#?\w+;/;function ca(a,b,c,d,e){for(var f,g,h,i,j,k,l=b.createDocumentFragment(),m=[],o=0,p=a.length;p>o;o++)if(f=a[o],f||0===f)if("object"===n.type(f))n.merge(m,f.nodeType?[f]:f);else if(ba.test(f)){g=g||l.appendChild(b.createElement("div")),h=(Y.exec(f)||["",""])[1].toLowerCase(),i=$[h]||$._default,g.innerHTML=i[1]+n.htmlPrefilter(f)+i[2],k=i[0];while(k--)g=g.lastChild;n.merge(m,g.childNodes),g=l.firstChild,g.textContent=""}else m.push(b.createTextNode(f));l.textContent="",o=0;while(f=m[o++])if(d&&n.inArray(f,d)>-1)e&&e.push(f);else if(j=n.contains(f.ownerDocument,f),g=_(l.appendChild(f),"script"),j&&aa(g),c){k=0;while(f=g[k++])Z.test(f.type||"")&&c.push(f)}return l}!function(){var a=d.createDocumentFragment(),b=a.appendChild(d.createElement("div")),c=d.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var da=/^key/,ea=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,fa=/^([^.]*)(?:\.(.+)|)/;function ga(){return!0}function ha(){return!1}function ia(){try{return d.activeElement}catch(a){}}function ja(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)ja(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=ha;else if(!e)return a;return 1===f&&(g=e,e=function(a){return n().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=n.guid++)),a.each(function(){n.event.add(this,b,e,d,c)})}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=N.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return"undefined"!=typeof n&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(G)||[""],j=b.length;while(j--)h=fa.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=N.hasData(a)&&N.get(a);if(r&&(i=r.events)){b=(b||"").match(G)||[""],j=b.length;while(j--)if(h=fa.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&N.remove(a,"handle events")}},dispatch:function(a){a=n.event.fix(a);var b,c,d,f,g,h=[],i=e.call(arguments),j=(N.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())a.rnamespace&&!a.rnamespace.test(g.namespace)||(a.handleObj=g,a.data=g.data,d=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==d&&(a.result=d)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&("click"!==a.type||isNaN(a.button)||a.button<1))for(;i!==this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>-1:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},props:"altKey bubbles cancelable ctrlKey currentTarget detail eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,e,f,g=b.button;return null==a.pageX&&null!=b.clientX&&(c=a.target.ownerDocument||d,e=c.documentElement,f=c.body,a.pageX=b.clientX+(e&&e.scrollLeft||f&&f.scrollLeft||0)-(e&&e.clientLeft||f&&f.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||f&&f.scrollTop||0)-(e&&e.clientTop||f&&f.clientTop||0)),a.which||void 0===g||(a.which=1&g?1:2&g?3:4&g?2:0),a}},fix:function(a){if(a[n.expando])return a;var b,c,e,f=a.type,g=a,h=this.fixHooks[f];h||(this.fixHooks[f]=h=ea.test(f)?this.mouseHooks:da.test(f)?this.keyHooks:{}),e=h.props?this.props.concat(h.props):this.props,a=new n.Event(g),b=e.length;while(b--)c=e[b],a[c]=g[c];return a.target||(a.target=d),3===a.target.nodeType&&(a.target=a.target.parentNode),h.filter?h.filter(a,g):a},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==ia()&&this.focus?(this.focus(),!1):void 0},delegateType:"focusin"},blur:{trigger:function(){return this===ia()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&n.nodeName(this,"input")?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}}},n.removeEvent=function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c)},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ga:ha):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={constructor:n.Event,isDefaultPrevented:ha,isPropagationStopped:ha,isImmediatePropagationStopped:ha,isSimulated:!1,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ga,a&&!this.isSimulated&&a.preventDefault()},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ga,a&&!this.isSimulated&&a.stopPropagation()},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ga,a&&!this.isSimulated&&a.stopImmediatePropagation(),this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return e&&(e===d||n.contains(d,e))||(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),n.fn.extend({on:function(a,b,c,d){return ja(this,a,b,c,d)},one:function(a,b,c,d){return ja(this,a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return b!==!1&&"function"!=typeof b||(c=b,b=void 0),c===!1&&(c=ha),this.each(function(){n.event.remove(this,a,c,b)})}});var ka=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,la=/<script|<style|<link/i,ma=/checked\s*(?:[^=]|=\s*.checked.)/i,na=/^true\/(.*)/,oa=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;function pa(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function qa(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function ra(a){var b=na.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function sa(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(N.hasData(a)&&(f=N.access(a),g=N.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}O.hasData(a)&&(h=O.access(a),i=n.extend({},h),O.set(b,i))}}function ta(a,b){var c=b.nodeName.toLowerCase();"input"===c&&X.test(a.type)?b.checked=a.checked:"input"!==c&&"textarea"!==c||(b.defaultValue=a.defaultValue)}function ua(a,b,c,d){b=f.apply([],b);var e,g,h,i,j,k,m=0,o=a.length,p=o-1,q=b[0],r=n.isFunction(q);if(r||o>1&&"string"==typeof q&&!l.checkClone&&ma.test(q))return a.each(function(e){var f=a.eq(e);r&&(b[0]=q.call(this,e,f.html())),ua(f,b,c,d)});if(o&&(e=ca(b,a[0].ownerDocument,!1,a,d),g=e.firstChild,1===e.childNodes.length&&(e=g),g||d)){for(h=n.map(_(e,"script"),qa),i=h.length;o>m;m++)j=e,m!==p&&(j=n.clone(j,!0,!0),i&&n.merge(h,_(j,"script"))),c.call(a[m],j,m);if(i)for(k=h[h.length-1].ownerDocument,n.map(h,ra),m=0;i>m;m++)j=h[m],Z.test(j.type||"")&&!N.access(j,"globalEval")&&n.contains(k,j)&&(j.src?n._evalUrl&&n._evalUrl(j.src):n.globalEval(j.textContent.replace(oa,"")))}return a}function va(a,b,c){for(var d,e=b?n.filter(b,a):a,f=0;null!=(d=e[f]);f++)c||1!==d.nodeType||n.cleanData(_(d)),d.parentNode&&(c&&n.contains(d.ownerDocument,d)&&aa(_(d,"script")),d.parentNode.removeChild(d));return a}n.extend({htmlPrefilter:function(a){return a.replace(ka,"<$1></$2>")},clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=_(h),f=_(a),d=0,e=f.length;e>d;d++)ta(f[d],g[d]);if(b)if(c)for(f=f||_(a),g=g||_(h),d=0,e=f.length;e>d;d++)sa(f[d],g[d]);else sa(a,h);return g=_(h,"script"),g.length>0&&aa(g,!i&&_(a,"script")),h},cleanData:function(a){for(var b,c,d,e=n.event.special,f=0;void 0!==(c=a[f]);f++)if(L(c)){if(b=c[N.expando]){if(b.events)for(d in b.events)e[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);c[N.expando]=void 0}c[O.expando]&&(c[O.expando]=void 0)}}}),n.fn.extend({domManip:ua,detach:function(a){return va(this,a,!0)},remove:function(a){return va(this,a)},text:function(a){return K(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=a)})},null,a,arguments.length)},append:function(){return ua(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=pa(this,a);b.appendChild(a)}})},prepend:function(){return ua(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=pa(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return ua(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return ua(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(_(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return K(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!la.test(a)&&!$[(Y.exec(a)||["",""])[1].toLowerCase()]){a=n.htmlPrefilter(a);try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(_(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=[];return ua(this,arguments,function(b){var c=this.parentNode;n.inArray(this,a)<0&&(n.cleanData(_(this)),c&&c.replaceChild(b,this))},a)}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),f=e.length-1,h=0;f>=h;h++)c=h===f?this:this.clone(!0),n(e[h])[b](c),g.apply(d,c.get());return this.pushStack(d)}});var wa,xa={HTML:"block",BODY:"block"};function ya(a,b){var c=n(b.createElement(a)).appendTo(b.body),d=n.css(c[0],"display");return c.detach(),d}function za(a){var b=d,c=xa[a];return c||(c=ya(a,b),"none"!==c&&c||(wa=(wa||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=wa[0].contentDocument,b.write(),b.close(),c=ya(a,b),wa.detach()),xa[a]=c),c}var Aa=/^margin/,Ba=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ca=function(b){var c=b.ownerDocument.defaultView;return c&&c.opener||(c=a),c.getComputedStyle(b)},Da=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e},Ea=d.documentElement;!function(){var b,c,e,f,g=d.createElement("div"),h=d.createElement("div");if(h.style){h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,g.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",g.appendChild(h);function i(){h.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",h.innerHTML="",Ea.appendChild(g);var d=a.getComputedStyle(h);b="1%"!==d.top,f="2px"===d.marginLeft,c="4px"===d.width,h.style.marginRight="50%",e="4px"===d.marginRight,Ea.removeChild(g)}n.extend(l,{pixelPosition:function(){return i(),b},boxSizingReliable:function(){return null==c&&i(),c},pixelMarginRight:function(){return null==c&&i(),e},reliableMarginLeft:function(){return null==c&&i(),f},reliableMarginRight:function(){var b,c=h.appendChild(d.createElement("div"));return c.style.cssText=h.style.cssText="-webkit-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",c.style.marginRight=c.style.width="0",h.style.width="1px",Ea.appendChild(g),b=!parseFloat(a.getComputedStyle(c).marginRight),Ea.removeChild(g),h.removeChild(c),b}})}}();function Fa(a,b,c){var d,e,f,g,h=a.style;return c=c||Ca(a),g=c?c.getPropertyValue(b)||c[b]:void 0,""!==g&&void 0!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),c&&!l.pixelMarginRight()&&Ba.test(g)&&Aa.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f),void 0!==g?g+"":g}function Ga(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}var Ha=/^(none|table(?!-c[ea]).+)/,Ia={position:"absolute",visibility:"hidden",display:"block"},Ja={letterSpacing:"0",fontWeight:"400"},Ka=["Webkit","O","Moz","ms"],La=d.createElement("div").style;function Ma(a){if(a in La)return a;var b=a[0].toUpperCase()+a.slice(1),c=Ka.length;while(c--)if(a=Ka[c]+b,a in La)return a}function Na(a,b,c){var d=T.exec(b);return d?Math.max(0,d[2]-(c||0))+(d[3]||"px"):b}function Oa(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Pa(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ca(a),g="border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Fa(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ba.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Oa(a,b,c||(g?"border":"content"),d,f)+"px"}function Qa(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=N.get(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=N.access(d,"olddisplay",za(d.nodeName)))):(e=V(d),"none"===c&&e||N.set(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Fa(a,"opacity");return""===c?"1":c}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;return b=n.cssProps[h]||(n.cssProps[h]=Ma(h)||h),g=n.cssHooks[b]||n.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b]:(f=typeof c,"string"===f&&(e=T.exec(c))&&e[1]&&(c=W(a,b,e),f="number"),null!=c&&c===c&&("number"===f&&(c+=e&&e[3]||(n.cssNumber[h]?"":"px")),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),g&&"set"in g&&void 0===(c=g.set(a,c,d))||(i[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Ma(h)||h),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=Fa(a,b,d)),"normal"===e&&b in Ja&&(e=Ja[b]),""===c||c?(f=parseFloat(e),c===!0||isFinite(f)?f||0:e):e}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?Ha.test(n.css(a,"display"))&&0===a.offsetWidth?Da(a,Ia,function(){return Pa(a,b,d)}):Pa(a,b,d):void 0},set:function(a,c,d){var e,f=d&&Ca(a),g=d&&Oa(a,b,d,"border-box"===n.css(a,"boxSizing",!1,f),f);return g&&(e=T.exec(c))&&"px"!==(e[3]||"px")&&(a.style[b]=c,c=n.css(a,b)),Na(a,c,g)}}}),n.cssHooks.marginLeft=Ga(l.reliableMarginLeft,function(a,b){return b?(parseFloat(Fa(a,"marginLeft"))||a.getBoundingClientRect().left-Da(a,{marginLeft:0},function(){return a.getBoundingClientRect().left}))+"px":void 0}),n.cssHooks.marginRight=Ga(l.reliableMarginRight,function(a,b){return b?Da(a,{display:"inline-block"},Fa,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Aa.test(a)||(n.cssHooks[a+b].set=Na)}),n.fn.extend({css:function(a,b){return K(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Ca(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)},a,b,arguments.length>1)},show:function(){return Qa(this,!0)},hide:function(){return Qa(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function Ra(a,b,c,d,e){return new Ra.prototype.init(a,b,c,d,e)}n.Tween=Ra,Ra.prototype={constructor:Ra,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||n.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=Ra.propHooks[this.prop];return a&&a.get?a.get(this):Ra.propHooks._default.get(this)},run:function(a){var b,c=Ra.propHooks[this.prop];return this.options.duration?this.pos=b=n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Ra.propHooks._default.set(this),this}},Ra.prototype.init.prototype=Ra.prototype,Ra.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[n.cssProps[a.prop]]&&!n.cssHooks[a.prop]?a.elem[a.prop]=a.now:n.style(a.elem,a.prop,a.now+a.unit)}}},Ra.propHooks.scrollTop=Ra.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},n.fx=Ra.prototype.init,n.fx.step={};var Sa,Ta,Ua=/^(?:toggle|show|hide)$/,Va=/queueHooks$/;function Wa(){return a.setTimeout(function(){Sa=void 0}),Sa=n.now()}function Xa(a,b){var c,d=0,e={height:a};for(b=b?1:0;4>d;d+=2-b)c=U[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function Ya(a,b,c){for(var d,e=(_a.tweeners[b]||[]).concat(_a.tweeners["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function Za(a,b,c){var d,e,f,g,h,i,j,k,l=this,m={},o=a.style,p=a.nodeType&&V(a),q=N.get(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,l.always(function(){l.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=n.css(a,"display"),k="none"===j?N.get(a,"olddisplay")||za(a.nodeName):j,"inline"===k&&"none"===n.css(a,"float")&&(o.display="inline-block")),c.overflow&&(o.overflow="hidden",l.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],Ua.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}m[d]=q&&q[d]||n.style(a,d)}else j=void 0;if(n.isEmptyObject(m))"inline"===("none"===j?za(a.nodeName):j)&&(o.display=j);else{q?"hidden"in q&&(p=q.hidden):q=N.access(a,"fxshow",{}),f&&(q.hidden=!p),p?n(a).show():l.done(function(){n(a).hide()}),l.done(function(){var b;N.remove(a,"fxshow");for(b in m)n.style(a,b,m[b])});for(d in m)g=Ya(p?q[d]:0,d,l),d in q||(q[d]=g.start,p&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function $a(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function _a(a,b,c){var d,e,f=0,g=_a.prefilters.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=Sa||Wa(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{},easing:n.easing._default},c),originalProperties:b,originalOptions:c,startTime:Sa||Wa(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?(h.notifyWith(a,[j,1,0]),h.resolveWith(a,[j,b])):h.rejectWith(a,[j,b]),this}}),k=j.props;for($a(k,j.opts.specialEasing);g>f;f++)if(d=_a.prefilters[f].call(j,a,k,j.opts))return n.isFunction(d.stop)&&(n._queueHooks(j.elem,j.opts.queue).stop=n.proxy(d.stop,d)),d;return n.map(k,Ya,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(_a,{tweeners:{"*":[function(a,b){var c=this.createTween(a,b);return W(c.elem,a,T.exec(b),c),c}]},tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.match(G);for(var c,d=0,e=a.length;e>d;d++)c=a[d],_a.tweeners[c]=_a.tweeners[c]||[],_a.tweeners[c].unshift(b)},prefilters:[Za],prefilter:function(a,b){b?_a.prefilters.unshift(a):_a.prefilters.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,null!=d.queue&&d.queue!==!0||(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(V).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=_a(this,n.extend({},a),f);(e||N.get(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=N.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&Va.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));!b&&c||n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=N.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(Xa(b,!0),a,d,e)}}),n.each({slideDown:Xa("show"),slideUp:Xa("hide"),slideToggle:Xa("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=0,c=n.timers;for(Sa=n.now();b<c.length;b++)a=c[b],a()||c[b]!==a||c.splice(b--,1);c.length||n.fx.stop(),Sa=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){Ta||(Ta=a.setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){a.clearInterval(Ta),Ta=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(b,c){return b=n.fx?n.fx.speeds[b]||b:b,c=c||"fx",this.queue(c,function(c,d){var e=a.setTimeout(c,b);d.stop=function(){a.clearTimeout(e)}})},function(){var a=d.createElement("input"),b=d.createElement("select"),c=b.appendChild(d.createElement("option"));a.type="checkbox",l.checkOn=""!==a.value,l.optSelected=c.selected,b.disabled=!0,l.optDisabled=!c.disabled,a=d.createElement("input"),a.value="t",a.type="radio",l.radioValue="t"===a.value}();var ab,bb=n.expr.attrHandle;n.fn.extend({attr:function(a,b){return K(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return"undefined"==typeof a.getAttribute?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),e=n.attrHooks[b]||(n.expr.match.bool.test(b)?ab:void 0)),void 0!==c?null===c?void n.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=n.find.attr(a,b),null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(G);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)&&(a[d]=!1),a.removeAttribute(c)}}),ab={set:function(a,b,c){return b===!1?n.removeAttr(a,c):a.setAttribute(c,c),c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=bb[b]||n.find.attr;bb[b]=function(a,b,d){var e,f;return d||(f=bb[b],bb[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,bb[b]=f),e}});var cb=/^(?:input|select|textarea|button)$/i,db=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return K(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[n.propFix[a]||a]})}}),n.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&n.isXMLDoc(a)||(b=n.propFix[b]||b,e=n.propHooks[b]),
void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):cb.test(a.nodeName)||db.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this});var eb=/[\t\r\n\f]/g;function fb(a){return a.getAttribute&&a.getAttribute("class")||""}n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,fb(this)))});if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=fb(c),d=1===c.nodeType&&(" "+e+" ").replace(eb," ")){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=n.trim(d),e!==h&&c.setAttribute("class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,fb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=fb(c),d=1===c.nodeType&&(" "+e+" ").replace(eb," ")){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=n.trim(d),e!==h&&c.setAttribute("class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):n.isFunction(a)?this.each(function(c){n(this).toggleClass(a.call(this,c,fb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=n(this),f=a.match(G)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=fb(this),b&&N.set(this,"__className__",b),this.setAttribute&&this.setAttribute("class",b||a===!1?"":N.get(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+fb(c)+" ").replace(eb," ").indexOf(b)>-1)return!0;return!1}});var gb=/\r/g,hb=/[\x20\t\r\n\f]+/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(gb,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.text(a)).replace(hb," ")}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],(c.selected||i===e)&&(l.optDisabled?!c.disabled:null===c.getAttribute("disabled"))&&(!c.parentNode.disabled||!n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=n.inArray(n.valHooks.option.get(d),f)>-1)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>-1:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var ib=/^(?:focusinfocus|focusoutblur)$/;n.extend(n.event,{trigger:function(b,c,e,f){var g,h,i,j,l,m,o,p=[e||d],q=k.call(b,"type")?b.type:b,r=k.call(b,"namespace")?b.namespace.split("."):[];if(h=i=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!ib.test(q+n.event.triggered)&&(q.indexOf(".")>-1&&(r=q.split("."),q=r.shift(),r.sort()),l=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=r.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},f||!o.trigger||o.trigger.apply(e,c)!==!1)){if(!f&&!o.noBubble&&!n.isWindow(e)){for(j=o.delegateType||q,ib.test(j+q)||(h=h.parentNode);h;h=h.parentNode)p.push(h),i=h;i===(e.ownerDocument||d)&&p.push(i.defaultView||i.parentWindow||a)}g=0;while((h=p[g++])&&!b.isPropagationStopped())b.type=g>1?j:o.bindType||q,m=(N.get(h,"events")||{})[b.type]&&N.get(h,"handle"),m&&m.apply(h,c),m=l&&h[l],m&&m.apply&&L(h)&&(b.result=m.apply(h,c),b.result===!1&&b.preventDefault());return b.type=q,f||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==!1||!L(e)||l&&n.isFunction(e[q])&&!n.isWindow(e)&&(i=e[l],i&&(e[l]=null),n.event.triggered=q,e[q](),n.event.triggered=void 0,i&&(e[l]=i)),b.result}},simulate:function(a,b,c){var d=n.extend(new n.Event,c,{type:a,isSimulated:!0});n.event.trigger(d,null,b)}}),n.fn.extend({trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),l.focusin="onfocusin"in a,l.focusin||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a))};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=N.access(d,b);e||d.addEventListener(a,c,!0),N.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=N.access(d,b)-1;e?N.access(d,b,e):(d.removeEventListener(a,c,!0),N.remove(d,b))}}});var jb=a.location,kb=n.now(),lb=/\?/;n.parseJSON=function(a){return JSON.parse(a+"")},n.parseXML=function(b){var c;if(!b||"string"!=typeof b)return null;try{c=(new a.DOMParser).parseFromString(b,"text/xml")}catch(d){c=void 0}return c&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var mb=/#.*$/,nb=/([?&])_=[^&]*/,ob=/^(.*?):[ \t]*([^\r\n]*)$/gm,pb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,qb=/^(?:GET|HEAD)$/,rb=/^\/\//,sb={},tb={},ub="*/".concat("*"),vb=d.createElement("a");vb.href=jb.href;function wb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(G)||[];if(n.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function xb(a,b,c,d){var e={},f=a===tb;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function yb(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&n.extend(!0,a,d),a}function zb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Ab(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:jb.href,type:"GET",isLocal:pb.test(jb.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":ub,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?yb(yb(a,n.ajaxSettings),b):yb(n.ajaxSettings,a)},ajaxPrefilter:wb(sb),ajaxTransport:wb(tb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var e,f,g,h,i,j,k,l,m=n.ajaxSetup({},c),o=m.context||m,p=m.context&&(o.nodeType||o.jquery)?n(o):n.event,q=n.Deferred(),r=n.Callbacks("once memory"),s=m.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,getResponseHeader:function(a){var b;if(2===v){if(!h){h={};while(b=ob.exec(g))h[b[1].toLowerCase()]=b[2]}b=h[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===v?g:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return v||(a=u[c]=u[c]||a,t[a]=b),this},overrideMimeType:function(a){return v||(m.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>v)for(b in a)s[b]=[s[b],a[b]];else x.always(a[x.status]);return this},abort:function(a){var b=a||w;return e&&e.abort(b),z(0,b),this}};if(q.promise(x).complete=r.add,x.success=x.done,x.error=x.fail,m.url=((b||m.url||jb.href)+"").replace(mb,"").replace(rb,jb.protocol+"//"),m.type=c.method||c.type||m.method||m.type,m.dataTypes=n.trim(m.dataType||"*").toLowerCase().match(G)||[""],null==m.crossDomain){j=d.createElement("a");try{j.href=m.url,j.href=j.href,m.crossDomain=vb.protocol+"//"+vb.host!=j.protocol+"//"+j.host}catch(y){m.crossDomain=!0}}if(m.data&&m.processData&&"string"!=typeof m.data&&(m.data=n.param(m.data,m.traditional)),xb(sb,m,c,x),2===v)return x;k=n.event&&m.global,k&&0===n.active++&&n.event.trigger("ajaxStart"),m.type=m.type.toUpperCase(),m.hasContent=!qb.test(m.type),f=m.url,m.hasContent||(m.data&&(f=m.url+=(lb.test(f)?"&":"?")+m.data,delete m.data),m.cache===!1&&(m.url=nb.test(f)?f.replace(nb,"$1_="+kb++):f+(lb.test(f)?"&":"?")+"_="+kb++)),m.ifModified&&(n.lastModified[f]&&x.setRequestHeader("If-Modified-Since",n.lastModified[f]),n.etag[f]&&x.setRequestHeader("If-None-Match",n.etag[f])),(m.data&&m.hasContent&&m.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",m.contentType),x.setRequestHeader("Accept",m.dataTypes[0]&&m.accepts[m.dataTypes[0]]?m.accepts[m.dataTypes[0]]+("*"!==m.dataTypes[0]?", "+ub+"; q=0.01":""):m.accepts["*"]);for(l in m.headers)x.setRequestHeader(l,m.headers[l]);if(m.beforeSend&&(m.beforeSend.call(o,x,m)===!1||2===v))return x.abort();w="abort";for(l in{success:1,error:1,complete:1})x[l](m[l]);if(e=xb(tb,m,c,x)){if(x.readyState=1,k&&p.trigger("ajaxSend",[x,m]),2===v)return x;m.async&&m.timeout>0&&(i=a.setTimeout(function(){x.abort("timeout")},m.timeout));try{v=1,e.send(t,z)}catch(y){if(!(2>v))throw y;z(-1,y)}}else z(-1,"No Transport");function z(b,c,d,h){var j,l,t,u,w,y=c;2!==v&&(v=2,i&&a.clearTimeout(i),e=void 0,g=h||"",x.readyState=b>0?4:0,j=b>=200&&300>b||304===b,d&&(u=zb(m,x,d)),u=Ab(m,u,x,j),j?(m.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(n.lastModified[f]=w),w=x.getResponseHeader("etag"),w&&(n.etag[f]=w)),204===b||"HEAD"===m.type?y="nocontent":304===b?y="notmodified":(y=u.state,l=u.data,t=u.error,j=!t)):(t=y,!b&&y||(y="error",0>b&&(b=0))),x.status=b,x.statusText=(c||y)+"",j?q.resolveWith(o,[l,y,x]):q.rejectWith(o,[x,y,t]),x.statusCode(s),s=void 0,k&&p.trigger(j?"ajaxSuccess":"ajaxError",[x,m,j?l:t]),r.fireWith(o,[x,y]),k&&(p.trigger("ajaxComplete",[x,m]),--n.active||n.event.trigger("ajaxStop")))}return x},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax(n.extend({url:a,type:b,dataType:e,data:c,success:d},n.isPlainObject(a)&&a))}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){var b;return n.isFunction(a)?this.each(function(b){n(this).wrapAll(a.call(this,b))}):(this[0]&&(b=n(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this)},wrapInner:function(a){return n.isFunction(a)?this.each(function(b){n(this).wrapInner(a.call(this,b))}):this.each(function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return!n.expr.filters.visible(a)},n.expr.filters.visible=function(a){return a.offsetWidth>0||a.offsetHeight>0||a.getClientRects().length>0};var Bb=/%20/g,Cb=/\[\]$/,Db=/\r?\n/g,Eb=/^(?:submit|button|image|reset|file)$/i,Fb=/^(?:input|select|textarea|keygen)/i;function Gb(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Cb.test(a)?d(a,e):Gb(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Gb(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Gb(c,a[c],b,e);return d.join("&").replace(Bb,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Fb.test(this.nodeName)&&!Eb.test(a)&&(this.checked||!X.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Db,"\r\n")}}):{name:b.name,value:c.replace(Db,"\r\n")}}).get()}}),n.ajaxSettings.xhr=function(){try{return new a.XMLHttpRequest}catch(b){}};var Hb={0:200,1223:204},Ib=n.ajaxSettings.xhr();l.cors=!!Ib&&"withCredentials"in Ib,l.ajax=Ib=!!Ib,n.ajaxTransport(function(b){var c,d;return l.cors||Ib&&!b.crossDomain?{send:function(e,f){var g,h=b.xhr();if(h.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(g in b.xhrFields)h[g]=b.xhrFields[g];b.mimeType&&h.overrideMimeType&&h.overrideMimeType(b.mimeType),b.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest");for(g in e)h.setRequestHeader(g,e[g]);c=function(a){return function(){c&&(c=d=h.onload=h.onerror=h.onabort=h.onreadystatechange=null,"abort"===a?h.abort():"error"===a?"number"!=typeof h.status?f(0,"error"):f(h.status,h.statusText):f(Hb[h.status]||h.status,h.statusText,"text"!==(h.responseType||"text")||"string"!=typeof h.responseText?{binary:h.response}:{text:h.responseText},h.getAllResponseHeaders()))}},h.onload=c(),d=h.onerror=c("error"),void 0!==h.onabort?h.onabort=d:h.onreadystatechange=function(){4===h.readyState&&a.setTimeout(function(){c&&d()})},c=c("abort");try{h.send(b.hasContent&&b.data||null)}catch(i){if(c)throw i}},abort:function(){c&&c()}}:void 0}),n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(e,f){b=n("<script>").prop({charset:a.scriptCharset,src:a.url}).on("load error",c=function(a){b.remove(),c=null,a&&f("error"===a.type?404:200,a.type)}),d.head.appendChild(b[0])},abort:function(){c&&c()}}}});var Jb=[],Kb=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Jb.pop()||n.expando+"_"+kb++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(Kb.test(b.url)?"url":"string"==typeof b.data&&0===(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&Kb.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(Kb,"$1"+e):b.jsonp!==!1&&(b.url+=(lb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){void 0===f?n(a).removeProp(e):a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,Jb.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||d;var e=x.exec(a),f=!c&&[];return e?[b.createElement(e[1])]:(e=ca([a],b,f),f&&f.length&&n(f).remove(),n.merge([],e.childNodes))};var Lb=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&Lb)return Lb.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>-1&&(d=n.trim(a.slice(h)),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&n.ajax({url:a,type:e||"GET",dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).always(c&&function(a,b){g.each(function(){c.apply(this,f||[a.responseText,b,a])})}),this},n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};function Mb(a){return n.isWindow(a)?a:9===a.nodeType&&a.defaultView}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&(f+i).indexOf("auto")>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,n.extend({},h))),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d=this[0],e={top:0,left:0},f=d&&d.ownerDocument;if(f)return b=f.documentElement,n.contains(b,d)?(e=d.getBoundingClientRect(),c=Mb(f),{top:e.top+c.pageYOffset-b.clientTop,left:e.left+c.pageXOffset-b.clientLeft}):e},position:function(){if(this[0]){var a,b,c=this[0],d={top:0,left:0};return"fixed"===n.css(c,"position")?b=c.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(d=a.offset()),d.top+=n.css(a[0],"borderTopWidth",!0),d.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-d.top-n.css(c,"marginTop",!0),left:b.left-d.left-n.css(c,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent;while(a&&"static"===n.css(a,"position"))a=a.offsetParent;return a||Ea})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c="pageYOffset"===b;n.fn[a]=function(d){return K(this,function(a,d,e){var f=Mb(a);return void 0===e?f?f[b]:a[d]:void(f?f.scrollTo(c?f.pageXOffset:e,c?e:f.pageYOffset):a[d]=e)},a,d,arguments.length)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Ga(l.pixelPosition,function(a,c){return c?(c=Fa(a,b),Ba.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return K(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.extend({bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)},size:function(){return this.length}}),n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var Nb=a.jQuery,Ob=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=Ob),b&&a.jQuery===n&&(a.jQuery=Nb),n},b||(a.jQuery=a.$=n),n});
var $j = jQuery.noConflict();
/*! jQuery Migrate v1.4.1 | (c) jQuery Foundation and other contributors | jquery.org/license */
"undefined"==typeof jQuery.migrateMute&&(jQuery.migrateMute=!0),function(a,b,c){function d(c){var d=b.console;f[c]||(f[c]=!0,a.migrateWarnings.push(c),d&&d.warn&&!a.migrateMute&&(d.warn("JQMIGRATE: "+c),a.migrateTrace&&d.trace&&d.trace()))}function e(b,c,e,f){if(Object.defineProperty)try{return void Object.defineProperty(b,c,{configurable:!0,enumerable:!0,get:function(){return d(f),e},set:function(a){d(f),e=a}})}catch(g){}a._definePropertyBroken=!0,b[c]=e}a.migrateVersion="1.4.1";var f={};a.migrateWarnings=[],b.console&&b.console.log&&b.console.log("JQMIGRATE: Migrate is installed"+(a.migrateMute?"":" with logging active")+", version "+a.migrateVersion),a.migrateTrace===c&&(a.migrateTrace=!0),a.migrateReset=function(){f={},a.migrateWarnings.length=0},"BackCompat"===document.compatMode&&d("jQuery is not compatible with Quirks Mode");var g=a("<input/>",{size:1}).attr("size")&&a.attrFn,h=a.attr,i=a.attrHooks.value&&a.attrHooks.value.get||function(){return null},j=a.attrHooks.value&&a.attrHooks.value.set||function(){return c},k=/^(?:input|button)$/i,l=/^[238]$/,m=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,n=/^(?:checked|selected)$/i;e(a,"attrFn",g||{},"jQuery.attrFn is deprecated"),a.attr=function(b,e,f,i){var j=e.toLowerCase(),o=b&&b.nodeType;return i&&(h.length<4&&d("jQuery.fn.attr( props, pass ) is deprecated"),b&&!l.test(o)&&(g?e in g:a.isFunction(a.fn[e])))?a(b)[e](f):("type"===e&&f!==c&&k.test(b.nodeName)&&b.parentNode&&d("Can't change the 'type' of an input or button in IE 6/7/8"),!a.attrHooks[j]&&m.test(j)&&(a.attrHooks[j]={get:function(b,d){var e,f=a.prop(b,d);return f===!0||"boolean"!=typeof f&&(e=b.getAttributeNode(d))&&e.nodeValue!==!1?d.toLowerCase():c},set:function(b,c,d){var e;return c===!1?a.removeAttr(b,d):(e=a.propFix[d]||d,e in b&&(b[e]=!0),b.setAttribute(d,d.toLowerCase())),d}},n.test(j)&&d("jQuery.fn.attr('"+j+"') might use property instead of attribute")),h.call(a,b,e,f))},a.attrHooks.value={get:function(a,b){var c=(a.nodeName||"").toLowerCase();return"button"===c?i.apply(this,arguments):("input"!==c&&"option"!==c&&d("jQuery.fn.attr('value') no longer gets properties"),b in a?a.value:null)},set:function(a,b){var c=(a.nodeName||"").toLowerCase();return"button"===c?j.apply(this,arguments):("input"!==c&&"option"!==c&&d("jQuery.fn.attr('value', val) no longer sets properties"),void(a.value=b))}};var o,p,q=a.fn.init,r=a.find,s=a.parseJSON,t=/^\s*</,u=/\[(\s*[-\w]+\s*)([~|^$*]?=)\s*([-\w#]*?#[-\w#]*)\s*\]/,v=/\[(\s*[-\w]+\s*)([~|^$*]?=)\s*([-\w#]*?#[-\w#]*)\s*\]/g,w=/^([^<]*)(<[\w\W]+>)([^>]*)$/;a.fn.init=function(b,e,f){var g,h;return b&&"string"==typeof b&&!a.isPlainObject(e)&&(g=w.exec(a.trim(b)))&&g[0]&&(t.test(b)||d("$(html) HTML strings must start with '<' character"),g[3]&&d("$(html) HTML text after last tag is ignored"),"#"===g[0].charAt(0)&&(d("HTML string cannot start with a '#' character"),a.error("JQMIGRATE: Invalid selector string (XSS)")),e&&e.context&&e.context.nodeType&&(e=e.context),a.parseHTML)?q.call(this,a.parseHTML(g[2],e&&e.ownerDocument||e||document,!0),e,f):(h=q.apply(this,arguments),b&&b.selector!==c?(h.selector=b.selector,h.context=b.context):(h.selector="string"==typeof b?b:"",b&&(h.context=b.nodeType?b:e||document)),h)},a.fn.init.prototype=a.fn,a.find=function(a){var b=Array.prototype.slice.call(arguments);if("string"==typeof a&&u.test(a))try{document.querySelector(a)}catch(c){a=a.replace(v,function(a,b,c,d){return"["+b+c+'"'+d+'"]'});try{document.querySelector(a),d("Attribute selector with '#' must be quoted: "+b[0]),b[0]=a}catch(e){d("Attribute selector with '#' was not fixed: "+b[0])}}return r.apply(this,b)};var x;for(x in r)Object.prototype.hasOwnProperty.call(r,x)&&(a.find[x]=r[x]);a.parseJSON=function(a){return a?s.apply(this,arguments):(d("jQuery.parseJSON requires a valid JSON string"),null)},a.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a.browser||(o=a.uaMatch(navigator.userAgent),p={},o.browser&&(p[o.browser]=!0,p.version=o.version),p.chrome?p.webkit=!0:p.webkit&&(p.safari=!0),a.browser=p),e(a,"browser",a.browser,"jQuery.browser is deprecated"),a.boxModel=a.support.boxModel="CSS1Compat"===document.compatMode,e(a,"boxModel",a.boxModel,"jQuery.boxModel is deprecated"),e(a.support,"boxModel",a.support.boxModel,"jQuery.support.boxModel is deprecated"),a.sub=function(){function b(a,c){return new b.fn.init(a,c)}a.extend(!0,b,this),b.superclass=this,b.fn=b.prototype=this(),b.fn.constructor=b,b.sub=this.sub,b.fn.init=function(d,e){var f=a.fn.init.call(this,d,e,c);return f instanceof b?f:b(f)},b.fn.init.prototype=b.fn;var c=b(document);return d("jQuery.sub() is deprecated"),b},a.fn.size=function(){return d("jQuery.fn.size() is deprecated; use the .length property"),this.length};var y=!1;a.swap&&a.each(["height","width","reliableMarginRight"],function(b,c){var d=a.cssHooks[c]&&a.cssHooks[c].get;d&&(a.cssHooks[c].get=function(){var a;return y=!0,a=d.apply(this,arguments),y=!1,a})}),a.swap=function(a,b,c,e){var f,g,h={};y||d("jQuery.swap() is undocumented and deprecated");for(g in b)h[g]=a.style[g],a.style[g]=b[g];f=c.apply(a,e||[]);for(g in b)a.style[g]=h[g];return f},a.ajaxSetup({converters:{"text json":a.parseJSON}});var z=a.fn.data;a.fn.data=function(b){var e,f,g=this[0];return!g||"events"!==b||1!==arguments.length||(e=a.data(g,b),f=a._data(g,b),e!==c&&e!==f||f===c)?z.apply(this,arguments):(d("Use of jQuery.fn.data('events') is deprecated"),f)};var A=/\/(java|ecma)script/i;a.clean||(a.clean=function(b,c,e,f){c=c||document,c=!c.nodeType&&c[0]||c,c=c.ownerDocument||c,d("jQuery.clean() is deprecated");var g,h,i,j,k=[];if(a.merge(k,a.buildFragment(b,c).childNodes),e)for(i=function(a){return!a.type||A.test(a.type)?f?f.push(a.parentNode?a.parentNode.removeChild(a):a):e.appendChild(a):void 0},g=0;null!=(h=k[g]);g++)a.nodeName(h,"script")&&i(h)||(e.appendChild(h),"undefined"!=typeof h.getElementsByTagName&&(j=a.grep(a.merge([],h.getElementsByTagName("script")),i),k.splice.apply(k,[g+1,0].concat(j)),g+=j.length));return k});var B=a.event.add,C=a.event.remove,D=a.event.trigger,E=a.fn.toggle,F=a.fn.live,G=a.fn.die,H=a.fn.load,I="ajaxStart|ajaxStop|ajaxSend|ajaxComplete|ajaxError|ajaxSuccess",J=new RegExp("\\b(?:"+I+")\\b"),K=/(?:^|\s)hover(\.\S+|)\b/,L=function(b){return"string"!=typeof b||a.event.special.hover?b:(K.test(b)&&d("'hover' pseudo-event is deprecated, use 'mouseenter mouseleave'"),b&&b.replace(K,"mouseenter$1 mouseleave$1"))};a.event.props&&"attrChange"!==a.event.props[0]&&a.event.props.unshift("attrChange","attrName","relatedNode","srcElement"),a.event.dispatch&&e(a.event,"handle",a.event.dispatch,"jQuery.event.handle is undocumented and deprecated"),a.event.add=function(a,b,c,e,f){a!==document&&J.test(b)&&d("AJAX events should be attached to document: "+b),B.call(this,a,L(b||""),c,e,f)},a.event.remove=function(a,b,c,d,e){C.call(this,a,L(b)||"",c,d,e)},a.each(["load","unload","error"],function(b,c){a.fn[c]=function(){var a=Array.prototype.slice.call(arguments,0);return"load"===c&&"string"==typeof a[0]?H.apply(this,a):(d("jQuery.fn."+c+"() is deprecated"),a.splice(0,0,c),arguments.length?this.bind.apply(this,a):(this.triggerHandler.apply(this,a),this))}}),a.fn.toggle=function(b,c){if(!a.isFunction(b)||!a.isFunction(c))return E.apply(this,arguments);d("jQuery.fn.toggle(handler, handler...) is deprecated");var e=arguments,f=b.guid||a.guid++,g=0,h=function(c){var d=(a._data(this,"lastToggle"+b.guid)||0)%g;return a._data(this,"lastToggle"+b.guid,d+1),c.preventDefault(),e[d].apply(this,arguments)||!1};for(h.guid=f;g<e.length;)e[g++].guid=f;return this.click(h)},a.fn.live=function(b,c,e){return d("jQuery.fn.live() is deprecated"),F?F.apply(this,arguments):(a(this.context).on(b,this.selector,c,e),this)},a.fn.die=function(b,c){return d("jQuery.fn.die() is deprecated"),G?G.apply(this,arguments):(a(this.context).off(b,this.selector||"**",c),this)},a.event.trigger=function(a,b,c,e){return c||J.test(a)||d("Global events are undocumented and deprecated"),D.call(this,a,b,c||document,e)},a.each(I.split("|"),function(b,c){a.event.special[c]={setup:function(){var b=this;return b!==document&&(a.event.add(document,c+"."+a.guid,function(){a.event.trigger(c,Array.prototype.slice.call(arguments,1),b,!0)}),a._data(this,c,a.guid++)),!1},teardown:function(){return this!==document&&a.event.remove(document,c+"."+a._data(this,c)),!1}}}),a.event.special.ready={setup:function(){this===document&&d("'ready' event is deprecated")}};var M=a.fn.andSelf||a.fn.addBack,N=a.fn.find;if(a.fn.andSelf=function(){return d("jQuery.fn.andSelf() replaced by jQuery.fn.addBack()"),M.apply(this,arguments)},a.fn.find=function(a){var b=N.apply(this,arguments);return b.context=this.context,b.selector=this.selector?this.selector+" "+a:a,b},a.Callbacks){var O=a.Deferred,P=[["resolve","done",a.Callbacks("once memory"),a.Callbacks("once memory"),"resolved"],["reject","fail",a.Callbacks("once memory"),a.Callbacks("once memory"),"rejected"],["notify","progress",a.Callbacks("memory"),a.Callbacks("memory")]];a.Deferred=function(b){var c=O(),e=c.promise();return c.pipe=e.pipe=function(){var b=arguments;return d("deferred.pipe() is deprecated"),a.Deferred(function(d){a.each(P,function(f,g){var h=a.isFunction(b[f])&&b[f];c[g[1]](function(){var b=h&&h.apply(this,arguments);b&&a.isFunction(b.promise)?b.promise().done(d.resolve).fail(d.reject).progress(d.notify):d[g[0]+"With"](this===e?d.promise():this,h?[b]:arguments)})}),b=null}).promise()},c.isResolved=function(){return d("deferred.isResolved is deprecated"),"resolved"===c.state()},c.isRejected=function(){return d("deferred.isRejected is deprecated"),"rejected"===c.state()},b&&b.call(c,c),c}}}(jQuery,window);
/**
* Created by Geo on 4/22/16.
*/
// jQuery Mask Plugin v1.7.2
// github.com/igorescobar/jQuery-Mask-Plugin
(function(g){"function"===typeof define&&define.amd?define(["jquery"],g):g(window.jQuery||window.Zepto)})(function(g){var z=function(a,e,b){var k=this,q,n;a=g(a);e="function"===typeof e?e(a.val(),void 0,a,b):e;k.init=function(){b=b||{};k.byPassKeys=[9,16,17,18,36,37,38,39,40,91];k.translation={0:{pattern:/\d/},9:{pattern:/\d/,optional:!0},"#":{pattern:/\d/,recursive:!0},A:{pattern:/[a-zA-Z0-9]/},S:{pattern:/[a-zA-Z]/}};k.translation=g.extend({},k.translation,b.translation);k=g.extend(!0,{},k,b);n=
c.getRegexMask();a.each(function(){!1!==b.maxlength&&a.attr("maxlength",e.length);b.placeholder&&a.attr("placeholder",b.placeholder);a.attr("autocomplete","off");c.destroyEvents();c.events();var d=c.getCaret();c.val(c.getMasked());c.setCaret(d+c.getMCharsBeforeCount(d,!0))})};var c={getCaret:function(){try{var d,f=0,c=a.get(0),h=document.selection,e=c.selectionStart;if(h&&!~navigator.appVersion.indexOf("MSIE 10"))d=h.createRange(),d.moveStart("character",a.is("input")?-a.val().length:-a.text().length),
f=d.text.length;else if(e||"0"===e)f=e;return f}catch(b){}},setCaret:function(d){try{if(a.is(":focus")){var f,c=a.get(0);c.setSelectionRange?c.setSelectionRange(d,d):c.createTextRange&&(f=c.createTextRange(),f.collapse(!0),f.moveEnd("character",d),f.moveStart("character",d),f.select())}}catch(h){}},events:function(){a.on("keydown.mask",function(){q=c.val()}).on("keyup.mask",c.behaviour).on("paste.mask drop.mask",function(){setTimeout(function(){a.keydown().keyup()},100)}).on("change.mask",function(){a.data("changed",
!0)}).on("blur.mask",function(){q===a.val()||a.data("changed")||a.trigger("change");a.data("changed",!1)}).on("focusout.mask",function(){b.clearIfNotMatch&&!n.test(c.val())&&c.val("")})},getRegexMask:function(){for(var d=[],f,a,c,b,l=0;l<e.length;l++)(f=k.translation[e[l]])?(a=f.pattern.toString().replace(/.{1}$|^.{1}/g,""),c=f.optional,(f=f.recursive)?(d.push(e[l]),b={digit:e[l],pattern:a}):d.push(c||f?a+"?":a)):d.push("\\"+e[l]);d=d.join("");b&&(d=d.replace(RegExp("("+b.digit+"(.*"+b.digit+")?)"),
"($1)?").replace(RegExp(b.digit,"g"),b.pattern));return RegExp(d)},destroyEvents:function(){a.off("keydown keyup paste drop change blur focusout DOMNodeInserted ".split(" ").join(".mask ")).removeData("changeCalled")},val:function(d){var c=a.is("input");return 0<arguments.length?c?a.val(d):a.text(d):c?a.val():a.text()},getMCharsBeforeCount:function(d,a){for(var c=0,b=0,g=e.length;b<g&&b<d;b++)k.translation[e.charAt(b)]||(d=a?d+1:d,c++);return c},caretPos:function(d,a,b,h){return k.translation[e.charAt(Math.min(d-
1,e.length-1))]?Math.min(d+b-a-h,b):c.caretPos(d+1,a,b,h)},behaviour:function(d){d=d||window.event;var a=d.keyCode||d.which;if(-1===g.inArray(a,k.byPassKeys)){var b=c.getCaret(),e=c.val(),p=e.length,l=b<p,u=c.getMasked(),m=u.length,n=c.getMCharsBeforeCount(m-1)-c.getMCharsBeforeCount(p-1);u!==e&&c.val(u);!l||65===a&&d.ctrlKey||(8!==a&&46!==a&&(b=c.caretPos(b,p,m,n)),c.setCaret(b));return c.callbacks(d)}},getMasked:function(a){var f=[],g=c.val(),h=0,p=e.length,l=0,n=g.length,m=1,q="push",s=-1,r,v;
b.reverse?(q="unshift",m=-1,r=0,h=p-1,l=n-1,v=function(){return-1<h&&-1<l}):(r=p-1,v=function(){return h<p&&l<n});for(;v();){var w=e.charAt(h),x=g.charAt(l),t=k.translation[w];if(t)x.match(t.pattern)?(f[q](x),t.recursive&&(-1===s?s=h:h===r&&(h=s-m),r===s&&(h-=m)),h+=m):t.optional&&(h+=m,l-=m),l+=m;else{if(!a)f[q](w);x===w&&(l+=m);h+=m}}a=e.charAt(r);p!==n+1||k.translation[a]||f.push(a);return f.join("")},callbacks:function(d){var f=c.val(),g=f!==q;if(!0===g&&"function"===typeof b.onChange)b.onChange(f,
d,a,b);if(!0===g&&"function"===typeof b.onKeyPress)b.onKeyPress(f,d,a,b);if("function"===typeof b.onComplete&&f.length===e.length)b.onComplete(f,d,a,b)}};k.remove=function(){var a;c.destroyEvents();c.val(k.getCleanVal()).removeAttr("maxlength");a=c.getCaret();c.setCaret(a-c.getMCharsBeforeCount(a))};k.getCleanVal=function(){return c.getMasked(!0)};k.init()},n={},y=function(){var a=g(this),e={};"true"===a.attr("data-mask-reverse")&&(e.reverse=!0);"false"===a.attr("data-mask-maxlength")&&(e.maxlength=
!1);"true"===a.attr("data-mask-clearifnotmatch")&&(e.clearIfNotMatch=!0);a.mask(a.attr("data-mask"),e)};g.fn.mask=function(a,e){this.unmask();var b=this.selector,k=function(){g(this).data("mask",new z(this,a,e))};b&&!n[b]&&(n[b]=!0,setTimeout(function(){g(document).on("DOMNodeInserted.mask",b,k)},500));return this.each(k)};g.fn.unmask=function(){try{return this.each(function(){g(this).data("mask").remove()})}catch(a){}};g.fn.cleanVal=function(){return this.data("mask").getCleanVal()};g("*[data-mask]").each(y);
g(document).on("DOMNodeInserted.mask","*[data-mask]",y)});
(function(e){function t(){var e=document.createElement("input"),t="onpaste";return e.setAttribute(t,""),"function"==typeof e[t]?"paste":"input"}var n,a=t()+".mask",r=navigator.userAgent,i=/iphone/i.test(r),o=/android/i.test(r);e.mask={definitions:{9:"[0-9]",a:"[A-Za-z]","*":"[A-Za-z0-9]"},dataName:"rawMaskFn",placeholder:"_"},e.fn.extend({caret:function(e,t){var n;if(0!==this.length&&!this.is(":hidden"))return"number"==typeof e?(t="number"==typeof t?t:e,this.each(function(){this.setSelectionRange?this.setSelectionRange(e,t):this.createTextRange&&(n=this.createTextRange(),n.collapse(!0),n.moveEnd("character",t),n.moveStart("character",e),n.select())})):(this[0].setSelectionRange?(e=this[0].selectionStart,t=this[0].selectionEnd):document.selection&&document.selection.createRange&&(n=document.selection.createRange(),e=0-n.duplicate().moveStart("character",-1e5),t=e+n.text.length),{begin:e,end:t})},unmask:function(){return this.trigger("unmask")},mask:function(t,r){var c,l,s,u,f,h;return!t&&this.length>0?(c=e(this[0]),c.data(e.mask.dataName)()):(r=e.extend({placeholder:e.mask.placeholder,completed:null},r),l=e.mask.definitions,s=[],u=h=t.length,f=null,e.each(t.split(""),function(e,t){"?"==t?(h--,u=e):l[t]?(s.push(RegExp(l[t])),null===f&&(f=s.length-1)):s.push(null)}),this.trigger("unmask").each(function(){function c(e){for(;h>++e&&!s[e];);return e}function d(e){for(;--e>=0&&!s[e];);return e}function m(e,t){var n,a;if(!(0>e)){for(n=e,a=c(t);h>n;n++)if(s[n]){if(!(h>a&&s[n].test(R[a])))break;R[n]=R[a],R[a]=r.placeholder,a=c(a)}b(),x.caret(Math.max(f,e))}}function p(e){var t,n,a,i;for(t=e,n=r.placeholder;h>t;t++)if(s[t]){if(a=c(t),i=R[t],R[t]=n,!(h>a&&s[a].test(i)))break;n=i}}function g(e){var t,n,a,r=e.which;8===r||46===r||i&&127===r?(t=x.caret(),n=t.begin,a=t.end,0===a-n&&(n=46!==r?d(n):a=c(n-1),a=46===r?c(a):a),k(n,a),m(n,a-1),e.preventDefault()):27==r&&(x.val(S),x.caret(0,y()),e.preventDefault())}function v(t){var n,a,i,l=t.which,u=x.caret();t.ctrlKey||t.altKey||t.metaKey||32>l||l&&(0!==u.end-u.begin&&(k(u.begin,u.end),m(u.begin,u.end-1)),n=c(u.begin-1),h>n&&(a=String.fromCharCode(l),s[n].test(a)&&(p(n),R[n]=a,b(),i=c(n),o?setTimeout(e.proxy(e.fn.caret,x,i),0):x.caret(i),r.completed&&i>=h&&r.completed.call(x))),t.preventDefault())}function k(e,t){var n;for(n=e;t>n&&h>n;n++)s[n]&&(R[n]=r.placeholder)}function b(){x.val(R.join(""))}function y(e){var t,n,a=x.val(),i=-1;for(t=0,pos=0;h>t;t++)if(s[t]){for(R[t]=r.placeholder;pos++<a.length;)if(n=a.charAt(pos-1),s[t].test(n)){R[t]=n,i=t;break}if(pos>a.length)break}else R[t]===a.charAt(pos)&&t!==u&&(pos++,i=t);return e?b():u>i+1?(x.val(""),k(0,h)):(b(),x.val(x.val().substring(0,i+1))),u?t:f}var x=e(this),R=e.map(t.split(""),function(e){return"?"!=e?l[e]?r.placeholder:e:void 0}),S=x.val();x.data(e.mask.dataName,function(){return e.map(R,function(e,t){return s[t]&&e!=r.placeholder?e:null}).join("")}),x.attr("readonly")||x.one("unmask",function(){x.unbind(".mask").removeData(e.mask.dataName)}).bind("focus.mask",function(){clearTimeout(n);var e;S=x.val(),e=y(),n=setTimeout(function(){b(),e==t.length?x.caret(0,e):x.caret(e)},10)}).bind("blur.mask",function(){y(),x.val()!=S&&x.change()}).bind("keydown.mask",g).bind("keypress.mask",v).bind(a,function(){setTimeout(function(){var e=y(!0);x.caret(e),r.completed&&e==x.val().length&&r.completed.call(x)},0)}),y()}))}})})(jQuery);
/* Modernizr 2.6.2 (Custom Build) | MIT & BSD
* Build: http://modernizr.com/download/#-localstorage-touch-shiv-mq-cssclasses-teststyles-prefixes-load
*/
;window.Modernizr=function(a,b,c){function x(a){j.cssText=a}function y(a,b){return x(m.join(a+";")+(b||""))}function z(a,b){return typeof a===b}function A(a,b){return!!~(""+a).indexOf(b)}function B(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:z(f,"function")?f.bind(d||b):f}return!1}var d="2.6.2",e={},f=!0,g=b.documentElement,h="modernizr",i=b.createElement(h),j=i.style,k,l={}.toString,m=" -webkit- -moz- -o- -ms- ".split(" "),n={},o={},p={},q=[],r=q.slice,s,t=function(a,c,d,e){var f,i,j,k,l=b.createElement("div"),m=b.body,n=m||b.createElement("body");if(parseInt(d,10))while(d--)j=b.createElement("div"),j.id=e?e[d]:h+(d+1),l.appendChild(j);return f=["­",'<style id="s',h,'">',a,"</style>"].join(""),l.id=h,(m?l:n).innerHTML+=f,n.appendChild(l),m||(n.style.background="",n.style.overflow="hidden",k=g.style.overflow,g.style.overflow="hidden",g.appendChild(n)),i=c(l,a),m?l.parentNode.removeChild(l):(n.parentNode.removeChild(n),g.style.overflow=k),!!i},u=function(b){var c=a.matchMedia||a.msMatchMedia;if(c)return c(b).matches;var d;return t("@media "+b+" { #"+h+" { position: absolute; } }",function(b){d=(a.getComputedStyle?getComputedStyle(b,null):b.currentStyle)["position"]=="absolute"}),d},v={}.hasOwnProperty,w;!z(v,"undefined")&&!z(v.call,"undefined")?w=function(a,b){return v.call(a,b)}:w=function(a,b){return b in a&&z(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=r.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(r.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(r.call(arguments)))};return e}),n.touch=function(){var c;return"ontouchstart"in a||a.DocumentTouch&&b instanceof DocumentTouch?c=!0:t(["@media (",m.join("touch-enabled),("),h,")","{#modernizr{top:9px;position:absolute}}"].join(""),function(a){c=a.offsetTop===9}),c},n.localstorage=function(){try{return localStorage.setItem(h,h),localStorage.removeItem(h),!0}catch(a){return!1}};for(var C in n)w(n,C)&&(s=C.toLowerCase(),e[s]=n[C](),q.push((e[s]?"":"no-")+s));return e.addTest=function(a,b){if(typeof a=="object")for(var d in a)w(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,typeof f!="undefined"&&f&&(g.className+=" "+(b?"":"no-")+a),e[a]=b}return e},x(""),i=k=null,function(a,b){function k(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function l(){var a=r.elements;return typeof a=="string"?a.split(" "):a}function m(a){var b=i[a[g]];return b||(b={},h++,a[g]=h,i[h]=b),b}function n(a,c,f){c||(c=b);if(j)return c.createElement(a);f||(f=m(c));var g;return f.cache[a]?g=f.cache[a].cloneNode():e.test(a)?g=(f.cache[a]=f.createElem(a)).cloneNode():g=f.createElem(a),g.canHaveChildren&&!d.test(a)?f.frag.appendChild(g):g}function o(a,c){a||(a=b);if(j)return a.createDocumentFragment();c=c||m(a);var d=c.frag.cloneNode(),e=0,f=l(),g=f.length;for(;e<g;e++)d.createElement(f[e]);return d}function p(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return r.shivMethods?n(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+l().join().replace(/\w+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(r,b.frag)}function q(a){a||(a=b);var c=m(a);return r.shivCSS&&!f&&!c.hasCSS&&(c.hasCSS=!!k(a,"article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}mark{background:#FF0;color:#000}")),j||p(a,c),a}var c=a.html5||{},d=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,e=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,f,g="_html5shiv",h=0,i={},j;(function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",f="hidden"in a,j=a.childNodes.length==1||function(){b.createElement("a");var a=b.createDocumentFragment();return typeof a.cloneNode=="undefined"||typeof a.createDocumentFragment=="undefined"||typeof a.createElement=="undefined"}()}catch(c){f=!0,j=!0}})();var r={elements:c.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:c.shivCSS!==!1,supportsUnknownElements:j,shivMethods:c.shivMethods!==!1,type:"default",shivDocument:q,createElement:n,createDocumentFragment:o};a.html5=r,q(b)}(this,b),e._version=d,e._prefixes=m,e.mq=u,e.testStyles=t,g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+q.join(" "):""),e}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f<d;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;f<b;f++)c=x[f](c);return c}function g(a,e,f,g,h){var i=b(a),j=i.autoCallback;i.url.split(".").pop().split("?").shift(),i.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]),i.instead?i.instead(a,e,f,g,h):(y[i.url]?i.noexec=!0:y[i.url]=1,f.load(i.url,i.forceCSS||!i.forceJS&&"css"==i.url.split(".").pop().split("?").shift()?"c":c,i.noexec,i.attrs,i.timeout),(d(e)||d(j))&&f.load(function(){k(),e&&e(i.origUrl,h,g),j&&j(i.origUrl,h,g),y[i.url]=2})))}function h(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var b=0,c;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f,m,n;c(h?a.yep:a.nope,!!i),i&&c(i)}var i,j,l=this.yepnope.loader;if(e(a))g(a,0,l,0);else if(w(a))for(i=0;i<a.length;i++)j=a[i],e(j)?g(j,0,l,0):w(j)?B(j):Object(j)===j&&h(j,l);else Object(a)===a&&h(a,l)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,null==b.readyState&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var k=b.createElement("script"),l,o,e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var e=b.createElement("link"),j,c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}}(this,document),Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0))};
/*
selectivizr v1.0.2 - (c) Keith Clark, freely distributable under the terms
of the MIT license.
selectivizr.com
*/
/*
Notes about this source
-----------------------
* The #DEBUG_START and #DEBUG_END comments are used to mark blocks of code
that will be removed prior to building a final release version (using a
pre-compression script)
References:
-----------
* CSS Syntax : http://www.w3.org/TR/2003/WD-css3-syntax-20030813/#style
* Selectors : http://www.w3.org/TR/css3-selectors/#selectors
* IE Compatability : http://msdn.microsoft.com/en-us/library/cc351024(VS.85).aspx
* W3C Selector Tests : http://www.w3.org/Style/CSS/Test/CSS3/Selectors/current/html/tests/
*/
(function(win) {
// If browser isn't IE, then stop execution! This handles the script
// being loaded by non IE browsers because the developer didn't use
// conditional comments.
if (/*@cc_on!@*/true) return;
// =========================== Init Objects ============================
var doc = document;
var root = doc.documentElement;
var xhr = getXHRObject();
var ieVersion = /MSIE (\d+)/.exec(navigator.userAgent)[1];
// If were not in standards mode, IE is too old / new or we can't create
// an XMLHttpRequest object then we should get out now.
if (doc.compatMode != 'CSS1Compat' || ieVersion<6 || ieVersion>8 || !xhr) {
return;
}
// ========================= Common Objects ============================
// Compatiable selector engines in order of CSS3 support. Note: '*' is
// a placholder for the object key name. (basically, crude compression)
var selectorEngines = {
"NW" : "*.Dom.select",
"MooTools" : "$$",
"DOMAssistant" : "*.$",
"Prototype" : "$$",
"YAHOO" : "*.util.Selector.query",
"Sizzle" : "*",
"jQuery" : "*",
"dojo" : "*.query"
};
var selectorMethod;
var enabledWatchers = []; // array of :enabled/:disabled elements to poll
var ie6PatchID = 0; // used to solve ie6's multiple class bug
var patchIE6MultipleClasses = true; // if true adds class bloat to ie6
var namespace = "slvzr";
// Stylesheet parsing regexp's
var RE_COMMENT = /(\/\*[^*]*\*+([^\/][^*]*\*+)*\/)\s*/g;
var RE_IMPORT = /@import\s*(?:(?:(?:url\(\s*(['"]?)(.*)\1)\s*\))|(?:(['"])(.*)\3))[^;]*;/g;
var RE_ASSET_URL = /\burl\(\s*(["']?)(?!data:)([^"')]+)\1\s*\)/g;
var RE_PSEUDO_STRUCTURAL = /^:(empty|(first|last|only|nth(-last)?)-(child|of-type))$/;
var RE_PSEUDO_ELEMENTS = /:(:first-(?:line|letter))/g;
var RE_SELECTOR_GROUP = /(^|})\s*([^\{]*?[\[:][^{]+)/g;
var RE_SELECTOR_PARSE = /([ +~>])|(:[a-z-]+(?:\(.*?\)+)?)|(\[.*?\])/g;
var RE_LIBRARY_INCOMPATIBLE_PSEUDOS = /(:not\()?:(hover|enabled|disabled|focus|checked|target|active|visited|first-line|first-letter)\)?/g;
var RE_PATCH_CLASS_NAME_REPLACE = /[^\w-]/g;
// HTML UI element regexp's
var RE_INPUT_ELEMENTS = /^(INPUT|SELECT|TEXTAREA|BUTTON)$/;
var RE_INPUT_CHECKABLE_TYPES = /^(checkbox|radio)$/;
// Broken attribute selector implementations (IE7/8 native [^=""], [$=""] and [*=""])
var BROKEN_ATTR_IMPLEMENTATIONS = ieVersion>6 ? /[\$\^*]=(['"])\1/ : null;
// Whitespace normalization regexp's
var RE_TIDY_TRAILING_WHITESPACE = /([(\[+~])\s+/g;
var RE_TIDY_LEADING_WHITESPACE = /\s+([)\]+~])/g;
var RE_TIDY_CONSECUTIVE_WHITESPACE = /\s+/g;
var RE_TIDY_TRIM_WHITESPACE = /^\s*((?:[\S\s]*\S)?)\s*$/;
// String constants
var EMPTY_STRING = "";
var SPACE_STRING = " ";
var PLACEHOLDER_STRING = "$1";
// =========================== Patching ================================
// --[ patchStyleSheet() ]----------------------------------------------
// Scans the passed cssText for selectors that require emulation and
// creates one or more patches for each matched selector.
function patchStyleSheet( cssText ) {
return cssText.replace(RE_PSEUDO_ELEMENTS, PLACEHOLDER_STRING).
replace(RE_SELECTOR_GROUP, function(m, prefix, selectorText) {
var selectorGroups = selectorText.split(",");
for (var c = 0, cs = selectorGroups.length; c < cs; c++) {
var selector = normalizeSelectorWhitespace(selectorGroups[c]) + SPACE_STRING;
var patches = [];
selectorGroups[c] = selector.replace(RE_SELECTOR_PARSE,
function(match, combinator, pseudo, attribute, index) {
if (combinator) {
if (patches.length>0) {
applyPatches( selector.substring(0, index), patches );
patches = [];
}
return combinator;
}
else {
var patch = (pseudo) ? patchPseudoClass( pseudo ) : patchAttribute( attribute );
if (patch) {
patches.push(patch);
return "." + patch.className;
}
return match;
}
}
);
}
return prefix + selectorGroups.join(",");
});
};
// --[ patchAttribute() ]-----------------------------------------------
// returns a patch for an attribute selector.
function patchAttribute( attr ) {
return (!BROKEN_ATTR_IMPLEMENTATIONS || BROKEN_ATTR_IMPLEMENTATIONS.test(attr)) ?
{ className: createClassName(attr), applyClass: true } : null;
};
// --[ patchPseudoClass() ]---------------------------------------------
// returns a patch for a pseudo-class
function patchPseudoClass( pseudo ) {
var applyClass = true;
var className = createClassName(pseudo.slice(1));
var isNegated = pseudo.substring(0, 5) == ":not(";
var activateEventName;
var deactivateEventName;
// if negated, remove :not()
if (isNegated) {
pseudo = pseudo.slice(5, -1);
}
// bracket contents are irrelevant - remove them
var bracketIndex = pseudo.indexOf("(")
if (bracketIndex > -1) {
pseudo = pseudo.substring(0, bracketIndex);
}
// check we're still dealing with a pseudo-class
if (pseudo.charAt(0) == ":") {
switch (pseudo.slice(1)) {
case "root":
applyClass = function(e) {
return isNegated ? e != root : e == root;
}
break;
case "target":
// :target is only supported in IE8
if (ieVersion == 8) {
applyClass = function(e) {
var handler = function() {
var hash = location.hash;
var hashID = hash.slice(1);
return isNegated ? (hash == EMPTY_STRING || e.id != hashID) : (hash != EMPTY_STRING && e.id == hashID);
};
addEvent( win, "hashchange", function() {
toggleElementClass(e, className, handler());
})
return handler();
}
break;
}
return false;
case "checked":
applyClass = function(e) {
if (RE_INPUT_CHECKABLE_TYPES.test(e.type)) {
addEvent( e, "propertychange", function() {
if (event.propertyName == "checked") {
toggleElementClass( e, className, e.checked !== isNegated );
}
})
}
return e.checked !== isNegated;
}
break;
case "disabled":
isNegated = !isNegated;
case "enabled":
applyClass = function(e) {
if (RE_INPUT_ELEMENTS.test(e.tagName)) {
addEvent( e, "propertychange", function() {
if (event.propertyName == "$disabled") {
toggleElementClass( e, className, e.$disabled === isNegated );
}
});
enabledWatchers.push(e);
e.$disabled = e.disabled;
return e.disabled === isNegated;
}
return pseudo == ":enabled" ? isNegated : !isNegated;
}
break;
case "focus":
activateEventName = "focus";
deactivateEventName = "blur";
case "hover":
if (!activateEventName) {
activateEventName = "mouseenter";
deactivateEventName = "mouseleave";
}
applyClass = function(e) {
addEvent( e, isNegated ? deactivateEventName : activateEventName, function() {
toggleElementClass( e, className, true );
})
addEvent( e, isNegated ? activateEventName : deactivateEventName, function() {
toggleElementClass( e, className, false );
})
return isNegated;
}
break;
// everything else
default:
// If we don't support this pseudo-class don't create
// a patch for it
if (!RE_PSEUDO_STRUCTURAL.test(pseudo)) {
return false;
}
break;
}
}
return { className: className, applyClass: applyClass };
};
// --[ applyPatches() ]-------------------------------------------------
// uses the passed selector text to find DOM nodes and patch them
function applyPatches(selectorText, patches) {
var elms;
// Although some selector libraries can find :checked :enabled etc.
// we need to find all elements that could have that state because
// it can be changed by the user.
var domSelectorText = selectorText.replace(RE_LIBRARY_INCOMPATIBLE_PSEUDOS, EMPTY_STRING);
// If the dom selector equates to an empty string or ends with
// whitespace then we need to append a universal selector (*) to it.
if (domSelectorText == EMPTY_STRING || domSelectorText.charAt(domSelectorText.length - 1) == SPACE_STRING) {
domSelectorText += "*";
}
// Ensure we catch errors from the selector library
try {
elms = selectorMethod( domSelectorText );
} catch (ex) {
// #DEBUG_START
log( "Selector '" + selectorText + "' threw exception '" + ex + "'" );
// #DEBUG_END
}
if (elms) {
for (var d = 0, dl = elms.length; d < dl; d++) {
var elm = elms[d];
var cssClasses = elm.className;
for (var f = 0, fl = patches.length; f < fl; f++) {
var patch = patches[f];
if (!hasPatch(elm, patch)) {
if (patch.applyClass && (patch.applyClass === true || patch.applyClass(elm) === true)) {
cssClasses = toggleClass(cssClasses, patch.className, true );
}
}
}
elm.className = cssClasses;
}
}
};
// --[ hasPatch() ]-----------------------------------------------------
// checks for the exsistence of a patch on an element
function hasPatch( elm, patch ) {
return new RegExp("(^|\\s)" + patch.className + "(\\s|$)").test(elm.className);
};
// =========================== Utility =================================
function createClassName( className ) {
return namespace + "-" + ((ieVersion == 6 && patchIE6MultipleClasses) ?
ie6PatchID++
:
className.replace(RE_PATCH_CLASS_NAME_REPLACE, function(a) { return a.charCodeAt(0) }));
};
// --[ log() ]----------------------------------------------------------
// #DEBUG_START
function log( message ) {
if (win.console) {
win.console.log(message);
}
};
// #DEBUG_END
// --[ trim() ]---------------------------------------------------------
// removes leading, trailing whitespace from a string
function trim( text ) {
return text.replace(RE_TIDY_TRIM_WHITESPACE, PLACEHOLDER_STRING);
};
// --[ normalizeWhitespace() ]------------------------------------------
// removes leading, trailing and consecutive whitespace from a string
function normalizeWhitespace( text ) {
return trim(text).replace(RE_TIDY_CONSECUTIVE_WHITESPACE, SPACE_STRING);
};
// --[ normalizeSelectorWhitespace() ]----------------------------------
// tidies whitespace around selector brackets and combinators
function normalizeSelectorWhitespace( selectorText ) {
return normalizeWhitespace(selectorText.
replace(RE_TIDY_TRAILING_WHITESPACE, PLACEHOLDER_STRING).
replace(RE_TIDY_LEADING_WHITESPACE, PLACEHOLDER_STRING)
);
};
// --[ toggleElementClass() ]-------------------------------------------
// toggles a single className on an element
function toggleElementClass( elm, className, on ) {
var oldClassName = elm.className;
var newClassName = toggleClass(oldClassName, className, on);
if (newClassName != oldClassName) {
elm.className = newClassName;
elm.parentNode.className += EMPTY_STRING;
}
};
// --[ toggleClass() ]--------------------------------------------------
// adds / removes a className from a string of classNames. Used to
// manage multiple class changes without forcing a DOM redraw
function toggleClass( classList, className, on ) {
var re = RegExp("(^|\\s)" + className + "(\\s|$)");
var classExists = re.test(classList);
if (on) {
return classExists ? classList : classList + SPACE_STRING + className;
} else {
return classExists ? trim(classList.replace(re, PLACEHOLDER_STRING)) : classList;
}
};
// --[ addEvent() ]-----------------------------------------------------
function addEvent(elm, eventName, eventHandler) {
elm.attachEvent("on" + eventName, eventHandler);
};
// --[ getXHRObject() ]-------------------------------------------------
function getXHRObject()
{
if (win.XMLHttpRequest) {
return new XMLHttpRequest;
}
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) {
return null;
}
};
// --[ loadStyleSheet() ]-----------------------------------------------
function loadStyleSheet( url ) {
xhr.open("GET", url, false);
xhr.send();
return (xhr.status==200) ? xhr.responseText : EMPTY_STRING;
};
// --[ resolveUrl() ]---------------------------------------------------
// Converts a URL fragment to a fully qualified URL using the specified
// context URL. Returns null if same-origin policy is broken
function resolveUrl( url, contextUrl ) {
function getProtocolAndHost( url ) {
return url.substring(0, url.indexOf("/", 8));
};
// absolute path
if (/^https?:\/\//i.test(url)) {
return getProtocolAndHost(contextUrl) == getProtocolAndHost(url) ? url : null;
}
// root-relative path
if (url.charAt(0)=="/") {
return getProtocolAndHost(contextUrl) + url;
}
// relative path
var contextUrlPath = contextUrl.split(/[?#]/)[0]; // ignore query string in the contextUrl
if (url.charAt(0) != "?" && contextUrlPath.charAt(contextUrlPath.length - 1) != "/") {
contextUrlPath = contextUrlPath.substring(0, contextUrlPath.lastIndexOf("/") + 1);
}
return contextUrlPath + url;
};
// --[ parseStyleSheet() ]----------------------------------------------
// Downloads the stylesheet specified by the URL, removes it's comments
// and recursivly replaces @import rules with their contents, ultimately
// returning the full cssText.
function parseStyleSheet( url ) {
if (url) {
return loadStyleSheet(url).replace(RE_COMMENT, EMPTY_STRING).
replace(RE_IMPORT, function( match, quoteChar, importUrl, quoteChar2, importUrl2 ) {
return parseStyleSheet(resolveUrl(importUrl || importUrl2, url));
}).
replace(RE_ASSET_URL, function( match, quoteChar, assetUrl ) {
quoteChar = quoteChar || EMPTY_STRING;
return " url(" + quoteChar + resolveUrl(assetUrl, url) + quoteChar + ") ";
});
}
return EMPTY_STRING;
};
// --[ init() ]---------------------------------------------------------
function init() {
// honour the <base> tag
var url, stylesheet;
var baseTags = doc.getElementsByTagName("BASE");
var baseUrl = (baseTags.length > 0) ? baseTags[0].href : doc.location.href;
/* Note: This code prevents IE from freezing / crashing when using
@font-face .eot files but it modifies the <head> tag and could
trigger the IE stylesheet limit. It will also cause FOUC issues.
If you choose to use it, make sure you comment out the for loop
directly below this comment.
var head = doc.getElementsByTagName("head")[0];
for (var c=doc.styleSheets.length-1; c>=0; c--) {
stylesheet = doc.styleSheets[c]
head.appendChild(doc.createElement("style"))
var patchedStylesheet = doc.styleSheets[doc.styleSheets.length-1];
if (stylesheet.href != EMPTY_STRING) {
url = resolveUrl(stylesheet.href, baseUrl)
if (url) {
patchedStylesheet.cssText = patchStyleSheet( parseStyleSheet( url ) )
stylesheet.disabled = true
setTimeout( function () {
stylesheet.owningElement.parentNode.removeChild(stylesheet.owningElement)
})
}
}
}
*/
for (var c = 0; c < doc.styleSheets.length; c++) {
stylesheet = doc.styleSheets[c]
if (stylesheet.href != EMPTY_STRING) {
url = resolveUrl(stylesheet.href, baseUrl);
if (url) {
stylesheet.cssText = patchStyleSheet( parseStyleSheet( url ) );
}
}
}
// :enabled & :disabled polling script (since we can't hook
// onpropertychange event when an element is disabled)
if (enabledWatchers.length > 0) {
setInterval( function() {
for (var c = 0, cl = enabledWatchers.length; c < cl; c++) {
var e = enabledWatchers[c];
if (e.disabled !== e.$disabled) {
if (e.disabled) {
e.disabled = false;
e.$disabled = true;
e.disabled = true;
}
else {
e.$disabled = e.disabled;
}
}
}
},250)
}
};
// Bind selectivizr to the ContentLoaded event.
ContentLoaded(win, function() {
// Determine the "best fit" selector engine
for (var engine in selectorEngines) {
var members, member, context = win;
if (win[engine]) {
members = selectorEngines[engine].replace("*", engine).split(".");
while ((member = members.shift()) && (context = context[member])) {}
if (typeof context == "function") {
selectorMethod = context;
init();
return;
}
}
}
});
/*!
* ContentLoaded.js by Diego Perini, modified for IE<9 only (to save space)
*
* Author: Diego Perini (diego.perini at gmail.com)
* Summary: cross-browser wrapper for DOMContentLoaded
* Updated: 20101020
* License: MIT
* Version: 1.2
*
* URL:
* http://javascript.nwbox.com/ContentLoaded/
* http://javascript.nwbox.com/ContentLoaded/MIT-LICENSE
*
*/
// @w window reference
// @f function reference
function ContentLoaded(win, fn) {
var done = false, top = true,
init = function(e) {
if (e.type == "readystatechange" && doc.readyState != "complete") return;
(e.type == "load" ? win : doc).detachEvent("on" + e.type, init, false);
if (!done && (done = true)) fn.call(win, e.type || e);
},
poll = function() {
try { root.doScroll("left"); } catch(e) { setTimeout(poll, 50); return; }
init('poll');
};
if (doc.readyState == "complete") fn.call(win, EMPTY_STRING);
else {
if (doc.createEventObject && root.doScroll) {
try { top = !win.frameElement; } catch(e) { }
if (top) poll();
}
addEvent(doc,"readystatechange", init);
addEvent(win,"load", init);
}
};
})(this);
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas, David Knight. Dual MIT/BSD license */
window.matchMedia || (window.matchMedia = function() {
"use strict";
// For browsers that support matchMedium api such as IE 9 and webkit
var styleMedia = (window.styleMedia || window.media);
// For those that don't support matchMedium
if (!styleMedia) {
var style = document.createElement('style'),
script = document.getElementsByTagName('script')[0],
info = null;
style.type = 'text/css';
style.id = 'matchmediajs-test';
script.parentNode.insertBefore(style, script);
// 'style.currentStyle' is used by IE <= 8 and 'window.getComputedStyle' for all other browsers
info = ('getComputedStyle' in window) && window.getComputedStyle(style, null) || style.currentStyle;
styleMedia = {
matchMedium: function(media) {
var text = '@media ' + media + '{ #matchmediajs-test { width: 1px; } }';
// 'style.styleSheet' is used by IE <= 8 and 'style.textContent' for all other browsers
if (style.styleSheet) {
style.styleSheet.cssText = text;
} else {
style.textContent = text;
}
// Test if media query is true or false
return info.width === '1px';
}
};
}
return function(media) {
return {
matches: styleMedia.matchMedium(media || 'all'),
media: media || 'all'
};
};
}());
/*! matchMedia() polyfill addListener/removeListener extension. Author & copyright (c) 2012: Scott Jehl. Dual MIT/BSD license */
(function(){
// Bail out for browsers that have addListener support
if (window.matchMedia && window.matchMedia('all').addListener) {
return false;
}
var localMatchMedia = window.matchMedia,
hasMediaQueries = localMatchMedia('only all').matches,
isListening = false,
timeoutID = 0, // setTimeout for debouncing 'handleChange'
queries = [], // Contains each 'mql' and associated 'listeners' if 'addListener' is used
handleChange = function(evt) {
// Debounce
clearTimeout(timeoutID);
timeoutID = setTimeout(function() {
for (var i = 0, il = queries.length; i < il; i++) {
var mql = queries[i].mql,
listeners = queries[i].listeners || [],
matches = localMatchMedia(mql.media).matches;
// Update mql.matches value and call listeners
// Fire listeners only if transitioning to or from matched state
if (matches !== mql.matches) {
mql.matches = matches;
for (var j = 0, jl = listeners.length; j < jl; j++) {
listeners[j].call(window, mql);
}
}
}
}, 30);
};
window.matchMedia = function(media) {
var mql = localMatchMedia(media),
listeners = [],
index = 0;
mql.addListener = function(listener) {
// Changes would not occur to css media type so return now (Affects IE <= 8)
if (!hasMediaQueries) {
return;
}
// Set up 'resize' listener for browsers that support CSS3 media queries (Not for IE <= 8)
// There should only ever be 1 resize listener running for performance
if (!isListening) {
isListening = true;
window.addEventListener('resize', handleChange, true);
}
// Push object only if it has not been pushed already
if (index === 0) {
index = queries.push({
mql : mql,
listeners : listeners
});
}
listeners.push(listener);
};
mql.removeListener = function(listener) {
for (var i = 0, il = listeners.length; i < il; i++){
if (listeners[i] === listener){
listeners.splice(i, 1);
}
}
};
return mql;
};
}());
/*!
* enquire.js v2.1.0 - Awesome Media Queries in JavaScript
* Copyright (c) 2013 Nick Williams - http://wicky.nillia.ms/enquire.js
* License: MIT (http://www.opensource.org/licenses/mit-license.php)
*/
;(function (name, context, factory) {
var matchMedia = context.matchMedia;
if (typeof module !== 'undefined' && module.exports) {
module.exports = factory(matchMedia);
}
else if (typeof define === 'function' && define.amd) {
define(function() {
return (context[name] = factory(matchMedia));
});
}
else {
context[name] = factory(matchMedia);
}
}('enquire', this, function (matchMedia) {
'use strict';
/*jshint unused:false */
/**
* Helper function for iterating over a collection
*
* @param collection
* @param fn
*/
function each(collection, fn) {
var i = 0,
length = collection.length,
cont;
for(i; i < length; i++) {
cont = fn(collection[i], i);
if(cont === false) {
break; //allow early exit
}
}
}
/**
* Helper function for determining whether target object is an array
*
* @param target the object under test
* @return {Boolean} true if array, false otherwise
*/
function isArray(target) {
return Object.prototype.toString.apply(target) === '[object Array]';
}
/**
* Helper function for determining whether target object is a function
*
* @param target the object under test
* @return {Boolean} true if function, false otherwise
*/
function isFunction(target) {
return typeof target === 'function';
}
/**
* Delegate to handle a media query being matched and unmatched.
*
* @param {object} options
* @param {function} options.match callback for when the media query is matched
* @param {function} [options.unmatch] callback for when the media query is unmatched
* @param {function} [options.setup] one-time callback triggered the first time a query is matched
* @param {boolean} [options.deferSetup=false] should the setup callback be run immediately, rather than first time query is matched?
* @constructor
*/
function QueryHandler(options) {
this.options = options;
!options.deferSetup && this.setup();
}
QueryHandler.prototype = {
/**
* coordinates setup of the handler
*
* @function
*/
setup : function() {
if(this.options.setup) {
this.options.setup();
}
this.initialised = true;
},
/**
* coordinates setup and triggering of the handler
*
* @function
*/
on : function() {
!this.initialised && this.setup();
this.options.match && this.options.match();
},
/**
* coordinates the unmatch event for the handler
*
* @function
*/
off : function() {
this.options.unmatch && this.options.unmatch();
},
/**
* called when a handler is to be destroyed.
* delegates to the destroy or unmatch callbacks, depending on availability.
*
* @function
*/
destroy : function() {
this.options.destroy ? this.options.destroy() : this.off();
},
/**
* determines equality by reference.
* if object is supplied compare options, if function, compare match callback
*
* @function
* @param {object || function} [target] the target for comparison
*/
equals : function(target) {
return this.options === target || this.options.match === target;
}
};
/**
* Represents a single media query, manages it's state and registered handlers for this query
*
* @constructor
* @param {string} query the media query string
* @param {boolean} [isUnconditional=false] whether the media query should run regardless of whether the conditions are met. Primarily for helping older browsers deal with mobile-first design
*/
function MediaQuery(query, isUnconditional) {
this.query = query;
this.isUnconditional = isUnconditional;
this.handlers = [];
this.mql = matchMedia(query);
var self = this;
this.listener = function(mql) {
self.mql = mql;
self.assess();
};
this.mql.addListener(this.listener);
}
MediaQuery.prototype = {
/**
* add a handler for this query, triggering if already active
*
* @param {object} handler
* @param {function} handler.match callback for when query is activated
* @param {function} [handler.unmatch] callback for when query is deactivated
* @param {function} [handler.setup] callback for immediate execution when a query handler is registered
* @param {boolean} [handler.deferSetup=false] should the setup callback be deferred until the first time the handler is matched?
*/
addHandler : function(handler) {
var qh = new QueryHandler(handler);
this.handlers.push(qh);
this.matches() && qh.on();
},
/**
* removes the given handler from the collection, and calls it's destroy methods
*
* @param {object || function} handler the handler to remove
*/
removeHandler : function(handler) {
var handlers = this.handlers;
each(handlers, function(h, i) {
if(h.equals(handler)) {
h.destroy();
return !handlers.splice(i,1); //remove from array and exit each early
}
});
},
/**
* Determine whether the media query should be considered a match
*
* @return {Boolean} true if media query can be considered a match, false otherwise
*/
matches : function() {
return this.mql.matches || this.isUnconditional;
},
/**
* Clears all handlers and unbinds events
*/
clear : function() {
each(this.handlers, function(handler) {
handler.destroy();
});
this.mql.removeListener(this.listener);
this.handlers.length = 0; //clear array
},
/*
* Assesses the query, turning on all handlers if it matches, turning them off if it doesn't match
*/
assess : function() {
var action = this.matches() ? 'on' : 'off';
each(this.handlers, function(handler) {
handler[action]();
});
}
};
/**
* Allows for registration of query handlers.
* Manages the query handler's state and is responsible for wiring up browser events
*
* @constructor
*/
function MediaQueryDispatch () {
if(!matchMedia) {
throw new Error('matchMedia not present, legacy browsers require a polyfill');
}
this.queries = {};
this.browserIsIncapable = !matchMedia('only all').matches;
}
MediaQueryDispatch.prototype = {
/**
* Registers a handler for the given media query
*
* @param {string} q the media query
* @param {object || Array || Function} options either a single query handler object, a function, or an array of query handlers
* @param {function} options.match fired when query matched
* @param {function} [options.unmatch] fired when a query is no longer matched
* @param {function} [options.setup] fired when handler first triggered
* @param {boolean} [options.deferSetup=false] whether setup should be run immediately or deferred until query is first matched
* @param {boolean} [shouldDegrade=false] whether this particular media query should always run on incapable browsers
*/
register : function(q, options, shouldDegrade) {
var queries = this.queries,
isUnconditional = shouldDegrade && this.browserIsIncapable;
if(!queries[q]) {
queries[q] = new MediaQuery(q, isUnconditional);
}
//normalise to object in an array
if(isFunction(options)) {
options = { match : options };
}
if(!isArray(options)) {
options = [options];
}
each(options, function(handler) {
queries[q].addHandler(handler);
});
return this;
},
/**
* unregisters a query and all it's handlers, or a specific handler for a query
*
* @param {string} q the media query to target
* @param {object || function} [handler] specific handler to unregister
*/
unregister : function(q, handler) {
var query = this.queries[q];
if(query) {
if(handler) {
query.removeHandler(handler);
}
else {
query.clear();
delete this.queries[q];
}
}
return this;
}
};
return new MediaQueryDispatch();
}));
/**
* Magento Enterprise Edition
*
* NOTICE OF LICENSE
*
* This source file is subject to the Magento Enterprise Edition End User License Agreement
* that is bundled with this package in the file LICENSE_EE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.magento.com/license/enterprise-edition
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category design
* @package rwd_default
* @copyright Copyright (c) 2006-2014 X.commerce, Inc. (http://www.magento.com)
* @license http://www.magento.com/license/enterprise-edition
*/
// =============================================
// Primary Break Points
// =============================================
// These should be used with the bp (max-width, xx) mixin
// where a min-width is used, remember to +1 to break correctly
// If these are changed, they must also be updated in _var.scss
var bp = {
xsmall: 479,
small: 599,
medium: 770,
iPadMedium: 900,
large: 900,
xlarge: 1199
};
// ==============================================
// Search
// ==============================================
/**
* Implements a custom validation style for the search form. When the form is invalidly submitted, the validation-failed
* class gets added to the input, but the "This is a required field." text does not display
*/
Varien.searchForm.prototype.initialize = function (form, field, emptyText) {
this.form = $(form);
this.field = $(field);
this.emptyText = emptyText;
Event.observe(this.form, 'submit', this.submit.bind(this));
Event.observe(this.field, 'change', this.change.bind(this));
Event.observe(this.field, 'focus', this.focus.bind(this));
Event.observe(this.field, 'blur', this.blur.bind(this));
this.blur();
};
Varien.searchForm.prototype.submit = function (event) {
if (this.field.value === this.emptyText || this.field.value === '') {
Event.stop(event);
this.field.addClassName('validation-failed');
this.field.focus();
return false;
}
return true;
};
Varien.searchForm.prototype.change = function (event) {
if (
this.field.value !== this.emptyText
&& this.field.value !== ''
&& this.field.hasClassName('validation-failed')
) {
this.field.removeClassName('validation-failed');
}
};
Varien.searchForm.prototype.blur = function (event) {
if (this.field.hasClassName('validation-failed')) {
this.field.removeClassName('validation-failed');
}
};
// ==============================================
// Pointer abstraction
// ==============================================
/**
* This class provides an easy and abstracted mechanism to determine the
* best pointer behavior to use -- that is, is the user currently interacting
* with their device in a touch manner, or using a mouse.
*
* Since devices may use either touch or mouse or both, there is no way to
* know the user's preferred pointer type until they interact with the site.
*
* To accommodate this, this class provides a method and two events
* to determine the user's preferred pointer type.
*
* - getPointer() returns the last used pointer type, or, if the user has
* not yet interacted with the site, falls back to a Modernizr test.
*
* - The mouse-detected event is triggered on the window object when the user
* is using a mouse pointer input, or has switched from touch to mouse input.
* It can be observed in this manner: $j(window).on('mouse-detected', function(event) { // custom code });
*
* - The touch-detected event is triggered on the window object when the user
* is using touch pointer input, or has switched from mouse to touch input.
* It can be observed in this manner: $j(window).on('touch-detected', function(event) { // custom code });
*/
var PointerManager = {
MOUSE_POINTER_TYPE: 'mouse',
TOUCH_POINTER_TYPE: 'touch',
POINTER_EVENT_TIMEOUT_MS: 500,
standardTouch: false,
touchDetectionEvent: null,
lastTouchType: null,
pointerTimeout: null,
pointerEventLock: false,
getPointerEventsSupported: function () {
return this.standardTouch;
},
getPointerEventsInputTypes: function () {
if (window.navigator.pointerEnabled) { //IE 11+
//return string values from http://msdn.microsoft.com/en-us/library/windows/apps/hh466130.aspx
return {
MOUSE: 'mouse',
TOUCH: 'touch',
PEN: 'pen'
};
} else if (window.navigator.msPointerEnabled) { //IE 10
//return numeric values from http://msdn.microsoft.com/en-us/library/windows/apps/hh466130.aspx
return {
MOUSE: 0x00000004,
TOUCH: 0x00000002,
PEN: 0x00000003
};
} else { //other browsers don't support pointer events
return {}; //return empty object
}
},
/**
* If called before init(), get best guess of input pointer type
* using Modernizr test.
* If called after init(), get current pointer in use.
*/
getPointer: function () {
// On iOS devices, always default to touch, as this.lastTouchType will intermittently return 'mouse' if
// multiple touches are triggered in rapid succession in Safari on iOS
if (Modernizr.ios) {
return this.TOUCH_POINTER_TYPE;
}
if (this.lastTouchType) {
return this.lastTouchType;
}
return Modernizr.touch ? this.TOUCH_POINTER_TYPE : this.MOUSE_POINTER_TYPE;
},
setPointerEventLock: function () {
this.pointerEventLock = true;
},
clearPointerEventLock: function () {
this.pointerEventLock = false;
},
setPointerEventLockTimeout: function () {
var that = this;
if (this.pointerTimeout) {
clearTimeout(this.pointerTimeout);
}
this.setPointerEventLock();
this.pointerTimeout = setTimeout(function () {
that.clearPointerEventLock();
}, this.POINTER_EVENT_TIMEOUT_MS);
},
triggerMouseEvent: function (originalEvent) {
if (this.lastTouchType === this.MOUSE_POINTER_TYPE) {
return; //prevent duplicate events
}
this.lastTouchType = this.MOUSE_POINTER_TYPE;
$j(window).trigger('mouse-detected', originalEvent);
},
triggerTouchEvent: function (originalEvent) {
if (this.lastTouchType === this.TOUCH_POINTER_TYPE) {
return; //prevent duplicate events
}
this.lastTouchType = this.TOUCH_POINTER_TYPE;
$j(window).trigger('touch-detected', originalEvent);
},
initEnv: function () {
if (window.navigator.pointerEnabled) {
this.standardTouch = true;
this.touchDetectionEvent = 'pointermove';
} else if (window.navigator.msPointerEnabled) {
this.standardTouch = true;
this.touchDetectionEvent = 'MSPointerMove';
} else {
this.touchDetectionEvent = 'touchstart';
}
},
wirePointerDetection: function () {
var that = this;
if (this.standardTouch) { //standard-based touch events. Wire only one event.
//detect pointer event
$j(window).on(this.touchDetectionEvent, function (e) {
switch (e.originalEvent.pointerType) {
case that.getPointerEventsInputTypes().MOUSE:
that.triggerMouseEvent(e);
break;
case that.getPointerEventsInputTypes().TOUCH:
case that.getPointerEventsInputTypes().PEN:
// intentionally group pen and touch together
that.triggerTouchEvent(e);
break;
}
});
} else { //non-standard touch events. Wire touch and mouse competing events.
//detect first touch
$j(window).on(this.touchDetectionEvent, function (e) {
if (that.pointerEventLock) {
return;
}
that.setPointerEventLockTimeout();
that.triggerTouchEvent(e);
});
//detect mouse usage
$j(document).on('mouseover', function (e) {
if (that.pointerEventLock) {
return;
}
that.setPointerEventLockTimeout();
that.triggerMouseEvent(e);
});
}
},
init: function () {
this.initEnv();
this.wirePointerDetection();
}
};
/**
* This class manages the main navigation and supports infinite nested
* menus which support touch, mouse click, and hover correctly.
*
* The following is the expected behavior:
*
* - Hover with an actual mouse should expand the menu (at any level of nesting)
* - Click with an actual mouse will follow the link, regardless of any children
* - Touch will follow links without children, and toggle submenus of links with children
*
* Caveats:
* - According to Mozilla's documentation (https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Touch_events),
* Firefox has disabled Apple-style touch events on desktop, so desktop devices using Firefox will not support
* the desired touch behavior.
*/
var MenuManager = {
// These variables are used to detect incorrect touch / mouse event order
mouseEnterEventObserved: false,
touchEventOrderIncorrect: false,
cancelNextTouch: false,
/**
* This class manages touch scroll detection
*/
TouchScroll: {
/**
* Touch which moves the screen vertically more than
* this many pixels will be considered a scroll.
*/
TOUCH_SCROLL_THRESHOLD: 20,
touchStartPosition: null,
/**
* Note scroll position so that scroll action can be detected later.
* Should probably be called on touchstart (or similar) event.
*/
reset: function () {
this.touchStartPosition = $j(window).scrollTop();
},
/**
* Determines if touch was actually a scroll. Should probably be checked
* on touchend (or similar) event.
* @returns {boolean}
*/
shouldCancelTouch: function () {
if (this.touchStartPosition == null) {
return false;
}
var scroll = $j(window).scrollTop() - this.touchStartPosition;
return Math.abs(scroll) > this.TOUCH_SCROLL_THRESHOLD;
}
},
/**
* Determines if small screen behavior should be used.
*
* @returns {boolean}
*/
useSmallScreenBehavior: function () {
return Modernizr.mq('screen and (max-width:' + bp.large + 'px)');
},
/**
* Toggles a given menu item's visibility.
* On large screens, also closes sibling and children of sibling menus.
*
* @param target
*/
toggleMenuVisibility: function (target) {
var link = $j(target);
var li = link.closest('li');
if (!this.useSmallScreenBehavior()) {
// remove menu-active from siblings and children of siblings
li.siblings()
.removeClass('menu-active')
.find('li')
.removeClass('menu-active');
//remove menu-active from children
li.find('li.menu-active').removeClass('menu-active');
}
//toggle current item's active state
li.toggleClass('menu-active');
},
// --------------------------------------------
// Initialization methods
//
/**
* Initialize MenuManager and wire all required events.
* Should only be called once.
*
*/
init: function () {
this.wirePointerEvents();
},
/**
* This method observes an absurd number of events
* depending on the capabilities of the current browser
* to implement expected header navigation functionality.
*
* The goal is to separate interactions into four buckets:
* - pointer enter using an actual mouse
* - pointer leave using an actual mouse
* - pointer down using an actual mouse
* - pointer down using touch
*
* Browsers supporting PointerEvent events will use these
* to differentiate pointer types.
*
* Browsers supporting Apple-style will use those events
* along with mouseenter / mouseleave to emulate pointer events.
*/
wirePointerEvents: function () {
var that = this;
var pointerTarget = $j('#nav a.has-children');
var hoverTarget = $j('#nav li');
if (PointerManager.getPointerEventsSupported()) {
// pointer events supported, so observe those type of events
var enterEvent = window.navigator.pointerEnabled ? 'pointerenter' : 'mouseenter';
var leaveEvent = window.navigator.pointerEnabled ? 'pointerleave' : 'mouseleave';
var fullPointerSupport = window.navigator.pointerEnabled;
hoverTarget.on(enterEvent, function (e) {
if (e.originalEvent.pointerType === undefined // Browsers with partial PointerEvent support don't provide pointer type
|| e.originalEvent.pointerType === PointerManager.getPointerEventsInputTypes().MOUSE) {
if (fullPointerSupport) {
that.mouseEnterAction(e, this);
} else {
that.PartialPointerEventsSupport.mouseEnterAction(e, this);
}
}
}).on(leaveEvent, function (e) {
if (e.originalEvent.pointerType === undefined // Browsers with partial PointerEvent support don't provide pointer type
|| e.originalEvent.pointerType === PointerManager.getPointerEventsInputTypes().MOUSE) {
if (fullPointerSupport) {
that.mouseLeaveAction(e, this);
} else {
that.PartialPointerEventsSupport.mouseLeaveAction(e, this);
}
}
});
if (!fullPointerSupport) {
//click event doesn't have pointer type on it.
//observe MSPointerDown to set pointer type for click to find later
pointerTarget.on('MSPointerDown', function (e) {
$j(this).data('pointer-type', e.originalEvent.pointerType);
});
}
pointerTarget.on('click', function (e) {
var pointerType = fullPointerSupport ? e.originalEvent.pointerType : $j(this).data('pointer-type');
if (pointerType === undefined || pointerType === PointerManager.getPointerEventsInputTypes().MOUSE) {
that.mouseClickAction(e, this);
} else {
if (fullPointerSupport) {
that.touchAction(e, this);
} else {
that.PartialPointerEventsSupport.touchAction(e, this);
}
}
$j(this).removeData('pointer-type'); // clear pointer type hint from target, if any
});
} else {
//pointer events not supported, use Apple-style events to simulate
hoverTarget.on('mouseenter', function (e) {
// Touch events should cancel this event if a touch pointer is used.
// Record that this method has fired so that erroneous following
// touch events (if any) can respond accordingly.
that.mouseEnterEventObserved = true;
that.cancelNextTouch = true;
that.mouseEnterAction(e, this);
}).on('mouseleave', function (e) {
that.mouseLeaveAction(e, this);
});
$j(window).on('touchstart', function (e) {
if (that.mouseEnterEventObserved) {
// If mouse enter observed before touch, then device touch
// event order is incorrect.
that.touchEventOrderIncorrect = true;
that.mouseEnterEventObserved = false; // Reset test
}
// Reset TouchScroll in order to detect scroll later.
that.TouchScroll.reset();
});
pointerTarget.on('touchend', function (e) {
$j(this).data('was-touch', true); // Note that element was invoked by touch pointer
e.preventDefault(); // Prevent mouse compatibility events from firing where possible
if (that.TouchScroll.shouldCancelTouch()) {
return; // Touch was a scroll -- don't do anything else
}
if (that.touchEventOrderIncorrect) {
that.PartialTouchEventsSupport.touchAction(e, this);
} else {
that.touchAction(e, this);
}
}).on('click', function (e) {
if ($j(this).data('was-touch')) { // Event invoked after touch
e.preventDefault(); // Prevent following link
return; // Prevent other behavior
}
that.mouseClickAction(e, this);
});
}
},
// --------------------------------------------
// Behavior "buckets"
//
/**
* Browsers with incomplete PointerEvent support (such as IE 10)
* require special event management. This collection of methods
* accommodate such browsers.
*/
PartialPointerEventsSupport: {
/**
* Without proper pointerenter / pointerleave / click pointerType support,
* we have to use mouseenter events. These end up triggering
* lots of mouseleave events that can be misleading.
*
* Each touch mouseenter and click event that ends up triggering
* an undesired mouseleave increments this lock variable.
*
* Mouseleave events are cancelled if this variable is > 0,
* and then the variable is decremented regardless.
*/
mouseleaveLock: 0,
/**
* Handles mouse enter behavior, but if using touch,
* toggle menus in the absence of full PointerEvent support.
*
* @param event
* @param target
*/
mouseEnterAction: function (event, target) {
if (MenuManager.useSmallScreenBehavior()) {
// fall back to normal method behavior
MenuManager.mouseEnterAction(event, target);
return;
}
event.stopPropagation();
var jtarget = $j(target);
if (!jtarget.hasClass('level0')) {
this.mouseleaveLock = jtarget.parents('li').length + 1;
}
MenuManager.toggleMenuVisibility(target);
},
/**
* Handles mouse leave behaivor, but obeys the mouseleaveLock
* to allow undesired mouseleave events to be cancelled.
*
* @param event
* @param target
*/
mouseLeaveAction: function (event, target) {
if (MenuManager.useSmallScreenBehavior()) {
// fall back to normal method behavior
MenuManager.mouseLeaveAction(event, target);
return;
}
if (this.mouseleaveLock > 0) {
this.mouseleaveLock--;
return; // suppress duplicate mouseleave event after touch
}
$j(target).removeClass('menu-active'); //hide all menus
},
/**
* Does no work on its own, but increments mouseleaveLock
* to prevent following undesireable mouseleave events.
*
* @param event
* @param target
*/
touchAction: function (event, target) {
if (MenuManager.useSmallScreenBehavior()) {
// fall back to normal method behavior
MenuManager.touchAction(event, target);
return;
}
event.preventDefault(); // prevent following link
this.mouseleaveLock++;
}
},
/**
* Browsers with incomplete Apple-style touch event support
* (such as the legacy Android browser) sometimes fire
* touch events out of order. In particular, mouseenter may
* fire before the touch events. This collection of methods
* accommodate such browsers.
*/
PartialTouchEventsSupport: {
/**
* Toggles visibility of menu, unless suppressed by previous
* out of order mouseenter event.
*
* @param event
* @param target
*/
touchAction: function (event, target) {
if (MenuManager.cancelNextTouch) {
// Mouseenter has already manipulated the menu.
// Suppress this undesired touch event.
MenuManager.cancelNextTouch = false;
return;
}
MenuManager.toggleMenuVisibility(target);
}
},
/**
* On large screens, show menu.
* On small screens, do nothing.
*
* @param event
* @param target
*/
mouseEnterAction: function (event, target) {
if (this.useSmallScreenBehavior()) {
return; // don't do mouse enter functionality on smaller screens
}
$j(target).addClass('menu-active'); //show current menu
},
/**
* On large screens, hide menu.
* On small screens, do nothing.
*
* @param event
* @param target
*/
mouseLeaveAction: function (event, target) {
if (this.useSmallScreenBehavior()) {
return; // don't do mouse leave functionality on smaller screens
}
$j(target).removeClass('menu-active'); //hide all menus
},
/**
* On large screens, don't interfere so that browser will follow link.
* On small screens, toggle menu visibility.
*
* @param event
* @param target
*/
mouseClickAction: function (event, target) {
if (this.useSmallScreenBehavior()) {
event.preventDefault(); //don't follow link
this.toggleMenuVisibility(target); //instead, toggle visibility
}
},
/**
* Toggle menu visibility, and prevent event default to avoid
* undesired, duplicate, synthetic mouse events.
*
* @param event
* @param target
*/
touchAction: function (event, target) {
this.toggleMenuVisibility(target);
event.preventDefault();
}
};
// ==============================================
// UI Pattern - Toggle Content (tabs and accordions in one setup)
// ==============================================
var toggleContent = function () {
$j('.toggle-content').each(function () {
var wrapper = jQuery(this);
var hasTabs = wrapper.hasClass('tabs');
//var hasAccordion = wrapper.hasClass('accordion');
var startOpen = wrapper.hasClass('open');
var dl = wrapper.children('dl:first');
var dts = dl.children('dt');
var panes = dl.children('dd');
var groups = [dts, panes];
//Create a ul for tabs if necessary.
if (hasTabs) {
var ul = jQuery('<ul class="toggle-tabs"></ul>');
dts.each(function () {
var dt = jQuery(this);
var li = jQuery('<li></li>');
li.html(dt.html());
ul.append(li);
});
ul.insertBefore(dl);
var lis = ul.children();
groups.push(lis);
}
//Add "last" classes.
var i;
for (i = 0; i < groups.length; i++) {
groups[i].filter(':last').addClass('last');
}
function toggleClasses(clickedItem, group) {
var index = group.index(clickedItem);
var i;
for (i = 0; i < groups.length; i++) {
groups[i].removeClass('current');
groups[i].eq(index).addClass('current');
}
}
//Toggle on tab (dt) click.
dts.on('click', function (e) {
//They clicked the current dt to close it. Restore the wrapper to unclicked state.
if (jQuery(this).hasClass('current') && wrapper.hasClass('accordion-open')) {
wrapper.removeClass('accordion-open');
} else {
//They're clicking something new. Reflect the explicit user interaction.
wrapper.addClass('accordion-open');
}
toggleClasses(jQuery(this), dts);
});
//Toggle on tab (li) click.
if (hasTabs) {
lis.on('click', function (e) {
toggleClasses(jQuery(this), lis);
});
//Open the first tab.
lis.eq(0).trigger('click');
}
//Open the first accordion if desired.
if (startOpen) {
dts.eq(0).trigger('click');
}
});
}
// ==============================================
// jQuery Init
// ==============================================
// Use $j(document).ready() because Magento executes Prototype inline
$j(document).ready(function () {
// ==============================================
// Shared Vars
// ==============================================
// Document
Modernizr.addTest('ios', function () {
return navigator.userAgent.match(/(iPad|iPhone|iPod)/g);
});
//initialize pointer abstraction manager
PointerManager.init();
/* Wishlist Toggle Class */
$j('.change').click(function (e) {
$j(this).toggleClass('active');
e.stopPropagation();
});
$j(document).click(function (e) {
if (!$j(e.target).hasClass('.change')) {
$j('.change').removeClass('active');
}
});
// =============================================
// Skip Links
// =============================================
var skipContents = $j('.skip-content');
var skipLinks = $j('.skip-link');
skipLinks.on('click', function (e) {
e.preventDefault();
var self = $j(this);
// Use the data-target-element attribute, if it exists. Fall back to href.
var target = self.attr('data-target-element') ? self.attr('data-target-element') : self.attr('href');
// Get target element
var elem = $j(target);
// Check if stub is open
var isSkipContentOpen = elem.hasClass('skip-active');
var isSlidingDropdown = (target === '#header-account') || (target === '#header-cart');
if (isSlidingDropdown && (Modernizr.mq('screen and (min-width: ' + (bp.large + 1) + 'px)'))) {
// Hide all stubs
skipLinks.removeClass('skip-active');
$j('#header-account.skip-active, #header-cart.skip-active').slideUp(150, 'swing', function () {
$j(this).removeClass('skip-active');
$j(this).css('display', ''); // Remove styling leftovers from slideUp
});
// Toggle stubs
if (isSkipContentOpen) {
self.removeClass('skip-active');
} else {
self.addClass('skip-active');
elem.slideDown(150, 'swing', function () {
$j(this).addClass('skip-active');
$j(this).css('display', ''); // Remove styling leftovers from slideDown
});
}
} else {
// Hide all stubs
skipLinks.removeClass('skip-active');
skipContents.removeClass('skip-active');
// Toggle stubs
if (isSkipContentOpen) {
self.removeClass('skip-active');
} else {
self.addClass('skip-active');
elem.addClass('skip-active');
}
}
});
$j('#header-cart').on('click', '.skip-link-close', function (e) {
var parent = $j(this).parents('.skip-content');
var link = parent.siblings('.skip-link');
parent.removeClass('skip-active');
link.removeClass('skip-active');
e.preventDefault();
});
// ==============================================
// Header Menus
// ==============================================
// initialize menu
MenuManager.init();
// Prevent sub menus from spilling out of the window.
function preventMenuSpill() {
var windowWidth = $j(window).width();
$j('ul.level0').each(function () {
var ul = $j(this);
//Show it long enough to get info, then hide it.
ul.addClass('position-test');
ul.removeClass('spill');
var width = ul.outerWidth();
var offset = ul.offset().left;
ul.removeClass('position-test');
//Add the spill class if it will spill off the page.
if ((offset + width) > windowWidth) {
ul.addClass('spill');
}
});
}
preventMenuSpill();
$j(window).on('delayed-resize', preventMenuSpill);
// ==============================================
// Language Switcher
// ==============================================
// In order to display the language switcher next to the logo, we are moving the content at different viewports,
// rather than having duplicate markup or changing the design
enquire.register('(max-width: ' + bp.large + 'px)', {
match: function () {
$j('.store-language-container.mobile-view').prepend($j('.switcher-language'));
$j('.header-phone-number.mobile-view').prepend($j('.header-phone-number > a'));
},
unmatch: function () {
$j('.store-language-container.desktop-view').prepend($j('.switcher-language'));
$j('.header-phone-number.desktop-view').prepend($j('.header-phone-number > a'));
}
});
// ==============================================
// Enquire JS
// ==============================================
enquire.register('screen and (min-width: ' + (bp.large + 1) + 'px)', {
match: function () {
$j('.menu-active').removeClass('menu-active');
$j('.sub-menu-active').removeClass('sub-menu-active');
$j('.skip-active').removeClass('skip-active');
},
unmatch: function () {
$j('.menu-active').removeClass('menu-active');
$j('.sub-menu-active').removeClass('sub-menu-active');
$j('.skip-active').removeClass('skip-active');
}
});
// ==============================================
// UI Pattern - Media Switcher
// ==============================================
// Used to swap primary product photo from thumbnails.
var mediaListLinks = $j('.media-list').find('a');
var mediaPrimaryImage = $j('.primary-image').find('img');
if (mediaListLinks.length) {
mediaListLinks.on('click', function (e) {
e.preventDefault();
var self = $j(this);
mediaPrimaryImage.attr('src', self.attr('href'));
});
}
// ==============================================
// UI Pattern - ToggleSingle
// ==============================================
// Use this plugin to toggle the visibility of content based on a toggle link/element.
// This pattern differs from the accordion functionality in the Toggle pattern in that each toggle group acts
// independently of the others. It is named so as not to be confused with the Toggle pattern below
//
// This plugin requires a specific markup structure. The plugin expects a set of elements that it
// will use as the toggle link. It then hides all immediately following siblings and toggles the sibling's
// visibility when the toggle link is clicked.
//
// Example markup:
// <div class="block">//NOSONAR
// <div class="block-title">Trigger</div>//NOSONAR
// <div class="block-content">Content that should show when </div>//NOSONAR
// </div>//NOSONAR
//
// JS: jQuery('.block-title').toggleSingle(); //NOSONAR
//
// Options:
// destruct: defaults to false, but if true, the plugin will remove itself, display content, and remove event handlers
jQuery.fn.toggleSingle = function (options) {
// passing destruct: true allows
var settings = $j.extend({
destruct: false
}, options);
return this.each(function () {
if (!settings.destruct) {
$j(this).on('click', function () {
$j(this)
.toggleClass('active')
.next()
.toggleClass('no-display');
});
// Hide the content
$j(this).next().addClass('no-display');
} else {
// Remove event handler so that the toggle link can no longer be used
$j(this).off('click');
// Remove all classes that were added by this plugin
$j(this)
.removeClass('active')
.next()
.removeClass('no-display');
}
});
};
// ==============================================
// UI Pattern - Toggle Content (tabs and accordions in one setup)
// ==============================================
toggleContent();
// ==============================================
// Layered Navigation Block
// ==============================================
// On product list pages, we want to show the layered nav/category menu immediately above the product list.
// While it would make more sense to just move the .block-layered-nav block rather than .col-left-first
// (since other blocks can be inserted into left_first), it creates simpler code to move the entire
// .col-left-first block, so that is the approach we're taking
if ($j('.col-left-first > .block').length && $j('.category-products').length) {
enquire.register('screen and (max-width: ' + bp.iPadMedium + 'px)', {
match: function () {
$j('.col-left-first').insertBefore($j('.category-title'));
},
unmatch: function () {
// Move layered nav back to left column
$j('.col-left-first').insertBefore($j('.col-main'));
}
});
}
// ==============================================
// 3 column layout
// ==============================================
// On viewports smaller than 1000px, move the right column into the left column
if ($j('.main-container.col3-layout').length > 0) {
enquire.register('screen and (max-width: 1000px)', {
match: function () {
var rightColumn = $j('.col-right');
var colWrapper = $j('.col-wrapper');
rightColumn.appendTo(colWrapper);
},
unmatch: function () {
var rightColumn = $j('.col-right');
var main = $j('.main');
rightColumn.appendTo(main);
}
});
}
// ==============================================
// Block collapsing (on smaller viewports)
// ==============================================
var breakpointSize = bp.large;
if ($j('.catalog-category-view').length) {
breakpointSize = bp.iPadMedium + 125;
}
enquire.register('(max-width: ' + breakpointSize + 'px)', {
setup: function () {
this.toggleElements = $j(
// This selects the menu on the My Account and CMS pages
'.col-left-first .block:not(.block-layered-nav) .block-title, ' +
'.col-left-first .block-layered-nav .block-subtitle--filter, ' +
'.sidebar:not(.col-left-first) .block .block-title'
);
},
match: function () {
this.toggleElements.toggleSingle();
},
unmatch: function () {
this.toggleElements.toggleSingle({destruct: true});
}
});
// ==============================================
// OPC - Progress Block
// ==============================================
if ($j('body.checkout-onepage-index').length) {
enquire.register('(max-width: ' + bp.large + 'px)', {
match: function () {
$j('#checkout-step-review').prepend($j('#checkout-progress-wrapper'));
},
unmatch: function () {
$j('.col-right').prepend($j('#checkout-progress-wrapper'));
}
});
}
// ==============================================
// Checkout Cart - events
// ==============================================
if ($j('body.checkout-cart-index').length) {
$j('input[name^="cart"]').focus(function () {
$j(this).siblings('button').fadeIn();
});
}
// ==============================================
// Gift Registry Styles
// ==============================================
if ($j('.a-left').length) {
enquire.register('(max-width: ' + bp.large + 'px)', {
match: function () {
$j('.gift-info').each(function () {
$j(this).next('td').children('textarea').appendTo(this).children();
});
},
unmatch: function () {
$j('.left-note').each(function () {
$j(this).prev('td').children('textarea').appendTo(this).children();
});
}
});
}
// ==============================================
// Product Listing - Align action buttons/links
// ==============================================
// Since the number of columns per grid will vary based on the viewport size, the only way to align the action
// buttons/links is via JS
if ($j('.products-grid').length) {
var alignProductGridActions = function () {
// Loop through each product grid on the page
$j('.products-grid').each(function () {
var gridRows = []; // This will store an array per row
var tempRow = [];
productGridElements = $j(this).children('li');
productGridElements.each(function (index) {
// The JS ought to be agnostic of the specific CSS breakpoints, so we are dynamically checking to find
// each row by grouping all cells (eg, li elements) up until we find an element that is cleared.
// We are ignoring the first cell since it will always be cleared.
if ($j(this).css('clear') !== 'none' && index !== 0) {
gridRows.push(tempRow); // Add the previous set of rows to the main array
tempRow = []; // Reset the array since we're on a new row
}
tempRow.push(this);
// The last row will not contain any cells that clear that row, so we check to see if this is the last cell
// in the grid, and if so, we add its row to the array
if (productGridElements.length === (index + 1)) {
gridRows.push(tempRow);
}
});
$j.each(gridRows, function () {
var tallestProductInfo = 0;
$j.each(this, function () {
// Since this function is called every time the page is resized, we need to remove the min-height
// and bottom-padding so each cell can return to its natural size before being measured.
$j(this).find('.product-info').css({
'min-height': '',
'padding-bottom': ''
});
// We are checking the height of .product-info (rather than the entire li), because the images
// will not be loaded when this JS is run.
var productInfoHeight = $j(this).find('.product-info').height();
// Space above .actions element
var actionSpacing = 3;
// The height of the absolutely positioned .actions element
var actionHeight = $j(this).find('.product-info .actions').height();
// Add height of two elements. This is necessary since .actions is absolutely positioned and won't
// be included in the height of .product-info
var totalHeight = productInfoHeight + actionSpacing + actionHeight;
if (totalHeight > tallestProductInfo) {
tallestProductInfo = totalHeight;
}
// Set the bottom-padding to accommodate the height of the .actions element. Note: if .actions
// elements are of varying heights, they will not be aligned.
$j(this).find('.product-info').css('padding-bottom', actionHeight + 'px');
});
// Set the height of all .product-info elements in a row to the tallest height
$j.each(this, function () {
$j(this).find('.product-info').css('min-height', tallestProductInfo);
});
});
});
};
alignProductGridActions();
// Since the height of each cell and the number of columns per page may change when the page is resized, we are
// going to run the alignment function each time the page is resized.
$j(window).on('delayed-resize', function (e, resizeEvent) {
alignProductGridActions();
});
}
// ==============================================
// Generic, efficient window resize handler
// ==============================================
// Using setTimeout since Web-Kit and some other browsers call the resize function constantly upon window resizing.
var resizeTimer;
$j(window).resize(function (e) {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function () {
$j(window).trigger('delayed-resize', e);
}, 250);
});
});
// ==============================================
// PDP - image zoom - needs to be available outside document.ready scope
// ==============================================
var ProductMediaManager = {
IMAGE_ZOOM_THRESHOLD: 20,
imageWrapper: null,
destroyZoom: function () {
$j('.zoomContainer').remove();
$j('.product-image-gallery .gallery-image').removeData('elevateZoom');
},
createZoom: function (image) {
// Destroy since zoom shouldn't be enabled under certain conditions
ProductMediaManager.destroyZoom();
if (
// Don't use zoom on devices where touch has been used
PointerManager.getPointer() === PointerManager.TOUCH_POINTER_TYPE
// Don't use zoom when screen is small, or else zoom window shows outside body
|| Modernizr.mq('screen and (max-width:' + bp.large + 'px)')
) {
return; // zoom not enabled
}
if (image.length <= 0) { //no image found
return;
}
if (image[0].naturalWidth && image[0].naturalHeight) {
var widthDiff = image[0].naturalWidth - image.width() - ProductMediaManager.IMAGE_ZOOM_THRESHOLD;
var heightDiff = image[0].naturalHeight - image.height() - ProductMediaManager.IMAGE_ZOOM_THRESHOLD;
if (widthDiff < 0 && heightDiff < 0) {
//image not big enough
image.parents('.product-image').removeClass('zoom-available');
return;
} else {
image.parents('.product-image').addClass('zoom-available');
}
}
image.elevateZoom();
},
swapImage: function (targetImage) {
targetImage = $j(targetImage);
targetImage.addClass('gallery-image');
ProductMediaManager.destroyZoom();
var imageGallery = $j('.product-image-gallery');
if (targetImage[0].complete) { //image already loaded -- swap immediately
imageGallery.find('.gallery-image').removeClass('visible');
//move target image to correct place, in case it's necessary
imageGallery.append(targetImage);
//reveal new image
targetImage.addClass('visible');
//wire zoom on new image
ProductMediaManager.createZoom(targetImage);
} else { //need to wait for image to load
//add spinner
imageGallery.addClass('loading');
//move target image to correct place, in case it's necessary
imageGallery.append(targetImage);
//wait until image is loaded
imagesLoaded(targetImage, function () {
//remove spinner
imageGallery.removeClass('loading');
//hide old image
imageGallery.find('.gallery-image').removeClass('visible');
//reveal new image
targetImage.addClass('visible');
//wire zoom on new image
ProductMediaManager.createZoom(targetImage);
});
}
},
wireThumbnails: function () {
//trigger image change event on thumbnail click
$j('.product-image-thumbs .thumb-link').click(function (e) {
e.preventDefault();
var jlink = $j(this);
var target = $j('#image-' + jlink.data('image-index'));
ProductMediaManager.swapImage(target);
});
},
initZoom: function () {
ProductMediaManager.createZoom($j('.gallery-image.visible')); //set zoom on first image
},
init: function () {
ProductMediaManager.imageWrapper = $j('.product-img-box');
// Re-initialize zoom on viewport size change since resizing causes problems with zoom and since smaller
// viewport sizes shouldn't have zoom
$j(window).on('delayed-resize', function (e, resizeEvent) {
if ($j('.product-image-gallery').hasClass('zoom-enabled')) {
ProductMediaManager.initZoom();
}
});
if ($j('.product-image-gallery').hasClass('zoom-enabled')) {
ProductMediaManager.initZoom();
}
ProductMediaManager.wireThumbnails();
$j(document).trigger('product-media-loaded', ProductMediaManager);
}
};
$j(document).ready(function () {
ProductMediaManager.init();
});
movePriceBlock = function () {
$j('.product-view .add-to-cart-buttons:eq(0)').addClass('fixed-button');
$j('body > .wrapper').addClass('fix-wrapper');
if ($j('.product-options-bottom').length) {
$j('.price-info-container.mobile-view').append($j('.product-options-bottom .price-box')); //conf & bundle product
} else {
$j('.price-info-container.mobile-view').append($j('.price-info')); // simpre product
}
setTimeout(function () {
$j('.product-view .add-to-cart-buttons').not('.mini').find('.add-to-cart-placeholder .fn_addToCart').after($j('.price-info-container.mobile-view .price').clone());
$j('.add-to-cart-placeholder .price:eq(1)').hide();
}, 200);
}
unMovePriceBlock = function () {
$j('.add-to-cart-placeholder .price:eq(1)').show();
$j('body > .wrapper').removeClass('fix-wrapper');
$j('.product-view').find('.fixed-button').removeClass('fixed-button');
$j('.add-to-cart-buttons').not('.mini').find('.price').remove();
if ($j('.product-options-bottom').length) {
$j('.product-options-bottom').append($j('.price-info-container .price-box'));
} else {
$j('.add-to-box').append($j('.price-info'));
}
}
$j(document).ready(function () {
// ==============================================
// Cart Header Wrapper
// ==============================================
enquire.register('(max-width: ' + bp.large + 'px)', {
match: function () {
$j('.header-cart-wrapper.mobile-view').prepend($j('.account-cart-wrapper'));
$j('.account-cart-wrapper').prepend($j('.skip-cart'));
},
unmatch: function () {
$j('.skip-links').prepend($j('.account-cart-wrapper'));
$j('.header-minicart').prepend($j('.skip-cart'));
}
});
// ==============================================
// Catalog view mode move toolbar
// ==============================================
enquire.register('(max-width: ' + (bp.large + 125) + 'px)', {
match: function () {
$j('.col-left-first').append($j('.top-category-products'));
},
unmatch: function () {
$j('.col-main .products-sizes ').after($j('.top-category-products'));
}
});
// ==============================================
// Catalog applied filters
// ==============================================
enquire.register('(max-width: ' + bp.medium + 'px)', {
match: function () {
var element = document.createElement('div');
element.className = 'block-layered-nav-applied-filters';
$element = $j(element);
$element.append($j('.block-layered-nav .block-title'));
$element.append($j('.block-layered-nav .currently'));
$j('.col-left-first').after($element);
},
unmatch: function () {
$j('.block-layered-nav-applied-filters').remove();
$j('.col-left-first .block-layered-nav').prepend($j('.block-layered-nav-applied-filters .block-title'));
$j('.col-left-first .block-layered-nav .block-content').prepend($j('.block-layered-nav-applied-filters .currently'));
}
});
// ==============================================
// Catalog product price view mode
// ==============================================
enquire.register('(max-width: ' + bp.large + 'px)', {
match: function () {
movePriceBlock();
},
unmatch: function () {
unMovePriceBlock();
}
});
// ==============================================
// Catalog product toolbar view
// ==============================================
// enquire.register('(max-width: ' + bp.large + 'px)', {
// match: function () {
// $j('.col-left-first').after($j('.top-category-products'));
// },
// unmatch: function () {
// $j('.col-left-first').append($j('.top-category-products'));
// }
// });
/**
*
* @param string tagName
* @param string src
* @param bool reinit
* @returns void
*/
conditionallyAddBySource = function conditionallyAddBySource(tagName, src) {
var reinit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
tagName = tagName.toLowerCase();
var propToCheck = {script: 'src', link: 'href'}[tagName];
var element = document.querySelector(tagName + '[' + propToCheck + '$="' + src + '"]');
/**
* need for reinit js logic
*/
if (reinit && element && tagName == 'script') {
element.remove();
element = false;
}
if (!element) {
element = document.createElement(tagName);
if (tagName == 'link') {
element.setAttribute("type", "text/css");
element.setAttribute("rel", "stylesheet");
} else {
element.setAttribute("type", "text/javascript");
}
element[propToCheck] = src;
document.getElementsByTagName('head')[0].appendChild(element);
}
};
addToCartFromProductViewBlock = function (parentBlock) {
$j(parentBlock + ' .add-to-cart-placeholder').on('click', function () {
var qtyBox = $j(this).siblings('.qty-box');
$j(parentBlock + ' .qty-box').not(qtyBox).slideUp('fast');
qtyBox.slideToggle('fast');
});
$j(parentBlock + ' .qty-box').each(function () {
var $this = $j(this);
$this.find('td').on('click', function () {
$this.find('[id^=qty]').val($j(this).html()).change();
$this.find('.btn-cart').trigger('click');
});
});
$j(parentBlock + ' .add-to-cart-buttons').click(function (event) {
event.stopPropagation();
});
}
initCarouselProductSlick = function () {
$j('.products-carousel').slick({
centerMode: false,
infinite: false,
slidesToScroll: 1,
variableWidth: true,
swipeToSlide: true,
swipe: true,
responsive: [
{
breakpoint: 767,
settings: {
slidesToShow: 2,
slidesToScroll: 1,
infinite: true,
centerMode: true
}
},
{
breakpoint: 415,
settings: {
variableWidth: true,
slidesToShow: 1,
slidesToScroll: 1,
infinite: true,
centerMode: true
}
}
]
});
}
carouselProductClickFunction = function () {
$j('.products-carousel li').click(function (event) {
event.preventDefault();
var productId = 0;
$j(this).parents('.slick-track').find('li').removeClass('item-active');
if ($j(this).prop("tagName").toLowerCase() != 'li') {
$j(this).parents('li').addClass('item-active');
productId = $j(event.target).parents('li').data('product-id');
} else {
$j(this).addClass('item-active');
productId = $j(this).data('product-id');
}
var lang = $j('html').attr('lang');
$j.ajax({
url: location.origin + '/ru/' + lang + "/catalog/product/view/id/" + productId + '/?ver201712081101',
beforeSend: function () {
/**
* added required js to head
*/
conditionallyAddBySource('script', 'https://www.nespresso.com/ru/js/varien/product.js');
conditionallyAddBySource('script', 'https://www.nespresso.com/ru/skin/frontend/base/default/js/bundle.js');
conditionallyAddBySource('script', 'https://www.nespresso.com/ru/skin/frontend/rwd/default/js/lib/elevatezoom/jquery.elevateZoom-3.0.8.min.js');
conditionallyAddBySource('script', 'https://www.nespresso.com/ru/js/calendar/calendar.js');
if (!$j('.product-view').length) {
$j('.col-main').append("<div class='product-view'></div>");
}
$j('.product-view').addClass('loading');
}
}).done(function (data) {
$j('.product-view').remove();
var prod = $j(data).find('.col-main').html();
$j('.col-main').append(prod);
if (window.matchMedia("(max-width: 767px)").matches) {
movePriceBlock();
}
if ($j(prod).find('.product-additional-container').is(':parent')) {
conditionallyAddBySource('link', 'https://www.nespresso.com/ru/club/utils/crosssell/css/product-crosssell.css?ver281117');
conditionallyAddBySource('script', 'https://www.nespresso.com/ru/club/utils/crosssell/js/product-crosssell.min.js?ver281117', true);
}
setTimeout(function () {
addToCartFromProductViewBlock('.product-view');
ProductMediaManager.init();
toggleContent();
}, 500);
});
});
}
navigationFilterFunction = function () {
$j('#narrow-by-list a').click(function (event) {
event.preventDefault();
var el = $j(event.target);
if ($j(this).prop("tagName").toLowerCase() != 'li') {
value = $j(event.target).parents('li').data('filter-value');
el = $j(event.target).parents('li');
} else {
value = $j(this).data('filter-value');
}
// var targetValue = value[Object.keys(value)[0]];
var targetKey = Object.keys(value)[0];
var targetUrl = el.find('a').attr('href');
if (el.hasClass('active-filter')) {
el.removeClass('active-filter');
targetUrl = location.pathname + '/?mode=carousel'
} else {
el.parents('ol').find('li').removeClass('active-filter');
el.addClass('active-filter');
}
// change value
if (targetKey == 'price') {
$j('#narrow-by-list dd.price_filter .toggle-filters span').html($j(el.find('span')[0]).clone().html());
}
// change value
if (targetKey == 'cat') {
$j('#narrow-by-list dd.category_filter .toggle-filters span').html($j(el.find('span')[0]).clone().html());
}
$j.ajax({
url: targetUrl,
beforeSend: function () {
$j('.products-carousel').addClass('loading');
$j('body').removeClass('v_scrollLock');
$j('#narrow-by-list.mobile').removeClass('mobile').addClass('no-display');
}
}).done(function (data) {
$j('.products-carousel').slick('unslick');
var prod = $j(data).find('.col-main .category-products').html();
$j('.category-products').html(prod);
var filtersArr = ['category', 'capsule_product_aromatics', 'capsule_product_cupsizes', 'coffee_strength', 'price', 'color'];
filtersArr.forEach(function (item, i, arr) {
if (item == targetKey) {
return;
}
var toChange = $j(data).find('dd.' + item + '_filter').html();
$j('#narrow-by-list dd.' + item + '_filter').html(toChange);
});
$j('#narrow-by-list a').unbind('click');
$j('.toggle-filters').unbind('click');
$j('.products-carousel li').unbind('click');
Nespresso.layerNavigation();
navigationFilterFunction();
initCarouselProductSlick();
addToCartFromProductViewBlock('.category-products');
$j('.products-carousel').removeClass('init loading');
carouselProductClickFunction();
$j('.products-carousel .slick-current').addClass('item-active').click();
});
});
}
/*
* Product Capsules Carousel
*/
if ($j('.products-carousel').length) {
/**
* init slick
*/
initCarouselProductSlick();
/**
* init filters
*/
navigationFilterFunction();
$j('.products-carousel').removeClass('init');
carouselProductClickFunction();
// click on first item for view first product
$j('.products-carousel .slick-current').addClass('item-active').click();
}
$j('.catalog-category-view .block-subtitle--filter ').click(function (event) {
event.preventDefault();
$j(this).next().addClass('mobile').removeClass('no-display');
$j('body').addClass('v_scrollLock');
});
$j('#narrow-by-list .close-filter').click(function (event) {
event.preventDefault();
$j('body').removeClass('v_scrollLock');
$j('#narrow-by-list').removeClass('mobile').addClass('no-display');
});
});
/*!
* jQuery Cycle2; build: v20131022
* http://jquery.malsup.com/cycle2/
* Copyright (c) 2013 M. Alsup; Dual licensed: MIT/GPL
*/
/*! core engine; version: 20131003 */
(function(e){"use strict";function t(e){return(e||"").toLowerCase()}var i="20131003";e.fn.cycle=function(i){var n;return 0!==this.length||e.isReady?this.each(function(){var n,s,o,c,r=e(this),l=e.fn.cycle.log;if(!r.data("cycle.opts")){(r.data("cycle-log")===!1||i&&i.log===!1||s&&s.log===!1)&&(l=e.noop),l("--c2 init--"),n=r.data();for(var a in n)n.hasOwnProperty(a)&&/^cycle[A-Z]+/.test(a)&&(c=n[a],o=a.match(/^cycle(.*)/)[1].replace(/^[A-Z]/,t),l(o+":",c,"("+typeof c+")"),n[o]=c);s=e.extend({},e.fn.cycle.defaults,n,i||{}),s.timeoutId=0,s.paused=s.paused||!1,s.container=r,s._maxZ=s.maxZ,s.API=e.extend({_container:r},e.fn.cycle.API),s.API.log=l,s.API.trigger=function(e,t){return s.container.trigger(e,t),s.API},r.data("cycle.opts",s),r.data("cycle.API",s.API),s.API.trigger("cycle-bootstrap",[s,s.API]),s.API.addInitialSlides(),s.API.preInitSlideshow(),s.slides.length&&s.API.initSlideshow()}}):(n={s:this.selector,c:this.context},e.fn.cycle.log("requeuing slideshow (dom not ready)"),e(function(){e(n.s,n.c).cycle(i)}),this)},e.fn.cycle.API={opts:function(){return this._container.data("cycle.opts")},addInitialSlides:function(){var t=this.opts(),i=t.slides;t.slideCount=0,t.slides=e(),i=i.jquery?i:t.container.find(i),t.random&&i.sort(function(){return Math.random()-.5}),t.API.add(i)},preInitSlideshow:function(){var t=this.opts();t.API.trigger("cycle-pre-initialize",[t]);var i=e.fn.cycle.transitions[t.fx];i&&e.isFunction(i.preInit)&&i.preInit(t),t._preInitialized=!0},postInitSlideshow:function(){var t=this.opts();t.API.trigger("cycle-post-initialize",[t]);var i=e.fn.cycle.transitions[t.fx];i&&e.isFunction(i.postInit)&&i.postInit(t)},initSlideshow:function(){var t,i=this.opts(),n=i.container;i.API.calcFirstSlide(),"static"==i.container.css("position")&&i.container.css("position","relative"),e(i.slides[i.currSlide]).css("opacity",1).show(),i.API.stackSlides(i.slides[i.currSlide],i.slides[i.nextSlide],!i.reverse),i.pauseOnHover&&(i.pauseOnHover!==!0&&(n=e(i.pauseOnHover)),n.hover(function(){i.API.pause(!0)},function(){i.API.resume(!0)})),i.timeout&&(t=i.API.getSlideOpts(i.currSlide),i.API.queueTransition(t,t.timeout+i.delay)),i._initialized=!0,i.API.updateView(!0),i.API.trigger("cycle-initialized",[i]),i.API.postInitSlideshow()},pause:function(t){var i=this.opts(),n=i.API.getSlideOpts(),s=i.hoverPaused||i.paused;t?i.hoverPaused=!0:i.paused=!0,s||(i.container.addClass("cycle-paused"),i.API.trigger("cycle-paused",[i]).log("cycle-paused"),n.timeout&&(clearTimeout(i.timeoutId),i.timeoutId=0,i._remainingTimeout-=e.now()-i._lastQueue,(0>i._remainingTimeout||isNaN(i._remainingTimeout))&&(i._remainingTimeout=void 0)))},resume:function(e){var t=this.opts(),i=!t.hoverPaused&&!t.paused;e?t.hoverPaused=!1:t.paused=!1,i||(t.container.removeClass("cycle-paused"),0===t.slides.filter(":animated").length&&t.API.queueTransition(t.API.getSlideOpts(),t._remainingTimeout),t.API.trigger("cycle-resumed",[t,t._remainingTimeout]).log("cycle-resumed"))},add:function(t,i){var n,s=this.opts(),o=s.slideCount,c=!1;"string"==e.type(t)&&(t=e.trim(t)),e(t).each(function(){var t,n=e(this);i?s.container.prepend(n):s.container.append(n),s.slideCount++,t=s.API.buildSlideOpts(n),s.slides=i?e(n).add(s.slides):s.slides.add(n),s.API.initSlide(t,n,--s._maxZ),n.data("cycle.opts",t),s.API.trigger("cycle-slide-added",[s,t,n])}),s.API.updateView(!0),c=s._preInitialized&&2>o&&s.slideCount>=1,c&&(s._initialized?s.timeout&&(n=s.slides.length,s.nextSlide=s.reverse?n-1:1,s.timeoutId||s.API.queueTransition(s)):s.API.initSlideshow())},calcFirstSlide:function(){var e,t=this.opts();e=parseInt(t.startingSlide||0,10),(e>=t.slides.length||0>e)&&(e=0),t.currSlide=e,t.reverse?(t.nextSlide=e-1,0>t.nextSlide&&(t.nextSlide=t.slides.length-1)):(t.nextSlide=e+1,t.nextSlide==t.slides.length&&(t.nextSlide=0))},calcNextSlide:function(){var e,t=this.opts();t.reverse?(e=0>t.nextSlide-1,t.nextSlide=e?t.slideCount-1:t.nextSlide-1,t.currSlide=e?0:t.nextSlide+1):(e=t.nextSlide+1==t.slides.length,t.nextSlide=e?0:t.nextSlide+1,t.currSlide=e?t.slides.length-1:t.nextSlide-1)},calcTx:function(t,i){var n,s=t;return i&&s.manualFx&&(n=e.fn.cycle.transitions[s.manualFx]),n||(n=e.fn.cycle.transitions[s.fx]),n||(n=e.fn.cycle.transitions.fade,s.API.log('Transition "'+s.fx+'" not found. Using fade.')),n},prepareTx:function(e,t){var i,n,s,o,c,r=this.opts();return 2>r.slideCount?(r.timeoutId=0,void 0):(!e||r.busy&&!r.manualTrump||(r.API.stopTransition(),r.busy=!1,clearTimeout(r.timeoutId),r.timeoutId=0),r.busy||(0!==r.timeoutId||e)&&(n=r.slides[r.currSlide],s=r.slides[r.nextSlide],o=r.API.getSlideOpts(r.nextSlide),c=r.API.calcTx(o,e),r._tx=c,e&&void 0!==o.manualSpeed&&(o.speed=o.manualSpeed),r.nextSlide!=r.currSlide&&(e||!r.paused&&!r.hoverPaused&&r.timeout)?(r.API.trigger("cycle-before",[o,n,s,t]),c.before&&c.before(o,n,s,t),i=function(){r.busy=!1,r.container.data("cycle.opts")&&(c.after&&c.after(o,n,s,t),r.API.trigger("cycle-after",[o,n,s,t]),r.API.queueTransition(o),r.API.updateView(!0))},r.busy=!0,c.transition?c.transition(o,n,s,t,i):r.API.doTransition(o,n,s,t,i),r.API.calcNextSlide(),r.API.updateView()):r.API.queueTransition(o)),void 0)},doTransition:function(t,i,n,s,o){var c=t,r=e(i),l=e(n),a=function(){l.animate(c.animIn||{opacity:1},c.speed,c.easeIn||c.easing,o)};l.css(c.cssBefore||{}),r.animate(c.animOut||{},c.speed,c.easeOut||c.easing,function(){r.css(c.cssAfter||{}),c.sync||a()}),c.sync&&a()},queueTransition:function(t,i){var n=this.opts(),s=void 0!==i?i:t.timeout;return 0===n.nextSlide&&0===--n.loop?(n.API.log("terminating; loop=0"),n.timeout=0,s?setTimeout(function(){n.API.trigger("cycle-finished",[n])},s):n.API.trigger("cycle-finished",[n]),n.nextSlide=n.currSlide,void 0):(s&&(n._lastQueue=e.now(),void 0===i&&(n._remainingTimeout=t.timeout),n.paused||n.hoverPaused||(n.timeoutId=setTimeout(function(){n.API.prepareTx(!1,!n.reverse)},s))),void 0)},stopTransition:function(){var e=this.opts();e.slides.filter(":animated").length&&(e.slides.stop(!1,!0),e.API.trigger("cycle-transition-stopped",[e])),e._tx&&e._tx.stopTransition&&e._tx.stopTransition(e)},advanceSlide:function(e){var t=this.opts();return clearTimeout(t.timeoutId),t.timeoutId=0,t.nextSlide=t.currSlide+e,0>t.nextSlide?t.nextSlide=t.slides.length-1:t.nextSlide>=t.slides.length&&(t.nextSlide=0),t.API.prepareTx(!0,e>=0),!1},buildSlideOpts:function(i){var n,s,o=this.opts(),c=i.data()||{};for(var r in c)c.hasOwnProperty(r)&&/^cycle[A-Z]+/.test(r)&&(n=c[r],s=r.match(/^cycle(.*)/)[1].replace(/^[A-Z]/,t),o.API.log("["+(o.slideCount-1)+"]",s+":",n,"("+typeof n+")"),c[s]=n);c=e.extend({},e.fn.cycle.defaults,o,c),c.slideNum=o.slideCount;try{delete c.API,delete c.slideCount,delete c.currSlide,delete c.nextSlide,delete c.slides}catch(l){}return c},getSlideOpts:function(t){var i=this.opts();void 0===t&&(t=i.currSlide);var n=i.slides[t],s=e(n).data("cycle.opts");return e.extend({},i,s)},initSlide:function(t,i,n){var s=this.opts();i.css(t.slideCss||{}),n>0&&i.css("zIndex",n),isNaN(t.speed)&&(t.speed=e.fx.speeds[t.speed]||e.fx.speeds._default),t.sync||(t.speed=t.speed/2),i.addClass(s.slideClass)},updateView:function(e,t){var i=this.opts();if(i._initialized){var n=i.API.getSlideOpts(),s=i.slides[i.currSlide];!e&&t!==!0&&(i.API.trigger("cycle-update-view-before",[i,n,s]),0>i.updateView)||(i.slideActiveClass&&i.slides.removeClass(i.slideActiveClass).eq(i.currSlide).addClass(i.slideActiveClass),e&&i.hideNonActive&&i.slides.filter(":not(."+i.slideActiveClass+")").hide(),0===i.updateView&&setTimeout(function(){i.API.trigger("cycle-update-view",[i,n,s,e])},n.speed/(i.sync?2:1)),0!==i.updateView&&i.API.trigger("cycle-update-view",[i,n,s,e]),e&&i.API.trigger("cycle-update-view-after",[i,n,s]))}},getComponent:function(t){var i=this.opts(),n=i[t];return"string"==typeof n?/^\s*[\>|\+|~]/.test(n)?i.container.find(n):e(n):n.jquery?n:e(n)},stackSlides:function(t,i,n){var s=this.opts();t||(t=s.slides[s.currSlide],i=s.slides[s.nextSlide],n=!s.reverse),e(t).css("zIndex",s.maxZ);var o,c=s.maxZ-2,r=s.slideCount;if(n){for(o=s.currSlide+1;r>o;o++)e(s.slides[o]).css("zIndex",c--);for(o=0;s.currSlide>o;o++)e(s.slides[o]).css("zIndex",c--)}else{for(o=s.currSlide-1;o>=0;o--)e(s.slides[o]).css("zIndex",c--);for(o=r-1;o>s.currSlide;o--)e(s.slides[o]).css("zIndex",c--)}e(i).css("zIndex",s.maxZ-1)},getSlideIndex:function(e){return this.opts().slides.index(e)}},e.fn.cycle.log=function(){window.console&&console.log&&console.log("[cycle2] "+Array.prototype.join.call(arguments," "))},e.fn.cycle.version=function(){return"Cycle2: "+i},e.fn.cycle.transitions={custom:{},none:{before:function(e,t,i,n){e.API.stackSlides(i,t,n),e.cssBefore={opacity:1,display:"block"}}},fade:{before:function(t,i,n,s){var o=t.API.getSlideOpts(t.nextSlide).slideCss||{};t.API.stackSlides(i,n,s),t.cssBefore=e.extend(o,{opacity:0,display:"block"}),t.animIn={opacity:1},t.animOut={opacity:0}}},fadeout:{before:function(t,i,n,s){var o=t.API.getSlideOpts(t.nextSlide).slideCss||{};t.API.stackSlides(i,n,s),t.cssBefore=e.extend(o,{opacity:1,display:"block"}),t.animOut={opacity:0}}},scrollHorz:{before:function(e,t,i,n){e.API.stackSlides(t,i,n);var s=e.container.css("overflow","hidden").width();e.cssBefore={left:n?s:-s,top:0,opacity:1,display:"block"},e.cssAfter={zIndex:e._maxZ-2,left:0},e.animIn={left:0},e.animOut={left:n?-s:s}}}},e.fn.cycle.defaults={allowWrap:!0,autoSelector:".cycle-slideshow[data-cycle-auto-init!=false]",delay:0,easing:null,fx:"fade",hideNonActive:!0,loop:0,manualFx:void 0,manualSpeed:void 0,manualTrump:!0,maxZ:100,pauseOnHover:!1,reverse:!1,slideActiveClass:"cycle-slide-active",slideClass:"cycle-slide",slideCss:{position:"absolute",top:0,left:0},slides:"> img",speed:500,startingSlide:0,sync:!0,timeout:4e3,updateView:0},e(document).ready(function(){e(e.fn.cycle.defaults.autoSelector).cycle()})})(jQuery),/*! Cycle2 autoheight plugin; Copyright (c) M.Alsup, 2012; version: 20130304 */
function(e){"use strict";function t(t,n){var s,o,c,r=n.autoHeight;if("container"==r)o=e(n.slides[n.currSlide]).outerHeight(),n.container.height(o);else if(n._autoHeightRatio)n.container.height(n.container.width()/n._autoHeightRatio);else if("calc"===r||"number"==e.type(r)&&r>=0){if(c="calc"===r?i(t,n):r>=n.slides.length?0:r,c==n._sentinelIndex)return;n._sentinelIndex=c,n._sentinel&&n._sentinel.remove(),s=e(n.slides[c].cloneNode(!0)),s.removeAttr("id name rel").find("[id],[name],[rel]").removeAttr("id name rel"),s.css({position:"static",visibility:"hidden",display:"block"}).prependTo(n.container).addClass("cycle-sentinel cycle-slide").removeClass("cycle-slide-active"),s.find("*").css("visibility","hidden"),n._sentinel=s}}function i(t,i){var n=0,s=-1;return i.slides.each(function(t){var i=e(this).height();i>s&&(s=i,n=t)}),n}function n(t,i,n,s){var o=e(s).outerHeight(),c=i.sync?i.speed/2:i.speed;i.container.animate({height:o},c)}function s(i,o){o._autoHeightOnResize&&(e(window).off("resize orientationchange",o._autoHeightOnResize),o._autoHeightOnResize=null),o.container.off("cycle-slide-added cycle-slide-removed",t),o.container.off("cycle-destroyed",s),o.container.off("cycle-before",n),o._sentinel&&(o._sentinel.remove(),o._sentinel=null)}e.extend(e.fn.cycle.defaults,{autoHeight:0}),e(document).on("cycle-initialized",function(i,o){function c(){t(i,o)}var r,l=o.autoHeight,a=e.type(l),d=null;("string"===a||"number"===a)&&(o.container.on("cycle-slide-added cycle-slide-removed",t),o.container.on("cycle-destroyed",s),"container"==l?o.container.on("cycle-before",n):"string"===a&&/\d+\:\d+/.test(l)&&(r=l.match(/(\d+)\:(\d+)/),r=r[1]/r[2],o._autoHeightRatio=r),"number"!==a&&(o._autoHeightOnResize=function(){clearTimeout(d),d=setTimeout(c,50)},e(window).on("resize orientationchange",o._autoHeightOnResize)),setTimeout(c,30))})}(jQuery),/*! caption plugin for Cycle2; version: 20130306 */
function(e){"use strict";e.extend(e.fn.cycle.defaults,{caption:"> .cycle-caption",captionTemplate:"{{slideNum}} / {{slideCount}}",overlay:"> .cycle-overlay",overlayTemplate:"<div>{{title}}</div><div>{{desc}}</div>",captionModule:"caption"}),e(document).on("cycle-update-view",function(t,i,n,s){"caption"===i.captionModule&&e.each(["caption","overlay"],function(){var e=this,t=n[e+"Template"],o=i.API.getComponent(e);o.length&&t?(o.html(i.API.tmpl(t,n,i,s)),o.show()):o.hide()})}),e(document).on("cycle-destroyed",function(t,i){var n;e.each(["caption","overlay"],function(){var e=this,t=i[e+"Template"];i[e]&&t&&(n=i.API.getComponent("caption"),n.empty())})})}(jQuery),/*! command plugin for Cycle2; version: 20130707 */
function(e){"use strict";var t=e.fn.cycle;e.fn.cycle=function(i){var n,s,o,c=e.makeArray(arguments);return"number"==e.type(i)?this.cycle("goto",i):"string"==e.type(i)?this.each(function(){var r;return n=i,o=e(this).data("cycle.opts"),void 0===o?(t.log('slideshow must be initialized before sending commands; "'+n+'" ignored'),void 0):(n="goto"==n?"jump":n,s=o.API[n],e.isFunction(s)?(r=e.makeArray(c),r.shift(),s.apply(o.API,r)):(t.log("unknown command: ",n),void 0))}):t.apply(this,arguments)},e.extend(e.fn.cycle,t),e.extend(t.API,{next:function(){var e=this.opts();if(!e.busy||e.manualTrump){var t=e.reverse?-1:1;e.allowWrap===!1&&e.currSlide+t>=e.slideCount||(e.API.advanceSlide(t),e.API.trigger("cycle-next",[e]).log("cycle-next"))}},prev:function(){var e=this.opts();if(!e.busy||e.manualTrump){var t=e.reverse?1:-1;e.allowWrap===!1&&0>e.currSlide+t||(e.API.advanceSlide(t),e.API.trigger("cycle-prev",[e]).log("cycle-prev"))}},destroy:function(){this.stop();var t=this.opts(),i=e.isFunction(e._data)?e._data:e.noop;clearTimeout(t.timeoutId),t.timeoutId=0,t.API.stop(),t.API.trigger("cycle-destroyed",[t]).log("cycle-destroyed"),t.container.removeData(),i(t.container[0],"parsedAttrs",!1),t.retainStylesOnDestroy||(t.container.removeAttr("style"),t.slides.removeAttr("style"),t.slides.removeClass(t.slideActiveClass)),t.slides.each(function(){e(this).removeData(),i(this,"parsedAttrs",!1)})},jump:function(e){var t,i=this.opts();if(!i.busy||i.manualTrump){var n=parseInt(e,10);if(isNaN(n)||0>n||n>=i.slides.length)return i.API.log("goto: invalid slide index: "+n),void 0;if(n==i.currSlide)return i.API.log("goto: skipping, already on slide",n),void 0;i.nextSlide=n,clearTimeout(i.timeoutId),i.timeoutId=0,i.API.log("goto: ",n," (zero-index)"),t=i.currSlide<i.nextSlide,i.API.prepareTx(!0,t)}},stop:function(){var t=this.opts(),i=t.container;clearTimeout(t.timeoutId),t.timeoutId=0,t.API.stopTransition(),t.pauseOnHover&&(t.pauseOnHover!==!0&&(i=e(t.pauseOnHover)),i.off("mouseenter mouseleave")),t.API.trigger("cycle-stopped",[t]).log("cycle-stopped")},reinit:function(){var e=this.opts();e.API.destroy(),e.container.cycle()},remove:function(t){for(var i,n,s=this.opts(),o=[],c=1,r=0;s.slides.length>r;r++)i=s.slides[r],r==t?n=i:(o.push(i),e(i).data("cycle.opts").slideNum=c,c++);n&&(s.slides=e(o),s.slideCount--,e(n).remove(),t==s.currSlide?s.API.advanceSlide(1):s.currSlide>t?s.currSlide--:s.currSlide++,s.API.trigger("cycle-slide-removed",[s,t,n]).log("cycle-slide-removed"),s.API.updateView())}}),e(document).on("click.cycle","[data-cycle-cmd]",function(t){t.preventDefault();var i=e(this),n=i.data("cycle-cmd"),s=i.data("cycle-context")||".cycle-slideshow";e(s).cycle(n,i.data("cycle-arg"))})}(jQuery),/*! hash plugin for Cycle2; version: 20130905 */
function(e){"use strict";function t(t,i){var n;return t._hashFence?(t._hashFence=!1,void 0):(n=window.location.hash.substring(1),t.slides.each(function(s){if(e(this).data("cycle-hash")==n){if(i===!0)t.startingSlide=s;else{var o=s>t.currSlide;t.nextSlide=s,t.API.prepareTx(!0,o)}return!1}}),void 0)}e(document).on("cycle-pre-initialize",function(i,n){t(n,!0),n._onHashChange=function(){t(n,!1)},e(window).on("hashchange",n._onHashChange)}),e(document).on("cycle-update-view",function(e,t,i){i.hash&&"#"+i.hash!=window.location.hash&&(t._hashFence=!0,window.location.hash=i.hash)}),e(document).on("cycle-destroyed",function(t,i){i._onHashChange&&e(window).off("hashchange",i._onHashChange)})}(jQuery),/*! loader plugin for Cycle2; version: 20131020 */
function(e){"use strict";e.extend(e.fn.cycle.defaults,{loader:!1}),e(document).on("cycle-bootstrap",function(t,i){function n(t,n){function o(t){var o;"wait"==i.loader?(r.push(t),0===a&&(r.sort(c),s.apply(i.API,[r,n]),i.container.removeClass("cycle-loading"))):(o=e(i.slides[i.currSlide]),s.apply(i.API,[t,n]),o.show(),i.container.removeClass("cycle-loading"))}function c(e,t){return e.data("index")-t.data("index")}var r=[];if("string"==e.type(t))t=e.trim(t);else if("array"===e.type(t))for(var l=0;t.length>l;l++)t[l]=e(t[l])[0];t=e(t);var a=t.length;a&&(i.eventualSlideCount=i.slideCount+a,t.hide().appendTo("body").each(function(t){function c(){0===--l&&(--a,o(d))}var l=0,d=e(this),u=d.is("img")?d:d.find("img");return d.data("index",t),u=u.filter(":not(.cycle-loader-ignore)").filter(':not([src=""])'),u.length?(l=u.length,u.each(function(){this.complete?c():e(this).load(function(){c()}).error(function(){0===--l&&(i.API.log("slide skipped; img not loaded:",this.src),0===--a&&"wait"==i.loader&&s.apply(i.API,[r,n]))})}),void 0):(--a,r.push(d),void 0)}),a&&i.container.addClass("cycle-loading"))}var s;i.loader&&(s=i.API.add,i.API.add=n)})}(jQuery),/*! pager plugin for Cycle2; version: 20130525 */
function(e){"use strict";function t(t,i,n){var s,o=t.API.getComponent("pager");o.each(function(){var o=e(this);if(i.pagerTemplate){var c=t.API.tmpl(i.pagerTemplate,i,t,n[0]);s=e(c).appendTo(o)}else s=o.children().eq(t.slideCount-1);s.on(t.pagerEvent,function(e){e.preventDefault(),t.API.page(o,e.currentTarget)})})}function i(e,t){var i=this.opts();if(!i.busy||i.manualTrump){var n=e.children().index(t),s=n,o=s>i.currSlide;i.currSlide!=s&&(i.nextSlide=s,i.API.prepareTx(!0,o),i.API.trigger("cycle-pager-activated",[i,e,t]))}}e.extend(e.fn.cycle.defaults,{pager:"> .cycle-pager",pagerActiveClass:"cycle-pager-active",pagerEvent:"click.cycle",pagerTemplate:"<span>•</span>"}),e(document).on("cycle-bootstrap",function(e,i,n){n.buildPagerLink=t}),e(document).on("cycle-slide-added",function(e,t,n,s){t.pager&&(t.API.buildPagerLink(t,n,s),t.API.page=i)}),e(document).on("cycle-slide-removed",function(t,i,n){if(i.pager){var s=i.API.getComponent("pager");s.each(function(){var t=e(this);e(t.children()[n]).remove()})}}),e(document).on("cycle-update-view",function(t,i){var n;i.pager&&(n=i.API.getComponent("pager"),n.each(function(){e(this).children().removeClass(i.pagerActiveClass).eq(i.currSlide).addClass(i.pagerActiveClass)}))}),e(document).on("cycle-destroyed",function(e,t){var i=t.API.getComponent("pager");i&&(i.children().off(t.pagerEvent),t.pagerTemplate&&i.empty())})}(jQuery),/*! prevnext plugin for Cycle2; version: 20130709 */
function(e){"use strict";e.extend(e.fn.cycle.defaults,{next:"> .cycle-next",nextEvent:"click.cycle",disabledClass:"disabled",prev:"> .cycle-prev",prevEvent:"click.cycle",swipe:!1}),e(document).on("cycle-initialized",function(e,t){if(t.API.getComponent("next").on(t.nextEvent,function(e){e.preventDefault(),t.API.next()}),t.API.getComponent("prev").on(t.prevEvent,function(e){e.preventDefault(),t.API.prev()}),t.swipe){var i=t.swipeVert?"swipeUp.cycle":"swipeLeft.cycle swipeleft.cycle",n=t.swipeVert?"swipeDown.cycle":"swipeRight.cycle swiperight.cycle";t.container.on(i,function(){t.API.next()}),t.container.on(n,function(){t.API.prev()})}}),e(document).on("cycle-update-view",function(e,t){if(!t.allowWrap){var i=t.disabledClass,n=t.API.getComponent("next"),s=t.API.getComponent("prev"),o=t._prevBoundry||0,c=void 0!==t._nextBoundry?t._nextBoundry:t.slideCount-1;t.currSlide==c?n.addClass(i).prop("disabled",!0):n.removeClass(i).prop("disabled",!1),t.currSlide===o?s.addClass(i).prop("disabled",!0):s.removeClass(i).prop("disabled",!1)}}),e(document).on("cycle-destroyed",function(e,t){t.API.getComponent("prev").off(t.nextEvent),t.API.getComponent("next").off(t.prevEvent),t.container.off("swipeleft.cycle swiperight.cycle swipeLeft.cycle swipeRight.cycle swipeUp.cycle swipeDown.cycle")})}(jQuery),/*! progressive loader plugin for Cycle2; version: 20130315 */
function(e){"use strict";e.extend(e.fn.cycle.defaults,{progressive:!1}),e(document).on("cycle-pre-initialize",function(t,i){if(i.progressive){var n,s,o=i.API,c=o.next,r=o.prev,l=o.prepareTx,a=e.type(i.progressive);if("array"==a)n=i.progressive;else if(e.isFunction(i.progressive))n=i.progressive(i);else if("string"==a){if(s=e(i.progressive),n=e.trim(s.html()),!n)return;if(/^(\[)/.test(n))try{n=e.parseJSON(n)}catch(d){return o.log("error parsing progressive slides",d),void 0}else n=n.split(RegExp(s.data("cycle-split")||"\n")),n[n.length-1]||n.pop()}l&&(o.prepareTx=function(e,t){var s,o;return e||0===n.length?(l.apply(i.API,[e,t]),void 0):(t&&i.currSlide==i.slideCount-1?(o=n[0],n=n.slice(1),i.container.one("cycle-slide-added",function(e,t){setTimeout(function(){t.API.advanceSlide(1)},50)}),i.API.add(o)):t||0!==i.currSlide?l.apply(i.API,[e,t]):(s=n.length-1,o=n[s],n=n.slice(0,s),i.container.one("cycle-slide-added",function(e,t){setTimeout(function(){t.currSlide=1,t.API.advanceSlide(-1)},50)}),i.API.add(o,!0)),void 0)}),c&&(o.next=function(){var e=this.opts();if(n.length&&e.currSlide==e.slideCount-1){var t=n[0];n=n.slice(1),e.container.one("cycle-slide-added",function(e,t){c.apply(t.API),t.container.removeClass("cycle-loading")}),e.container.addClass("cycle-loading"),e.API.add(t)}else c.apply(e.API)}),r&&(o.prev=function(){var e=this.opts();if(n.length&&0===e.currSlide){var t=n.length-1,i=n[t];n=n.slice(0,t),e.container.one("cycle-slide-added",function(e,t){t.currSlide=1,t.API.advanceSlide(-1),t.container.removeClass("cycle-loading")}),e.container.addClass("cycle-loading"),e.API.add(i,!0)}else r.apply(e.API)})}})}(jQuery),/*! tmpl plugin for Cycle2; version: 20121227 */
function(e){"use strict";e.extend(e.fn.cycle.defaults,{tmplRegex:"{{((.)?.*?)}}"}),e.extend(e.fn.cycle.API,{tmpl:function(t,i){var n=RegExp(i.tmplRegex||e.fn.cycle.defaults.tmplRegex,"g"),s=e.makeArray(arguments);return s.shift(),t.replace(n,function(t,i){var n,o,c,r,l=i.split(".");for(n=0;s.length>n;n++)if(c=s[n]){if(l.length>1)for(r=c,o=0;l.length>o;o++)c=r,r=r[l[o]]||i;else r=c[i];if(e.isFunction(r))return r.apply(c,s);if(void 0!==r&&null!==r&&r!=i)return r}return i})}})}(jQuery);
/*! Plugin for Cycle2; Copyright (c) 2012 M. Alsup; ver: 20121120 */
(function(a){"use strict";var b="ontouchend"in document;a.event.special.swipe=a.event.special.swipe||{scrollSupressionThreshold:10,durationThreshold:1e3,horizontalDistanceThreshold:30,verticalDistanceThreshold:75,setup:function(){var b=a(this);b.bind("touchstart",function(c){function g(b){if(!f)return;var c=b.originalEvent.touches?b.originalEvent.touches[0]:b;e={time:(new Date).getTime(),coords:[c.pageX,c.pageY]},Math.abs(f.coords[0]-e.coords[0])>a.event.special.swipe.scrollSupressionThreshold&&b.preventDefault()}var d=c.originalEvent.touches?c.originalEvent.touches[0]:c,e,f={time:(new Date).getTime(),coords:[d.pageX,d.pageY],origin:a(c.target)};b.bind("touchmove",g).one("touchend",function(c){b.unbind("touchmove",g),f&&e&&e.time-f.time<a.event.special.swipe.durationThreshold&&Math.abs(f.coords[0]-e.coords[0])>a.event.special.swipe.horizontalDistanceThreshold&&Math.abs(f.coords[1]-e.coords[1])<a.event.special.swipe.verticalDistanceThreshold&&f.origin.trigger("swipe").trigger(f.coords[0]>e.coords[0]?"swipeleft":"swiperight"),f=e=undefined})})}},a.event.special.swipeleft=a.event.special.swipeleft||{setup:function(){a(this).bind("swipe",a.noop)}},a.event.special.swiperight=a.event.special.swiperight||a.event.special.swipeleft})(jQuery);
/**
* Magento Enterprise Edition
*
* NOTICE OF LICENSE
*
* This source file is subject to the Magento Enterprise Edition End User License Agreement
* that is bundled with this package in the file LICENSE_EE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.magento.com/license/enterprise-edition
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category design
* @package rwd_default
* @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
* @license http://www.magento.com/license/enterprise-edition
*/
$j(document).ready(function () {
// ==============================================
// UI Pattern - Slideshow
// ==============================================
$j('.slideshow-container .slideshow')
.cycle({
slides: '> li',
pager: '.slideshow-pager',
pagerTemplate: '<span class="pager-box"></span>',
speed: 600,
pauseOnHover: true,
swipe: true,
prev: '.slideshow-prev',
next: '.slideshow-next',
fx: 'scrollHorz'
});
});
/*!
* imagesLoaded PACKAGED v3.1.4
* JavaScript is all like "You images are done yet or what?"
* MIT License
*/
(function(){function e(){}function t(e,t){for(var n=e.length;n--;)if(e[n].listener===t)return n;return-1}function n(e){return function(){return this[e].apply(this,arguments)}}var i=e.prototype,r=this,o=r.EventEmitter;i.getListeners=function(e){var t,n,i=this._getEvents();if("object"==typeof e){t={};for(n in i)i.hasOwnProperty(n)&&e.test(n)&&(t[n]=i[n])}else t=i[e]||(i[e]=[]);return t},i.flattenListeners=function(e){var t,n=[];for(t=0;e.length>t;t+=1)n.push(e[t].listener);return n},i.getListenersAsObject=function(e){var t,n=this.getListeners(e);return n instanceof Array&&(t={},t[e]=n),t||n},i.addListener=function(e,n){var i,r=this.getListenersAsObject(e),o="object"==typeof n;for(i in r)r.hasOwnProperty(i)&&-1===t(r[i],n)&&r[i].push(o?n:{listener:n,once:!1});return this},i.on=n("addListener"),i.addOnceListener=function(e,t){return this.addListener(e,{listener:t,once:!0})},i.once=n("addOnceListener"),i.defineEvent=function(e){return this.getListeners(e),this},i.defineEvents=function(e){for(var t=0;e.length>t;t+=1)this.defineEvent(e[t]);return this},i.removeListener=function(e,n){var i,r,o=this.getListenersAsObject(e);for(r in o)o.hasOwnProperty(r)&&(i=t(o[r],n),-1!==i&&o[r].splice(i,1));return this},i.off=n("removeListener"),i.addListeners=function(e,t){return this.manipulateListeners(!1,e,t)},i.removeListeners=function(e,t){return this.manipulateListeners(!0,e,t)},i.manipulateListeners=function(e,t,n){var i,r,o=e?this.removeListener:this.addListener,s=e?this.removeListeners:this.addListeners;if("object"!=typeof t||t instanceof RegExp)for(i=n.length;i--;)o.call(this,t,n[i]);else for(i in t)t.hasOwnProperty(i)&&(r=t[i])&&("function"==typeof r?o.call(this,i,r):s.call(this,i,r));return this},i.removeEvent=function(e){var t,n=typeof e,i=this._getEvents();if("string"===n)delete i[e];else if("object"===n)for(t in i)i.hasOwnProperty(t)&&e.test(t)&&delete i[t];else delete this._events;return this},i.removeAllListeners=n("removeEvent"),i.emitEvent=function(e,t){var n,i,r,o,s=this.getListenersAsObject(e);for(r in s)if(s.hasOwnProperty(r))for(i=s[r].length;i--;)n=s[r][i],n.once===!0&&this.removeListener(e,n.listener),o=n.listener.apply(this,t||[]),o===this._getOnceReturnValue()&&this.removeListener(e,n.listener);return this},i.trigger=n("emitEvent"),i.emit=function(e){var t=Array.prototype.slice.call(arguments,1);return this.emitEvent(e,t)},i.setOnceReturnValue=function(e){return this._onceReturnValue=e,this},i._getOnceReturnValue=function(){return this.hasOwnProperty("_onceReturnValue")?this._onceReturnValue:!0},i._getEvents=function(){return this._events||(this._events={})},e.noConflict=function(){return r.EventEmitter=o,e},"function"==typeof define&&define.amd?define("eventEmitter/EventEmitter",[],function(){return e}):"object"==typeof module&&module.exports?module.exports=e:this.EventEmitter=e}).call(this),function(e){function t(t){var n=e.event;return n.target=n.target||n.srcElement||t,n}var n=document.documentElement,i=function(){};n.addEventListener?i=function(e,t,n){e.addEventListener(t,n,!1)}:n.attachEvent&&(i=function(e,n,i){e[n+i]=i.handleEvent?function(){var n=t(e);i.handleEvent.call(i,n)}:function(){var n=t(e);i.call(e,n)},e.attachEvent("on"+n,e[n+i])});var r=function(){};n.removeEventListener?r=function(e,t,n){e.removeEventListener(t,n,!1)}:n.detachEvent&&(r=function(e,t,n){e.detachEvent("on"+t,e[t+n]);try{delete e[t+n]}catch(i){e[t+n]=void 0}});var o={bind:i,unbind:r};"function"==typeof define&&define.amd?define("eventie/eventie",o):e.eventie=o}(this),function(e,t){"function"==typeof define&&define.amd?define(["eventEmitter/EventEmitter","eventie/eventie"],function(n,i){return t(e,n,i)}):"object"==typeof exports?module.exports=t(e,require("eventEmitter"),require("eventie")):e.imagesLoaded=t(e,e.EventEmitter,e.eventie)}(this,function(e,t,n){function i(e,t){for(var n in t)e[n]=t[n];return e}function r(e){return"[object Array]"===d.call(e)}function o(e){var t=[];if(r(e))t=e;else if("number"==typeof e.length)for(var n=0,i=e.length;i>n;n++)t.push(e[n]);else t.push(e);return t}function s(e,t,n){if(!(this instanceof s))return new s(e,t);"string"==typeof e&&(e=document.querySelectorAll(e)),this.elements=o(e),this.options=i({},this.options),"function"==typeof t?n=t:i(this.options,t),n&&this.on("always",n),this.getImages(),a&&(this.jqDeferred=new a.Deferred);var r=this;setTimeout(function(){r.check()})}function c(e){this.img=e}function f(e){this.src=e,v[e]=this}var a=e.jQuery,u=e.console,h=u!==void 0,d=Object.prototype.toString;s.prototype=new t,s.prototype.options={},s.prototype.getImages=function(){this.images=[];for(var e=0,t=this.elements.length;t>e;e++){var n=this.elements[e];"IMG"===n.nodeName&&this.addImage(n);for(var i=n.querySelectorAll("img"),r=0,o=i.length;o>r;r++){var s=i[r];this.addImage(s)}}},s.prototype.addImage=function(e){var t=new c(e);this.images.push(t)},s.prototype.check=function(){function e(e,r){return t.options.debug&&h&&u.log("confirm",e,r),t.progress(e),n++,n===i&&t.complete(),!0}var t=this,n=0,i=this.images.length;if(this.hasAnyBroken=!1,!i)return this.complete(),void 0;for(var r=0;i>r;r++){var o=this.images[r];o.on("confirm",e),o.check()}},s.prototype.progress=function(e){this.hasAnyBroken=this.hasAnyBroken||!e.isLoaded;var t=this;setTimeout(function(){t.emit("progress",t,e),t.jqDeferred&&t.jqDeferred.notify&&t.jqDeferred.notify(t,e)})},s.prototype.complete=function(){var e=this.hasAnyBroken?"fail":"done";this.isComplete=!0;var t=this;setTimeout(function(){if(t.emit(e,t),t.emit("always",t),t.jqDeferred){var n=t.hasAnyBroken?"reject":"resolve";t.jqDeferred[n](t)}})},a&&(a.fn.imagesLoaded=function(e,t){var n=new s(this,e,t);return n.jqDeferred.promise(a(this))}),c.prototype=new t,c.prototype.check=function(){var e=v[this.img.src]||new f(this.img.src);if(e.isConfirmed)return this.confirm(e.isLoaded,"cached was confirmed"),void 0;if(this.img.complete&&void 0!==this.img.naturalWidth)return this.confirm(0!==this.img.naturalWidth,"naturalWidth"),void 0;var t=this;e.on("confirm",function(e,n){return t.confirm(e.isLoaded,n),!0}),e.check()},c.prototype.confirm=function(e,t){this.isLoaded=e,this.emit("confirm",this,t)};var v={};return f.prototype=new t,f.prototype.check=function(){if(!this.isChecked){var e=new Image;n.bind(e,"load",this),n.bind(e,"error",this),e.src=this.src,this.isChecked=!0}},f.prototype.handleEvent=function(e){var t="on"+e.type;this[t]&&this[t](e)},f.prototype.onload=function(e){this.confirm(!0,"onload"),this.unbindProxyEvents(e)},f.prototype.onerror=function(e){this.confirm(!1,"onerror"),this.unbindProxyEvents(e)},f.prototype.confirm=function(e,t){this.isConfirmed=!0,this.isLoaded=e,this.emit("confirm",this,t)},f.prototype.unbindProxyEvents=function(e){n.unbind(e.target,"load",this),n.unbind(e.target,"error",this)},s});
/**
* Magento Enterprise Edition
*
* NOTICE OF LICENSE
*
* This source file is subject to the Magento Enterprise Edition End User License Agreement
* that is bundled with this package in the file LICENSE_EE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.magento.com/license/enterprise-edition
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category design
* @package rwd_enterprise
* @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
* @license http://www.magento.com/license/enterprise-edition
*/
// Add validation hints
Validation.defaultOptions.immediate = true;
Validation.defaultOptions.addClassNameToContainer = true;
Event.observe(document, 'dom:loaded', function() {
var inputs = $$('ul.options-list input');
for (var i = 0, l = inputs.length; i < l; i ++) {
inputs[i].addClassName('change-container-classname');
}
})
if (!window.Enterprise) {
window.Enterprise = {};
}
Enterprise.templatesPattern = /(^|.|\r|\n)(\{\{(.*?)\}\})/;
Enterprise.TopCart = {
initialize: function(container) {
this.container = $(container);
this.element = this.container.up(0);
this.elementHeader = this.container.previous(0);
this.intervalDuration = 4000;
this.interval = null;
this.onElementMouseOut = this.handleMouseOut.bindAsEventListener(this);
this.onElementMouseOver = this.handleMouseOver.bindAsEventListener(this);
this.onElementMouseClick = this.handleMouseClick.bindAsEventListener(this);
this.element.observe('mouseout', this.onElementMouseOut);
this.element.observe('mouseover', this.onElementMouseOver);
this.elementHeader.observe('click', this.onElementMouseClick);
},
handleMouseOut: function (evt) {
if ($(this.elementHeader).hasClassName('expanded')) {
this.interval = setTimeout(this.hideCart.bind(this), this.intervalDuration);
}
},
handleMouseOver: function (evt) {
if (this.interval !== null) {
clearTimeout(this.interval);
this.interval = null;
}
},
handleMouseClick: function (evt) {
if (!$(this.elementHeader).hasClassName('expanded') && !$(this.container.id).hasClassName('process')) {
this.showCart();
}
else {
this.hideCart();
}
},
showCart: function (timePeriod) {
this.container.parentNode.style.zIndex=992;
new Effect.SlideDown(this.container.id, { duration: 0.5,
beforeStart: function(effect) {$( effect.element.id ).addClassName('process');},
afterFinish: function(effect) {$( effect.element.id ).removeClassName('process'); }
});
$(this.elementHeader).addClassName('expanded');
if(timePeriod) {
this.timePeriod = timePeriod*1000;
this.interval = setTimeout(this.hideCart.bind(this), this.timePeriod);
}
},
hideCart: function () {
if (!$(this.container.id).hasClassName('process') && $(this.elementHeader).hasClassName('expanded')) {
new Effect.SlideUp(this.container.id, { duration: 0.5,
beforeStart: function(effect) {$( effect.element.id ).addClassName('process');},
afterFinish: function(effect) {
$( effect.element.id ).removeClassName('process');
effect.element.parentNode.style.zIndex=1;
}
});
}
if (this.interval !== null) {
clearTimeout(this.interval);
this.interval = null;
}
$(this.elementHeader).removeClassName('expanded');
}
};
Enterprise.Bundle = {
oldReloadPrice: false,
initialize: function () {
this.slider = $('bundleProduct');
this.xOffset = $('bundle-product-wrapper').getDimensions().width;
},
swapReloadPrice: function () {
Enterprise.Bundle.oldReloadPrice = Product.Bundle.prototype.reloadPrice;
Product.Bundle.prototype.reloadPrice = Enterprise.Bundle.reloadPrice;
Product.Bundle.prototype.selection = Enterprise.Bundle.selection;
},
reloadPrice: function () {
var result = Enterprise.Bundle.oldReloadPrice.bind(this)();
var priceContainer, duplicateContainer = null
if (priceContainer = $('bundle-product-wrapper').down('.price-box .price-as-configured')) {
if (duplicateContainer = $('bundle-product-wrapper').down('.duplicate-price-box .price-as-configured')) {
duplicateContainer.down('.price').update(
priceContainer.down('.price').innerHTML
);
}
}
if (!this.summaryTemplate && $('bundle-summary-template')) {
this.summaryTemplate = new Template($('bundle-summary-template').innerHTML, Enterprise.templatesPattern);
this.optionTemplate = new Template($('bundle-summary-option-template').innerHTML, Enterprise.templatesPattern);
this.optionMultiTemplate = new Template($('bundle-summary-option-multi-template').innerHTML, Enterprise.templatesPattern);
}
if (this.summaryTemplate && $('bundle-summary')) {
var summaryHTMLArray = [];
for (var option in this.config.options) {
if (typeof (this.config.selected[option]) !== 'undefined') {
var optionHTML = '';
for (var i = 0, l = this.config.selected[option].length; i < l; i ++) {
var selection = this.selection(option, this.config.selected[option][i]);
if (selection && this.config.options[option].isMulti) {
optionHTML += this.optionMultiTemplate.evaluate(selection);
} else if (selection) {
optionHTML += this.optionTemplate.evaluate(selection);
}
}
if (optionHTML.length > 0) {
var position = parseInt(this.config.options[option].position);
summaryHTMLArray[position] = this.summaryTemplate.evaluate({label:this.config.options[option].title.escapeHTML(), options: optionHTML});
}
}
}
var summaryHTML = summaryHTMLArray.join('');
if (typeof($('bundle-summary').update(summaryHTML).childElements().last()) != 'undefined') {
$('bundle-summary').update(summaryHTML).childElements().last().addClassName('last');
}
}
return result;
},
selection: function(optionId, selectionId) {
if (selectionId == '' || selectionId == 'none') {
return false;
}
var qty = null;
if (this.config.options[optionId].selections[selectionId].customQty == 1 && !this.config['options'][optionId].isMulti) {
if ($('bundle-option-' + optionId + '-qty-input')) {
qty = $('bundle-option-' + optionId + '-qty-input').value;
} else {
qty = 1;
}
} else {
qty = this.config.options[optionId].selections[selectionId].qty;
}
return {qty: qty, name: this.config.options[optionId].selections[selectionId].name.escapeHTML()};
},
start: function () {
if (!$('bundle-product-wrapper').hasClassName('moving-now')) {
new Effect.Move(this.slider, {
x: -this.xOffset, y: 0, mode: 'relative', duration: 1.5,
beforeStart: function (effect) {
$('bundle-product-wrapper').setStyle({height: $('productView').getHeight() + 'px'});
$('options-container').show();
Enterprise.BundleSummary.initialize();
$('bundle-product-wrapper').addClassName('moving-now');
},
afterFinish: function (effect) {
$('bundle-product-wrapper').setStyle({height: 'auto'});
$('productView').hide();
$('bundle-product-wrapper').removeClassName('moving-now');
}
});
}
},
end: function () {
if (!$('bundle-product-wrapper').hasClassName('moving-now')) {
new Effect.Move(this.slider, {
x: this.xOffset, y: 0, mode: 'relative', duration: 1.5,
beforeStart: function (effect) {
$('bundle-product-wrapper').setStyle({height: $('options-container').getHeight() + 'px'});
$('productView').show();
$('bundle-product-wrapper').addClassName('moving-now');
},
afterFinish: function (effect) {
$('bundle-product-wrapper').setStyle({height: 'auto'});
$('options-container').hide();
Enterprise.BundleSummary.exitSummary();
$('bundle-product-wrapper').removeClassName('moving-now');
}
});
}
}
};
Enterprise.BundleSummary = {
initialize: function () {
this.summary = $('bundleSummary');
this.summaryOffsetTop = $('customizeTitle').getDimensions().height;
this.summary.setStyle({top:this.summaryOffsetTop + "px"});
this.summaryContainer = this.summary.up(0);
this.doNotCheck = false;
this.summaryStartY = this.summary.positionedOffset().top;
this.summaryStartY = this.summaryOffsetTop;
this.summaryStartX = this.summary.positionedOffset().left;
this.onDocScroll = this.handleDocScroll.bindAsEventListener(this);
this.GetScroll = setInterval(this.onDocScroll, 50);
this.onEffectEnds = this.effectEnds.bind(this);
},
handleDocScroll: function () {
if (this.currentOffsetTop == document.viewport.getScrollOffsets().top
&& (this.checkOffset(null) == null)) {
return;
} else {
if (this.currentOffsetTop == document.viewport.getScrollOffsets().top) {
this.doNotCheck = true;
}
this.currentOffsetTop = document.viewport.getScrollOffsets().top;
}
if (this.currentEffect) {
this.currentEffect.cancel();
var topOffset = 0;
if (this.summaryContainer.viewportOffset().top < -60) {
topOffset = -(this.summaryContainer.viewportOffset().top);
} else {
topOffset = this.summaryStartY;
}
topOffset = this.checkOffset(topOffset);
if (topOffset === null) {
this.currentEffect = false;
return;
}
this.currentEffect.start({
x: this.summaryStartX,
y: topOffset,
mode: 'absolute',
duration: 0.3,
afterFinish: this.onEffectEnds
});
return;
}
this.currentEffect = new Effect.Move(this.summary);
},
effectEnds: function () {
if (this.doNotCheck == true) {
this.doNotCheck = false;
}
},
checkOffset: function (offset) {
if (this.doNotCheck && offset === null) {
return null;
}
var dimensions = this.summary.getDimensions();
var parentDimensions = this.summary.up().getDimensions();
if ((offset !== null ? offset : this.summary.offsetTop) + dimensions.height >= parentDimensions.height) {
offset = parentDimensions.height - dimensions.height;
} else if (offset === null &&
this.currentOffsetTop > (this.summaryContainer.viewportOffset().top) &&
(this.currentOffsetTop - this.summaryContainer.viewportOffset().top) > this.summary.offsetTop) {
offset = this.currentOffsetTop - this.summaryContainer.viewportOffset().top;
}
return offset;
},
exitSummary: function () {
clearInterval(this.GetScroll);
}
};
Enterprise.Tabs = Class.create();
Object.extend(Enterprise.Tabs.prototype, {
initialize: function (container) {
this.container = $(container);
this.container.addClassName('tab-list');
this.tabs = this.container.select('dt.tab');
this.activeTab = this.tabs.first();
this.tabs.first().addClassName('first');
this.tabs.last().addClassName('last');
this.onTabClick = this.handleTabClick.bindAsEventListener(this);
for (var i = 0, l = this.tabs.length; i < l; i ++) {
this.tabs[i].observe('click', this.onTabClick);
}
this.select();
},
handleTabClick: function (evt) {
this.activeTab = Event.findElement(evt, 'dt');
this.select();
},
select: function () {
for (var i = 0, l = this.tabs.length; i < l; i ++) {
if (this.tabs[i] == this.activeTab) {
this.tabs[i].addClassName('active');
this.tabs[i].style.zIndex = this.tabs.length + 2;
/*this.tabs[i].next('dd').show();*/
new Effect.Appear (this.tabs[i].next('dd'), { duration:0.5 });
this.tabs[i].parentNode.style.height=this.tabs[i].next('dd').getHeight() + 15 + 'px';
} else {
this.tabs[i].removeClassName('active');
this.tabs[i].style.zIndex = this.tabs.length + 1 - i;
this.tabs[i].next('dd').hide();
}
}
}
});
Enterprise.Slider = Class.create();
Object.extend(Enterprise.Slider.prototype, {
initialize: function (container, config) {
this.container = $(container);
this.config = {
panelCss: 'slider-panel',
sliderCss: 'slider',
itemCss: 'slider-item',
slideButtonCss: 'slide-button',
slideButtonInactiveCss: 'inactive',
forwardButtonCss: 'forward',
backwardButtonCss: 'backward',
pageSize: 6,
scrollSize: 2,
slideDuration: 1.0,
slideDirection: 'horizontal',
fadeEffect: true
};
Object.extend(this.config, config || {});
this.items = this.container.select('.' + this.config.itemCss);
this.isPlaying = false;
this.isAbsolutized = false;
this.offset = 0;
this.onClick = this.handleClick.bindAsEventListener(this);
this.sliderPanel = this.container.down('.' + this.config.panelCss);
this.slider = this.sliderPanel.down('.' + this.config.sliderCss);
this.container.select('.' + this.config.slideButtonCss).each(
this.initializeHandlers.bind(this)
);
this.updateButtons();
Event.observe(window, 'load', this.initializeDimensions.bind(this));
},
initializeHandlers: function (element) {
if (element.hasClassName(this.config.forwardButtonCss) ||
element.hasClassName(this.config.backwardButtonCss)) {
element.observe('click', this.onClick);
}
},
handleClick: function (evt) {
var element = Event.element(evt);
if (!element.hasClassName(this.config.slideButtonCss)) {
element = element.up('.' + this.config.slideButtonCss);
}
if (!element.hasClassName(this.config.slideButtonInactiveCss)) {
element.hasClassName(this.config.forwardButtonCss) || this.backward();
element.hasClassName(this.config.backwardButtonCss) || this.forward();
}
Event.stop(evt);
},
updateButtons: function () {
var buttons = this.container.select('.' + this.config.slideButtonCss);
for (var i = 0, l = buttons.length; i < l; i++) {
if (buttons[i].hasClassName(this.config.backwardButtonCss)) {
if (this.offset <= 0) {
buttons[i].addClassName(this.config.slideButtonInactiveCss);
}
else {
buttons[i].removeClassName(this.config.slideButtonInactiveCss);
}
} else if (buttons[i].hasClassName(this.config.forwardButtonCss)) {
if (this.offset >= this.items.length - this.config.pageSize) {
buttons[i].addClassName(this.config.slideButtonInactiveCss);
}
else {
buttons[i].removeClassName(this.config.slideButtonInactiveCss);
}
}
}
},
initializeDimensions: function () {
if ((this.config.slideDirection == 'horizontal' && this.sliderPanel.style.width) ||
(this.config.slideDirection != 'horizontal' && this.sliderPanel.style.height)) {
return this;
}
var firstItem = this.items.first();
var offset = 0;
if (this.config.slideDirection == 'horizontal') {
offset = (parseInt(firstItem.getStyle('margin-left')) + parseInt(firstItem.getStyle('margin-right'))) * (this.config.pageSize - 1);
this.sliderPanel.setStyle({width: (firstItem.getDimensions().width * this.config.pageSize + offset) + 'px'});
} else {
offset = (parseInt(firstItem.getStyle('margin-bottom')) + parseInt(firstItem.getStyle('margin-top'))) * (this.config.pageSize - 1);
this.sliderPanel.setStyle({height: (firstItem.getDimensions().height * this.config.pageSize + offset) + 'px'});
}
var dimensions = this.sliderPanel.getDimensions();
var sliderParent = this.sliderPanel.up();
/*
dimensions.height += parseInt(sliderParent.getStyle('padding-top'));
dimensions.height += parseInt(sliderParent.getStyle('padding-bottom'));
dimensions.width += parseInt(sliderParent.getStyle('padding-left'));
dimensions.width += parseInt(sliderParent.getStyle('padding-right'));
if (sliderParent.down('.slide-button')) {
var buttonDimensions = sliderParent.down('.slide-button').getDimensions();
if (this.config.slideDirection == 'horizontal') {
dimensions.width += 2 * buttonDimensions.width;
} else {
dimensions.height += 2 * buttonDimensions.height;
}
}
*/
sliderParent.setStyle({
width: dimensions.width + 'px',
height: dimensions.height + 'px'
});
return this;
},
absolutize: function () {
if (!this.isAbsolutized) {
this.isAbsolutized = true;
var dimensions = this.sliderPanel.getDimensions();
this.sliderPanel.setStyle({
height: dimensions.height + 'px',
width: dimensions.width + 'px'
});
this.slider.absolutize();
}
},
forward: function () {
if (this.offset + this.config.pageSize <= this.items.length - 1) {
this.slide(true);
}
},
backward: function () {
if (this.offset > 0) {
this.slide(false);
}
},
slide: function (isForward) {
if (this.isPlaying) {
return;
}
this.absolutize();
this.effectConfig = {
duration: this.config.slideDuration
};
if (this.config.slideDirection == 'horizontal') {
this.effectConfig.x = this.getSlidePosition(isForward).left;
} else {
this.effectConfig.y = this.getSlidePosition(isForward).top;
}
this.start();
},
start: function ()
{
if (this.config.fadeEffect) {
this.fadeIn();
} else {
this.move();
}
},
fadeIn: function ()
{
new Effect.Fade(this.slider.up('div.slider-panel'), {
from: 1.0,
to:0.5,
afterFinish: this.move.bind(this),
beforeStart: this.effectStarts.bind(this),
duration: 0.3
});
},
fadeOut: function ()
{
new Effect.Fade(this.slider.up('div.slider-panel'), {
from: 0.5,
to:1.0,
afterFinish: this.effectEnds.bind(this),
duration: 0.3
});
},
move: function ()
{
if (this.config.fadeEffect) {
this.effectConfig.afterFinish = this.fadeOut.bind(this);
} else {
this.effectConfig.afterFinish = this.effectEnds.bind(this);
this.effectConfig.beforeStart = this.effectStarts.bind(this);
}
new Effect.Move(this.slider, this.effectConfig);
},
effectStarts: function () {
this.isPlaying = true;
},
effectEnds: function () {
this.isPlaying = false;
this.updateButtons();
},
getSlidePosition: function (isForward) {
var targetOffset;
if (isForward) {
targetOffset = Math.min(this.items.length - this.config.pageSize, this.offset + this.config.scrollSize)
}
else {
targetOffset = Math.max(this.offset - this.config.scrollSize, 0);
}
this.offset = targetOffset;
var item = this.items[targetOffset];
var itemOffset = {left:0, top:0};
itemOffset.left = -(item.cumulativeOffset().left
- this.slider.cumulativeOffset().left + this.slider.offsetLeft);
itemOffset.top = -(item.cumulativeOffset().top
- this.slider.cumulativeOffset().top + this.slider.offsetTop);
return itemOffset;
}
});
Enterprise.PopUpMenu = {
currentPopUp: null,
documentHandlerInitialized: false,
popUpZIndex: 994,
hideDelay: 2000,
hideOnClick: true,
hideInterval: null,
initializeDocumentHandler: function () {
if (!this.documentHandlerInitialized) {
this.documentHandlerInitialized = true;
Event.observe(
document.body,
'click',
this.handleDocumentClick.bindAsEventListener(this)
);
}
},
handleDocumentClick: function (evt) {
if (this.currentPopUp !== null) {
var element = Event.element(evt);
if (!this.currentPopUp.onlyShowed && this.hideOnClick) {
this.hide();
} else {
this.currentPopUp.onlyShowed = false;
}
}
},
handlePopUpOver: function (evt) {
if (this.currentPopUp !== null) {
this.currentPopUp.removeClassName('faded');
this.resetTimeout(0);
}
},
handlePopUpOut: function (evt) {
if (this.currentPopUp !== null) {
this.currentPopUp.addClassName('faded');
this.resetTimeout(1);
}
},
show: function (trigger) {
this.initializeDocumentHandler();
var container = $(trigger).up('.switch-wrapper');
if (!$('popId-' + container.id)) {
return;
}
if (this.currentPopUp !== null && $('popId-' + container.id) !== this.currentPopUp) {
this.hide(true);
} else if (this.currentPopUp !== null && this.currentPopUp === $('popId-' + container.id)) {
this.hide();
return;
}
this.currentPopUp = $('popId-' + container.id);
this.currentPopUp.container = container;
this.currentPopUp.container.oldZIndex = this.currentPopUp.container.style.zIndex;
this.currentPopUp.container.style.zIndex = this.popUpZIndex;
new Effect.Appear(this.currentPopUp, { duration:0.3 });
if (!this.currentPopUp.isHandled) {
this.currentPopUp.observe('mouseover', this.handlePopUpOver.bindAsEventListener(this));
this.currentPopUp.observe('mouseout', this.handlePopUpOut.bindAsEventListener(this));
this.currentPopUp.isHandled = true;
}
this.currentPopUp.onlyShowed = true;
this.currentPopUp.container.down('.switcher').addClassName('list-opened');
this.resetTimeout(2);
},
hide: function () {
if (this.currentPopUp !== null) {
if (arguments.length == 0) {
new Effect.Fade(this.currentPopUp, {duration: 0.3});
} else {
this.currentPopUp.hide();
}
this.currentPopUp.container.style.zIndex = this.currentPopUp.container.oldZIndex;
this.resetTimeout(0);
this.currentPopUp.container.down('.switcher').removeClassName('list-opened');
this.currentPopUp = null;
}
},
resetTimeout: function (delay) {
if (this.hideTimeout !== null) {
clearTimeout(this.hideTimeout);
this.hideTimeout = null;
}
if (delay) {
this.hideTimeout = setTimeout(
this.hide.bind(this),
this.hideDelay * delay
);
}
}
};
function popUpMenu(element) {
Enterprise.PopUpMenu.show(element);
}
/*
function popUpMenu(element,trigger) {
var iDelay = 2000;
var new_popup = 0;
var sTempId = 'popUped';
if (document.getElementById(sTempId)) {
var eTemp = document.getElementById(sTempId);
$(sTempId).previous(0).down('.switcher').removeClassName('list-opened');
new Effect.Fade (eTemp, { duration:0.3 });
eTemp.id = sNativeId;
clearTimeout(tId);
document.onclick = null;
}
sNativeId = 'popId-'+$(element).up(1).id;
var el = $(sNativeId);
el.id = sTempId;
if (eTemp && el == eTemp) {
hideElement();
} else {
$(element).addClassName('list-opened');
$(sTempId).getOffsetParent().style.zIndex = 994;
new Effect.Appear (el, { duration:0.3 });
tId=setTimeout("hideElement()",2*iDelay);
}
new_popup = 1;
document.onclick = function() {
if (!new_popup) {
hideElement();
document.onclick = null;
}
new_popup = 0;
}
el.onmouseout = function() {
if ($(sTempId)) {
$(sTempId).addClassName('faded');
tId=setTimeout("hideElement()",iDelay);
}
}
el.onmouseover = function() {
if ($(sTempId)) {
$(sTempId).removeClassName('faded');
clearTimeout(tId);
}
}
hideElement = function() {
//el.hide();
new Effect.Fade (el, { duration:0.3 });
$(element).removeClassName('list-opened');
el.getOffsetParent().style.zIndex = 1;
el.id = sNativeId;
if (tId) {clearTimeout(tId);}
}
} */
Enterprise.Widget = Class.create({
_node: null,
_children: [],
initialize: function (node) {
this._node = node;
},
getNode: function() {
return this._node;
},
/**
* @param {Enterprise.Widget} widget
*/
addChild: function(widget) {
this._children.push(widget);
var children = $(this._node).immediateDescendants(),
exists = false;
$(this._node).immediateDescendants().each(function(child) {
if (child == widget.getNode()) {
exists = true;
}
});
if (!exists) {
widget.placeAt(this._node);
}
},
placeAt: function(node) {
$(node).insert(this._node);
}
});
Enterprise.Widget.Dialog = Class.create(Enterprise.Widget, {
_title: '',
_titleNode: {},
_contentNode: {},
_backNode: {},
_isPlaced: false,
initialize: function ($super, title, content, additionalClass) {
this._title = title;
//this._node = new Element('div', {'class': 'popup-block block', 'style': {'display': 'none'}});
this._node = new Element('div', {'class': 'popup-block block'});
this._node.addClassName(additionalClass);
//this._windowOverlay = new Element('div', {'class': 'window-overlay', 'style': {'display': 'none'}});
this._windowOverlay = new Element('div', {'class': 'window-overlay'});
var headerNode = new Element('div', {'class': 'block-title'});
this._titleNode = new Element('strong').update(title);
this._closeButton = new Element('div', {'class': 'btn-close'}).update('Close');
$(this._closeButton).onclick = (function() {
this.hide();
}).bind(this);
headerNode.insert(this._titleNode);
headerNode.insert(this._closeButton);
this._node.insert(headerNode);
this._contentNode = new Element('div', {'class': 'block-content'});
this._contentNode.insert(content);
this._node.insert(this._contentNode);
},
place: function() {
$('wishlist_edit_action_container').insert(this._node);
this._isPlaced = true;
},
setTitle: function(title) {
$(this._titleNode).update(title);
},
setContent: function(content) {
$(this._contentNode).update(content);
},
getContent: function() {
return this._contentNode;
},
show: function() {
if (!this._isPlaced) {
this.place();
}
//$(this._windowOverlay).setStyle({'display':'block'});
$(this._windowOverlay).addClassName('active');
this._windowOverlay.style.height=$$('body')[0].getHeight()+'px';
//$(this._node).setStyle({'display': 'block'});
$(this._node).addClassName('active');
$(this._node).show();
},
hide: function() {
//$(this._windowOverlay).setStyle({'display':'none'});
$(this._windowOverlay).removeClassName('active');
//$(this._node).setStyle({'display':'none'});
$(this._node).removeClassName('active');
$(this._node).hide();
},
setBusy: function(state) {
if (state) {
$(this._node).addClassName('loading');
} else {
$(this._node).removeClassName('loading');
}
},
destroy: function() {
$(this._node).remove();
}
});
Enterprise.Widget.SplitButton = Class.create(Enterprise.Widget, {
_list: null,
_templateString: '<strong class="split-button-title"><span></span></strong>' +
'<a href="#" class="change"></a>' +
'<div class="list-container">' +
'<ul>' +
'</ul>' +
'</div>',
initialize: function($super, title, alt, type) {
if (typeof title != 'string') {
$super(title);
} else {
$super(new Element('div', {'class': 'split-button split-button-created' + ((type)? ' ' + type: '')}));
this._node.update(this._templateString);
this._node.down('strong span').update(title);
this._node.down('.change').update(alt);
}
Event.observe($(this._node).down('strong'), 'click', (function(event){this.onClick(event);}).bind(this));
this._node.down('.change').setAttribute('tabindex', 20);
this._list = $(this._node).down('ul');
Event.observe($(this._node).down('.change'), 'click', this.onToggle.bind(this));
Event.observe($(this._node).down('.change'), 'blur', this.close.bind(this));
},
onClick: function(event) {
},
onToggle: function(event) {
Event.stop(event);
if (this.isOpened()) {
this.close();
} else {
this.open();
}
},
isOpened: function() {
return $(this._node).hasClassName('active');
},
open: function() {
$(this._node).addClassName('active');
this.onOpen();
},
onOpen: function() {
},
close: function() {
$(this._node).removeClassName.bind($(this._node), 'active').delay(0.2);
this.onClose();
},
onClose: function() {
},
/**
* @param {Enterprise.Widget.SplitButton.Option} option
*/
addOption: function(option) {
option.placeAt(this._list);
option.onClick = option.onClick.wrap((function(proceed) {
proceed();
this.close();
}).bind(this));
}
});
Enterprise.Widget.SplitButton.Option = Class.create(Enterprise.Widget, {
initialize: function($super, title, type) {
$super(new Element('li', {'class' : type ? type : null}));
this._node.update('<span title="' + title + '">' + title + '</span>');
Event.observe(this._node, 'click', (function(){this.onClick()}).bind(this));
},
getNode: function() {
return this._node;
},
onClick: function() {
}
})
Enterprise.loadSplitButtons = function() {
if (typeof Enterprise.splitButtonsLoaded == 'undefined') {
Enterprise.splitButtonsLoaded = true;
$$('.split-button').each(function(node) {
if (!$(node).hasClassName('split-button-created')) {
new Enterprise.Widget.SplitButton(node);
}
});
}
};
Enterprise.textOverflow = function(elem) {
var container = $(elem);
if (container.getStyle('overflow') == 'hidden') {
var inner = container.down(0);
var initialHeight = container.getHeight();
if (inner.getHeight() > initialHeight) {
var words = inner.innerHTML.split(' ');
var test = new Element('span', {'style': 'visibility:hidden;'});
test.style.width = container.getWidth();
container.insert(test);
var tempString = '';
for (var i = 0; $(test).getHeight() <= initialHeight || i < words.legth; i++) {
tempString = tempString + words[i] + ' ';
test.update(tempString)
};
var finalstring = (words.slice(-words.length, i - 2)).join(' ');
test.remove();
inner.update(finalstring + '…');
}
}
};
Event.observe(document, 'dom:loaded', Enterprise.loadSplitButtons);
/**
* Magento Enterprise Edition
*
* NOTICE OF LICENSE
*
* This source file is subject to the Magento Enterprise Edition End User License Agreement
* that is bundled with this package in the file LICENSE_EE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.magento.com/license/enterprise-edition
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category design
* @package rwd_default
* @copyright Copyright (c) 2006-2014 X.commerce, Inc. (http://www.magento.com)
* @license http://www.magento.com/license/enterprise-edition
*/
function Minicart(options) {
this.formKey = options.formKey;
this.trackDTM = options.trackDTM;
this.trackDDM = options.trackDDM;
this.previousVal = null;
this.defaultErrorMessage = 'Error occurred. Try to refresh page.';
this.selectors = {
itemRemove: '#cart-sidebar .remove',
container: '#header-cart',
inputQty: '.cart-item-quantity',
qty: 'div.header-minicart span.count',
overlay: '.minicart-wrapper',
error: '#minicart-error-message',
success: '#minicart-success-message',
quantityButtonPrefix: '#qbutton-',
quantityInputPrefix: '#qinput-',
quantityButtonClass: '.quantity-button',
cartHeader: '.skip-cart'
};
if (options.selectors) {
$j.extend(this.selectors, options.selectors);
}
}
Minicart.prototype = {
init: function() {
var cart = this;
// bind remove event
$j(this.selectors.itemRemove).unbind('click.minicart').bind('click.minicart', function(e) {
e.preventDefault();
cart.removeItem($j(this));
});
// bind update qty event
$j(this.selectors.inputQty)
.unbind('blur.minicart')
.unbind('focus.minicart')
.bind('focus.minicart', function() {
cart.previousVal = $j(this).val();
cart.displayQuantityButton($j(this));
})
.bind('blur.minicart', function() {
cart.revertInvalidValue(this);
});
$j(this.selectors.quantityButtonClass)
.unbind('click.quantity')
.bind('click.quantity', function() {
cart.processUpdateQuantity(this);
});
},
removeItem: function(el) {
var cart = this;
if (confirm(el.data('confirm'))) {
cart.hideMessage();
cart.showOverlay();
$j.ajax({
type: 'POST',
dataType: 'json',
data: {form_key: cart.formKey},
url: el.attr('href')
}).done(function(result) {
cart.hideOverlay();
if (result.success) {
if(cart.trackDDM) {
cart.updateDDM(el);
}
cart.updateCartQty(result.qty);
cart.updateContentOnRemove(result, el.closest('li'));
cart.updateHeader(result);
if(cart.trackDTM) {
cart.updateDTM(result, true);
}
} else {
cart.showMessage(result);
}
}).error(function() {
cart.hideOverlay();
cart.showError(cart.defaultErrorMessage);
});
}
},
revertInvalidValue: function(el) {
if (!this.isValidQty($j(el).val()) || $j(el).val() === this.previousVal) {
$j(el).val(this.previousVal);
this.hideQuantityButton(el);
}
},
displayQuantityButton: function(el) {
var buttonId = this.selectors.quantityButtonPrefix + $j(el).data('item-id');
$j(buttonId).addClass('visible').attr('disabled',null);
},
hideQuantityButton: function(el) {
var buttonId = this.selectors.quantityButtonPrefix + $j(el).data('item-id');
$j(buttonId).removeClass('visible').attr('disabled','disabled');
},
processUpdateQuantity: function(el) {
var input = $j(this.selectors.quantityInputPrefix + $j(el).data('item-id'));
if (this.isValidQty(input.val()) && input.val() !== this.previousVal) {
this.updateItem(el);
} else {
this.revertInvalidValue(input);
}
},
updateDTM: function(data, remove ) {
if(remove) {
_Lbt.cart.remove(data.productId);
} else {
_Lbt.cart.add(data.productId, data.productQty);
}
//_Lbt.cart.notifyUpdate();
},
updateDDM: function(el) {
if(window.digitalData) {
var productId = $(el).data('product-id');
var qty = $(el).data('qty');
window.digitalData.events.push({
'category': 'Ecommerce',
'name': 'Removed Product',
'product': '' + productId,
'quantity': +qty
});
}
},
updateItem: function(el) {
var cart = this;
var input = $j(this.selectors.quantityInputPrefix + $j(el).data('item-id'));
var quantity = parseInt(input.val(), 10);
cart.hideMessage();
cart.showOverlay();
$j.ajax({
type: 'POST',
dataType: 'json',
url: input.data('link'),
data: {qty: quantity, form_key: cart.formKey}
}).done(function(result) {
cart.hideOverlay();
if (result.success) {
cart.updateCartQty(result.qty);
if (quantity !== 0) {
cart.updateContentOnUpdate(result);
} else {
cart.updateContentOnRemove(result, input.closest('li'));
}
if(cart.trackDTM) {
cart.updateDTM(result, false);
}
cart.updateHeader(result);
} else {
cart.showMessage(result);
}
}).error(function() {
cart.hideOverlay();
cart.showError(cart.defaultErrorMessage);
});
return false;
},
updateContentOnRemove: function(result, el) {
var cart = this;
el.hide('slow', function() {
$j(cart.selectors.container).html(result.content);
cart.showMessage(result);
});
},
updateContentOnUpdate: function(result) {
$j(this.selectors.container).html(result.content);
this.showMessage(result);
},
updateCartQty: function(qty) {
if (typeof qty !== 'undefined') {
$j(this.selectors.qty).text(qty);
}
},
updateHeader: function(result) {
if (result.qty > 0) {
$j(this.selectors.cartHeader).removeClass('no-count');
}else{
$j(this.selectors.cartHeader).addClass('no-count');
}
$j(this.selectors.cartHeader + ' > .label').html(result.header_content);
},
isValidQty: function(val) {
return (val.length > 0) && (val - 0 === parseInt(val)) && (val - 0 > 0);
},
showOverlay: function() {
$j(this.selectors.overlay).addClass('loading');
},
hideOverlay: function() {
$j(this.selectors.overlay).removeClass('loading');
},
showMessage: function(result) {
if (typeof result.notice !== 'undefined') {
this.showError(result.notice);
} else if (typeof result.error !== 'undefined') {
this.showError(result.error);
} else if (typeof result.message !== 'undefined') {
this.showSuccess(result.message);
}
},
hideMessage: function() {
$j(this.selectors.error).fadeOut('slow');
$j(this.selectors.success).fadeOut('slow');
},
showError: function(message) {
$j(this.selectors.error).text(message).fadeIn('slow');
},
showSuccess: function(message) {
$j(this.selectors.success).text(message).fadeIn('slow');
}
};
/**
* Magento Enterprise Edition
*
* NOTICE OF LICENSE
*
* This source file is subject to the Magento Enterprise Edition End User License Agreement
* that is bundled with this package in the file LICENSE_EE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.magento.com/license/enterprise-edition
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category design
* @package rwd_enterprise
* @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
* @license http://www.magento.com/license/enterprise-edition
*/
if (!window.Enterprise) {
window.Enterprise = {};
}
if (!Enterprise.CatalogEvent) {
Enterprise.CatalogEvent = {};
}
Enterprise.CatalogEvent.Ticker = Class.create();
Object.extend(Enterprise.CatalogEvent.Ticker.prototype, {
initialize: function (container, seconds) {
this.container = $(container);
this.seconds = seconds;
this.start = new Date();
this.interval = setInterval(this.applyTimer.bind(this), 1000);
this.applyTimer();
},
getEstimate: function () {
var now = new Date();
var result = this.seconds - (now.getTime() - this.start.getTime())/1000;
if (result < 0) {
return 0;
}
return Math.round(result);
},
applyTimer: function () {
var seconds = this.getEstimate();
var daySec = Math.floor(seconds / (3600*24)) * (3600*24);
var hourSec = Math.floor(seconds / 3600) * 3600;
var minuteSec = Math.floor(seconds / 60) * 60;
var secondSec = seconds;
this.container.down('.days').update(this.formatNumber(Math.floor(daySec/(3600*24))));
this.container.down('.hour').update(this.formatNumber(Math.floor((hourSec - daySec)/3600)));
this.container.down('.minute').update(this.formatNumber(Math.floor((minuteSec - hourSec)/60)));
this.container.down('.second').update(this.formatNumber(seconds - minuteSec));
if (daySec > 0) {
this.container.down('.second').previous('.delimiter').hide();
this.container.down('.second').hide();
this.container.down('.days').show();
this.container.down('.days').next('.delimiter').show();
} else {
this.container.down('.days').hide();
this.container.down('.days').next('.delimiter').hide();
this.container.down('.second').previous('.delimiter').show();
this.container.down('.second').show();
}
},
formatNumber: function (number) {
if (number < 10) {
return '0' + number.toString();
}
return number.toString();
}
});
/**
* Magento Enterprise Edition
*
* NOTICE OF LICENSE
*
* This source file is subject to the Magento Enterprise Edition End User License Agreement
* that is bundled with this package in the file LICENSE_EE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.magento.com/license/enterprise-edition
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category design
* @package rwd_enterprise
* @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
* @license http://www.magento.com/license/enterprise-edition
*/
if (!window.Enterprise) {
window.Enterprise = {};
}
if (!Enterprise.Wishlist) {
Enterprise.Wishlist = {
Widget: {
Form: {}
}
};
}
Enterprise.Wishlist.Widget.Form = Class.create(Enterprise.Widget, {
action: null,
isValid: false,
initialize: function($super, action) {
var _templateString = '<ul class="form-list">' +
'<li><label for="wishlist-name">' + Translator.translate('Wishlist Name') + '</label><div class="input-box"><input type="text" id="wishlist-name" maxlength="255" class="input-text required-entry validate-length maximum-length-255" name="name"/></div>' +
'<li class="control"><div class="input-box"><input type="checkbox" id="wishlist-public" name="visibility" class="radio"></div><label for="wishlist-public">' + Translator.translate('Make This Wishlist Public') + '</label></li>' +
'</ul>' +
'<div class="buttons-set form-buttons"><button type="submit" class="button btn-save"><span><span>' + Translator.translate('Save') + '</span></span></button><button type="button" class="button btn-cancel button-secondary"><span><span>' + Translator.translate('Cancel') + '</span></span></button></div>';
this.action = action;
$super(new Element('form', {'method': 'post', 'action': action}));
this._node.update(_templateString);
var that = this;
var deferredList = {
event: null,
counter: 0,
callback: function() {
this.counter++;
if (this.counter >= 2) {
this.success();
}
},
success: function() {
that.onSubmit(this.event);
}
};
var validation = new Validation(this._node, {
onFormValidate: (function(result) {
this.isValid = result;
deferredList.callback();
}).bind(this)
});
Event.observe(this._node, 'submit',
(function(event) {
deferredList.event = event;
deferredList.callback();
}).bind(this)
);
Event.observe($(this._node).down('button.btn-cancel'), 'click',
(function() {
this.onCancel();
}).bind(this)
);
this.nameNode = $(this._node).down('#wishlist-name');
this.visibilityNode = $(this._node).down('#wishlist-public');
},
onSubmit: function(event) {
},
onCancel: function() {
},
setName: function(name) {
this.nameNode.value = name;
},
setIsVisible: function(state) {
this.visibilityNode.checked = !!state;
}
});
Enterprise.Wishlist.Widget.Form.Create = Class.create(Enterprise.Wishlist.Widget.Form, {
useAjax: true,
initialize: function($super, action, useAjax) {
$super(action);
this.useAjax = useAjax;
},
onSubmit: function(event) {
Event.stop(event);
if (!this.isValid) {
return;
}
if (!this.useAjax) {
this.onWishlistCreated({serializedData: $(this._node).serialize()});
} else {
var callback = (function(wishlistId){this.onWishlistCreated(wishlistId)}).bind(this);
new Ajax.Request(this.action, {
method: 'post',
parameters: $(this._node).serialize(),
onSuccess: function(response) {
try {
var data = response.responseJSON;
if (typeof data.wishlist_id != 'undefined') {
callback(data.wishlist_id);
} else if (typeof data.redirect != 'undefined') {
setLocation(data.redirect);
} else {
alert(Translator.translate('Error happened while creating wishlist. Please try again later'));
}
} catch (e) {
setLocation(window.location.href);
}
}
});
}
},
onWishlistCreated: function(wishlist) {
}
});
Enterprise.Wishlist.createWithCallback = function(createUrl, callback, useAjax) {
if (typeof useAjax == 'undefined') {
useAjax = true;
}
if (!Enterprise.Wishlist.createWithCallbackDialog) {
var createWithCallbackForm = new Enterprise.Wishlist.Widget.Form.Create(createUrl, useAjax);
Enterprise.Wishlist.createWithCallbackDialog = new Enterprise.Widget.Dialog(
Translator.translate('Create New Wishlist'),
createWithCallbackForm.getNode()
);
Enterprise.Wishlist.createWithCallbackDialog.form = createWithCallbackForm;
createWithCallbackForm.onCancel = Enterprise.Wishlist.createWithCallbackDialog.hide.bind(Enterprise.Wishlist.createWithCallbackDialog);
Enterprise.Wishlist.createWithCallbackDialog.form.onSubmit = Enterprise.Wishlist.createWithCallbackDialog.form.onSubmit.wrap(function(proceed, event) {
proceed(event);
if (this.isValid) {
Enterprise.Wishlist.createWithCallbackDialog.setBusy(true);
}
})
}
Enterprise.Wishlist.createWithCallbackDialog.form.useAjax = useAjax;
Enterprise.Wishlist.createWithCallbackDialog.form.onWishlistCreated = callback;
Enterprise.Wishlist.createWithCallbackDialog.show();
}
Enterprise.Wishlist.create = function(createUrl, callback) {
if (!Enterprise.Wishlist.createDialog) {
var createForm = new Enterprise.Wishlist.Widget.Form(createUrl);
Enterprise.Wishlist.createDialog = new Enterprise.Widget.Dialog(
Translator.translate('Create New Wishlist'),
createForm.getNode()
);
createForm.onCancel = Enterprise.Wishlist.createDialog.hide.bind(Enterprise.Wishlist.createDialog);
}
Enterprise.Wishlist.createDialog.show();
}
Enterprise.Wishlist.edit = function(editUrl, wishlistName, visibility) {
if (!Enterprise.Wishlist.editDialog) {
var editForm = new Enterprise.Wishlist.Widget.Form(editUrl);
Enterprise.Wishlist.editDialog = new Enterprise.Widget.Dialog(
Translator.translate('Edit Wishlist'),
editForm.getNode()
);
Enterprise.Wishlist.editDialog.form = editForm;
editForm.onCancel = Enterprise.Wishlist.editDialog.hide.bind(Enterprise.Wishlist.editDialog);
}
Enterprise.Wishlist.editDialog.form.setName(wishlistName);
Enterprise.Wishlist.editDialog.form.setIsVisible(visibility);
Enterprise.Wishlist.editDialog.show();
}
Enterprise.Wishlist.getRowQty = function(rowNode) {
var qtyNode = $(rowNode).down('input.qty');
return qtyNode ? qtyNode.value : null;
}
Enterprise.Wishlist.copyItemTo = function(itemId, qty, wishlistId) {
var form = new Element('form', {method: 'post', action: Enterprise.Wishlist.url.copyItem});
form.insert(new Element('input', {name: 'item_id', type: 'hidden', value: itemId}));
if (typeof wishlistId != 'undefined') {
form.insert(new Element('input', {name: 'wishlist_id', type: 'hidden', value: wishlistId}));
}
form.insert(new Element('input', {name: 'qty', type: 'hidden', value: qty}));
$(document.body).insert(form);
form.submit();
};
Enterprise.Wishlist.moveItemTo = function(itemId, qty, wishlistId) {
var form = new Element('form', {method: 'post', action: Enterprise.Wishlist.url.moveItem});
form.insert(new Element('input', {name: 'item_id', type: 'hidden', value: itemId}));
if (typeof wishlistId != 'undefined') {
form.insert(new Element('input', {name: 'wishlist_id', type: 'hidden', value: wishlistId}));
}
form.insert(new Element('input', {name: 'qty', type: 'hidden', value: qty}));
$(document.body).insert(form);
form.submit();
return false;
};
Enterprise.Wishlist.copySelectedTo = function(wishlistId) {
if (!this.itemsSelected()) {
alert(Translator.translate('You must select items to copy'));
return;
}
var url = Enterprise.Wishlist.url.copySelected;
this.form.action = url.gsub('%wishlist_id%', wishlistId);
this.form.submit();
};
Enterprise.Wishlist.moveSelectedTo = function(wishlistId) {
if (!this.itemsSelected()) {
alert(Translator.translate('You must select items to move'));
return;
}
var url = Enterprise.Wishlist.url.moveSelected;
this.form.action = url.gsub('%wishlist_id%', wishlistId);
this.form.submit();
};
Enterprise.Wishlist.itemsSelected = function() {
var selected = false;
$(this.form).select('input.select').each(function(item) {
if ($(item).checked) {
selected = true;
}
});
return selected;
};
Enterprise.Wishlist.copyItemToNew = function(itemId, qty) {
this.createWithCallback(Enterprise.Wishlist.url.create, this.copyItemTo.bind(this, itemId, qty));
};
Enterprise.Wishlist.moveItemToNew = function(itemId, qty) {
this.createWithCallback(Enterprise.Wishlist.url.create, this.moveItemTo.bind(this, itemId, qty));
};
Enterprise.Wishlist.moveSelectedToNew = function() {
if (!this.itemsSelected()) {
alert(Translator.translate('You must select items to move'));
return;
}
this.createWithCallback(Enterprise.Wishlist.url.create, this.moveSelectedTo.bind(this));
};
Enterprise.Wishlist.copySelectedToNew = function() {
if (!this.itemsSelected()) {
alert(Translator.translate('You must select items to copy'));
return;
}
this.createWithCallback(Enterprise.Wishlist.url.create, this.copySelectedTo.bind(this));
};
Event.observe(document, 'dom:loaded', function() {
if (typeof Enterprise.Wishlist.list != 'undefined'
&& (Enterprise.Wishlist.list.length || Enterprise.Wishlist.canCreate)) {
var buildUrl = function(url, wishlist) {
var glue = url.indexOf('?') == -1 ? '?' : '&';
var wishlistInfo = '';
if (typeof wishlist.serializedData != 'undefined') {
wishlistInfo = wishlist.serializedData;
} else {
wishlistInfo = Hash.toQueryString({'wishlist_id': wishlist});
}
return url + glue + wishlistInfo;
}
$$('.link-wishlist').each(function(link) {
var url = link.href;
var onclick = link.onclick || function() {
setLocation(this.href);
}
var wishlistSplitButton = new Enterprise.Widget.SplitButton(link.innerHTML, Translator.translate('Add to Wishlist'), 'light clickable wishlist-selector');
wishlistSplitButton.onClick = onclick.bind({href: url});
Enterprise.Wishlist.list.each(function(wishlist) {
var option = new Enterprise.Widget.SplitButton.Option(wishlist.name);
option.onClick = onclick.bind({href: buildUrl(url, wishlist.id)});
wishlistSplitButton.addOption(option);
});
if (Enterprise.Wishlist.canCreate) {
var option = new Enterprise.Widget.SplitButton.Option(Translator.translate('Create New Wishlist'), 'new');
option.onClick = Enterprise.Wishlist.createWithCallback.bind(this, Enterprise.Wishlist.url.create, function(wishlist) {
(onclick.bind({
href: buildUrl(url, wishlist)
}))();
}, link.hasClassName('use-ajax'));
wishlistSplitButton.addOption(option);
}
wishlistSplitButton.placeAt(link.up());
link.remove();
});
}
});
document.observe("dom:loaded", function() {
$$('#wishlist-table div.description').each(function(el) { Enterprise.textOverflow(el); });
});
/**
* Created by nnderaembe on 16/05/14.
* persistentCache.js uses localStorage when available, and falls back on the userData behavior in IE6 and IE7.
* No flash to slow down page load, no cookies to fatten network requests.
* Optionnaly, data can be compressed before storage (depends on LZString) : set persistentCache.compress to true before storing
* persistentCache.js depends on JSON for serialization to disk.
* Based on https://github.com/marcuswestin/store.js
* Dependencies: JSON, LZString (opt.)
* Licence : The MIT License (MIT) https://github.com/marcuswestin/store.js/blob/master/LICENSE
* Modif: added optional LZString compression option, some refactoring ("use strict", removal of the Function constr. for retrieving the global Obj, loop foreach, etc..)
*/
/*global window*/
(function (win) {
'use strict';
var persistentCache = {},
doc = win.document,
localStorageName = 'localStorage',
scriptTag = 'script',
storage;
persistentCache.disabled = false;
persistentCache.compressEnabled = false;
persistentCache.set = function (key, value) {
};
persistentCache.get = function (key) {
};
persistentCache.remove = function (key) {
};
persistentCache.clear = function () {
};
persistentCache.LZSt = null;
persistentCache.transact = function (key, defaultVal, transactionFn) {
var val = (persistentCache.LZSt === null) ? persistentCache.get(key, true) : persistentCache.LZSt;
if (transactionFn === null) {
transactionFn = defaultVal;
defaultVal = null;
}
if (typeof val === 'undefined') {
val = [defaultVal] || [];
}
transactionFn(val, defaultVal);
persistentCache.set(key, val);
persistentCache.LZSt = val;
};
persistentCache.getAll = function () {
};
persistentCache.forEach = function () {
};
persistentCache.serialize = function (value, key) {
var valueTemp = JSON.stringify(value), valueStr, LZSt = function () {
if (arguments[0].indexOf(arguments[1]) < 0) {
arguments[0].push(arguments[1]);
}
};
if (persistentCache.compressEnabled && win.hasOwnProperty('LZString')) {
valueStr = LZString.compressToUTF16(valueTemp);
persistentCache.compressEnabled = false;
persistentCache.transact('LZSt', key, LZSt);
}
return (valueStr === undefined) ? valueTemp : valueStr;
};
persistentCache.deserialize = function (value, key, ignoreCache) {
var isLZString = (ignoreCache) ? undefined : (persistentCache.LZSt !== null ) ? persistentCache.LZSt : persistentCache.get('LZSt', true), valueStr = value;
if (win.hasOwnProperty('LZString') && isLZString !== undefined && isLZString.indexOf(key) >= 0) {
valueStr = LZString.decompressFromUTF16(value);
}
if (typeof valueStr !== 'string') {
return undefined;
}
try {
return JSON.parse(valueStr);
}
catch (e) {
return valueStr || undefined;
}
};
// Functions to encapsulate questionable FireFox 3.6.13 behavior
// when about.config::dom.storage.enabled === false
// See https://github.com/marcuswestin/store.js/issues#issue/13
function isLocalStorageNameSupported() {
try {
return (localStorageName in win && win[localStorageName]);
}
catch (err) {
return false;
}
}
if (isLocalStorageNameSupported()) {
storage = win[localStorageName];
persistentCache.set = function (key, val) {
if (val === undefined) {
return persistentCache.remove(key);
}
storage.setItem(key, persistentCache.serialize(val, key));
return val;
};
persistentCache.get = function (key, ignoreCache) {
if (ignoreCache === undefined) {
ignoreCache = false;
}
return persistentCache.deserialize(storage.getItem(key), key, ignoreCache);
};
persistentCache.remove = function (key) {
storage.removeItem(key);
};
persistentCache.clear = function () {
storage.clear();
};
persistentCache.getAll = function () {
var ret = {};
persistentCache.forEach(function (key, val) {
ret[key] = val;
});
return ret;
};
persistentCache.forEach = function (callback) {
for (var i = 0; i < storage.length; i++) {
var key = storage.key(i);
callback(key, persistentCache.get(key));
}
};
} else if (doc.documentElement.addBehavior) {
var storageOwner,
storageContainer,
forbiddenCharsRegex = new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]", "g"),
withIEStorage = function (storeFunction) {
return function () {
var args = Array.prototype.slice.call(arguments, 0);
args.unshift(storage);
// See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx
// and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx
storageOwner.appendChild(storage);
storage.addBehavior('#default#userData');
storage.load(localStorageName);
var result = storeFunction.apply(persistentCache, args);
storageOwner.removeChild(storage);
return result;
};
},
// In IE7, keys cannot start with a digit or contain certain chars.
// See https://github.com/marcuswestin/store.js/issues/40
// See https://github.com/marcuswestin/store.js/issues/83
ieKeyFix = function (key) {
return key.replace(/^d/, '___$&').replace(forbiddenCharsRegex, '___');
};
// Since #userData storage applies only to specific paths, we need to
// somehow link our data to a specific path. We choose /favicon.ico
// as a pretty safe option, since all browsers already make a request to
// this URL anyway and being a 404 will not hurt us here. We wrap an
// iframe pointing to the favicon in an ActiveXObject(htmlfile) object
// (see: http://msdn.microsoft.com/en-us/library/aa752574(v=VS.85).aspx)
// since the iframe access rules appear to allow direct access and
// manipulation of the document element, even for a 404 page. This
// document can be used instead of the current document (which would
// have been limited to the current path) to perform #userData storage.
try {
storageContainer = new ActiveXObject('htmlfile');
storageContainer.open();
storageContainer.write('<' + scriptTag + '>document.w=window</' + scriptTag + '><iframe src="/favicon.ico"></iframe>');
storageContainer.close();
storageOwner = storageContainer.w.frames[0].document;
storage = storageOwner.createElement('div');
} catch (e) {
// somehow ActiveXObject instantiation failed (perhaps some special
// security settings or otherwse), fall back to per-path storage
storage = doc.createElement('div');
storageOwner = doc.body;
}
persistentCache.set = withIEStorage(function (storage, key, val) {
key = ieKeyFix(key);
if (val === undefined) {
return persistentCache.remove(key);
}
storage.setAttribute(key, persistentCache.serialize(val, key));
storage.save(localStorageName);
return val;
});
persistentCache.get = withIEStorage(function (storage, key, ignoreCache) {
key = ieKeyFix(key);
if (ignoreCache === undefined) {
ignoreCache = false;
}
return persistentCache.deserialize(storage.getAttribute(key), key, ignoreCache);
});
persistentCache.remove = withIEStorage(function (storage, key) {
key = ieKeyFix(key);
storage.removeAttribute(key);
storage.save(localStorageName);
});
persistentCache.clear = withIEStorage(function (storage) {
var attributes = storage.XMLDocument.documentElement.attributes,
len = attributes.length;
storage.load(localStorageName);
while (0 <= --len) {
var attr = attributes[len];
storage.removeAttribute(attr.name);
}
storage.save(localStorageName);
});
persistentCache.getAll = function (storage) {
var ret = {};
persistentCache.forEach(function (key, val) {
ret[key] = val;
});
return ret;
};
persistentCache.forEach = withIEStorage(function (storage, callback) {
var attributes = storage.XMLDocument.documentElement.attributes,
len = attributes.length;
while (0 <= --len) {
var attr = attributes[len];
callback(attr.name, persistentCache.deserialize(storage.getAttribute(attr.name), attr.name, false));
}
});
}
try {
var testKey = '__storejs__';
persistentCache.set(testKey, testKey);
if (persistentCache.get(testKey) !== testKey) {
persistentCache.disabled = true;
}
persistentCache.remove(testKey);
} catch (e) {
persistentCache.disabled = true;
}
persistentCache.enabled = !persistentCache.disabled;
win.persistentCache = persistentCache;
})(window);
var config = {};
config.tracking = {
namespace: 'nestms',
sCodeNameSpace: 's',
satelliteNameSpace: '_satellite',
disableScode: false,
debug: {
debugMode: false
},
dtm: {
missingValue: "missing",
pendingValue: "pending",
defaultValue: "other",
dataLayerInitialized: "initialized",
dataLayerParsingError: "parsing error"
},
defaults: {
app: {
version: {
type: "string",
allowedValues: ["NC2-classic", "NC2-mosaic"]
},
platform: {
type: "string",
allowedValues: ["desktop-site", "mobile-site", "iOS", "android", "mini-site"]
},
release: {
type: "string",
example: "4.7"
},
channel: {
type: "string",
allowedValues: ["B2C", "B2B"]
},
language: {
type: "string",
regexp: "^\\b[a-z]{2,2}\\b$"
},
country: {
type: "string",
regexp: "^\\b[A-Z]{2,2}\\b$"
},
currency: {
type: "string",
allowedValues: ["CHF", "EUR"]
},
taxSystem: {
type: "string",
allowedValues: ["withTax", "withoutTax"]
}
},
page: {
pageUid: {
type: "string",
example: "myPageName"
},
techno: {
type: "array",
example: "['vertuo']"
},
breadcrumb: {
type: "array",
example: "['coffee','Volluto']"
}
},
user: {
userId: {
type: "string",
example: ""
},
status: {
type: "string",
allowedValues: ["not logged", "logged in", "remember-me"]
},
zip: {
type: "string",
example: "1234"
},
city: {
type: "string",
example: "Lausanne"
}
}
}
};
// Copyright (c) 2013 Pieroxy <pieroxy@pieroxy.net>
// This work is free. You can redistribute it and/or modify it
// under the terms of the WTFPL, Version 2
// For more information see LICENSE.txt or http://www.wtfpl.net/
//
// For more information, the home page:
// http://pieroxy.net/blog/pages/lz-string/testing.html
//
// LZ-based compression algorithm, version 1.3.3
var LZString = {
// private property
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
_f: String.fromCharCode,
compressToBase64: function (input) {
if (input == null) return "";
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = LZString.compress(input);
while (i < input.length * 2) {
if (i % 2 == 0) {
chr1 = input.charCodeAt(i / 2) >> 8;
chr2 = input.charCodeAt(i / 2) & 255;
if (i / 2 + 1 < input.length)
chr3 = input.charCodeAt(i / 2 + 1) >> 8;
else
chr3 = NaN;
} else {
chr1 = input.charCodeAt((i - 1) / 2) & 255;
if ((i + 1) / 2 < input.length) {
chr2 = input.charCodeAt((i + 1) / 2) >> 8;
chr3 = input.charCodeAt((i + 1) / 2) & 255;
} else
chr2 = chr3 = NaN;
}
i += 3;
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
LZString._keyStr.charAt(enc1) + LZString._keyStr.charAt(enc2) +
LZString._keyStr.charAt(enc3) + LZString._keyStr.charAt(enc4);
}
return output;
},
decompressFromBase64: function (input) {
if (input == null) return "";
var output = "",
ol = 0,
output_,
chr1, chr2, chr3,
enc1, enc2, enc3, enc4,
i = 0, f = LZString._f;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = LZString._keyStr.indexOf(input.charAt(i++));
enc2 = LZString._keyStr.indexOf(input.charAt(i++));
enc3 = LZString._keyStr.indexOf(input.charAt(i++));
enc4 = LZString._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
if (ol % 2 == 0) {
output_ = chr1 << 8;
if (enc3 != 64) {
output += f(output_ | chr2);
}
if (enc4 != 64) {
output_ = chr3 << 8;
}
} else {
output = output + f(output_ | chr1);
if (enc3 != 64) {
output_ = chr2 << 8;
}
if (enc4 != 64) {
output += f(output_ | chr3);
}
}
ol += 3;
}
return LZString.decompress(output);
},
compressToUTF16: function (input) {
if (input == null) return "";
var output = "",
i, c,
current,
status = 0,
f = LZString._f;
input = LZString.compress(input);
for (i = 0; i < input.length; i++) {
c = input.charCodeAt(i);
switch (status++) {
case 0:
output += f((c >> 1) + 32);
current = (c & 1) << 14;
break;
case 1:
output += f((current + (c >> 2)) + 32);
current = (c & 3) << 13;
break;
case 2:
output += f((current + (c >> 3)) + 32);
current = (c & 7) << 12;
break;
case 3:
output += f((current + (c >> 4)) + 32);
current = (c & 15) << 11;
break;
case 4:
output += f((current + (c >> 5)) + 32);
current = (c & 31) << 10;
break;
case 5:
output += f((current + (c >> 6)) + 32);
current = (c & 63) << 9;
break;
case 6:
output += f((current + (c >> 7)) + 32);
current = (c & 127) << 8;
break;
case 7:
output += f((current + (c >> 8)) + 32);
current = (c & 255) << 7;
break;
case 8:
output += f((current + (c >> 9)) + 32);
current = (c & 511) << 6;
break;
case 9:
output += f((current + (c >> 10)) + 32);
current = (c & 1023) << 5;
break;
case 10:
output += f((current + (c >> 11)) + 32);
current = (c & 2047) << 4;
break;
case 11:
output += f((current + (c >> 12)) + 32);
current = (c & 4095) << 3;
break;
case 12:
output += f((current + (c >> 13)) + 32);
current = (c & 8191) << 2;
break;
case 13:
output += f((current + (c >> 14)) + 32);
current = (c & 16383) << 1;
break;
case 14:
output += f((current + (c >> 15)) + 32, (c & 32767) + 32);
status = 0;
break;
}
}
return output + f(current + 32);
},
decompressFromUTF16: function (input) {
if (input == null) return "";
var output = "",
current, c,
status = 0,
i = 0,
f = LZString._f;
while (i < input.length) {
c = input.charCodeAt(i) - 32;
switch (status++) {
case 0:
current = c << 1;
break;
case 1:
output += f(current | (c >> 14));
current = (c & 16383) << 2;
break;
case 2:
output += f(current | (c >> 13));
current = (c & 8191) << 3;
break;
case 3:
output += f(current | (c >> 12));
current = (c & 4095) << 4;
break;
case 4:
output += f(current | (c >> 11));
current = (c & 2047) << 5;
break;
case 5:
output += f(current | (c >> 10));
current = (c & 1023) << 6;
break;
case 6:
output += f(current | (c >> 9));
current = (c & 511) << 7;
break;
case 7:
output += f(current | (c >> 8));
current = (c & 255) << 8;
break;
case 8:
output += f(current | (c >> 7));
current = (c & 127) << 9;
break;
case 9:
output += f(current | (c >> 6));
current = (c & 63) << 10;
break;
case 10:
output += f(current | (c >> 5));
current = (c & 31) << 11;
break;
case 11:
output += f(current | (c >> 4));
current = (c & 15) << 12;
break;
case 12:
output += f(current | (c >> 3));
current = (c & 7) << 13;
break;
case 13:
output += f(current | (c >> 2));
current = (c & 3) << 14;
break;
case 14:
output += f(current | (c >> 1));
current = (c & 1) << 15;
break;
case 15:
output += f(current | c);
status = 0;
break;
}
i++;
}
return LZString.decompress(output);
//return output;
},
compress: function (uncompressed) {
if (uncompressed == null) return "";
var i, value,
context_dictionary = {},
context_dictionaryToCreate = {},
context_c = "",
context_wc = "",
context_w = "",
context_enlargeIn = 2, // Compensate for the first entry which should not count
context_dictSize = 3,
context_numBits = 2,
context_data_string = "",
context_data_val = 0,
context_data_position = 0,
ii,
f = LZString._f;
for (ii = 0; ii < uncompressed.length; ii += 1) {
context_c = uncompressed.charAt(ii);
if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
context_dictionary[context_c] = context_dictSize++;
context_dictionaryToCreate[context_c] = true;
}
context_wc = context_w + context_c;
if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) {
context_w = context_wc;
} else {
if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
if (context_w.charCodeAt(0) < 256) {
for (i = 0; i < context_numBits; i++) {
context_data_val = (context_data_val << 1);
if (context_data_position == 15) {
context_data_position = 0;
context_data_string += f(context_data_val);
context_data_val = 0;
} else {
context_data_position++;
}
}
value = context_w.charCodeAt(0);
for (i = 0; i < 8; i++) {
context_data_val = (context_data_val << 1) | (value & 1);
if (context_data_position == 15) {
context_data_position = 0;
context_data_string += f(context_data_val);
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
} else {
value = 1;
for (i = 0; i < context_numBits; i++) {
context_data_val = (context_data_val << 1) | value;
if (context_data_position == 15) {
context_data_position = 0;
context_data_string += f(context_data_val);
context_data_val = 0;
} else {
context_data_position++;
}
value = 0;
}
value = context_w.charCodeAt(0);
for (i = 0; i < 16; i++) {
context_data_val = (context_data_val << 1) | (value & 1);
if (context_data_position == 15) {
context_data_position = 0;
context_data_string += f(context_data_val);
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
}
context_enlargeIn--;
if (context_enlargeIn == 0) {
context_enlargeIn = Math.pow(2, context_numBits);
context_numBits++;
}
delete context_dictionaryToCreate[context_w];
} else {
value = context_dictionary[context_w];
for (i = 0; i < context_numBits; i++) {
context_data_val = (context_data_val << 1) | (value & 1);
if (context_data_position == 15) {
context_data_position = 0;
context_data_string += f(context_data_val);
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
}
context_enlargeIn--;
if (context_enlargeIn == 0) {
context_enlargeIn = Math.pow(2, context_numBits);
context_numBits++;
}
// Add wc to the dictionary.
context_dictionary[context_wc] = context_dictSize++;
context_w = String(context_c);
}
}
// Output the code for w.
if (context_w !== "") {
if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
if (context_w.charCodeAt(0) < 256) {
for (i = 0; i < context_numBits; i++) {
context_data_val = (context_data_val << 1);
if (context_data_position == 15) {
context_data_position = 0;
context_data_string += f(context_data_val);
context_data_val = 0;
} else {
context_data_position++;
}
}
value = context_w.charCodeAt(0);
for (i = 0; i < 8; i++) {
context_data_val = (context_data_val << 1) | (value & 1);
if (context_data_position == 15) {
context_data_position = 0;
context_data_string += f(context_data_val);
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
} else {
value = 1;
for (i = 0; i < context_numBits; i++) {
context_data_val = (context_data_val << 1) | value;
if (context_data_position == 15) {
context_data_position = 0;
context_data_string += f(context_data_val);
context_data_val = 0;
} else {
context_data_position++;
}
value = 0;
}
value = context_w.charCodeAt(0);
for (i = 0; i < 16; i++) {
context_data_val = (context_data_val << 1) | (value & 1);
if (context_data_position == 15) {
context_data_position = 0;
context_data_string += f(context_data_val);
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
}
context_enlargeIn--;
if (context_enlargeIn == 0) {
context_enlargeIn = Math.pow(2, context_numBits);
context_numBits++;
}
delete context_dictionaryToCreate[context_w];
} else {
value = context_dictionary[context_w];
for (i = 0; i < context_numBits; i++) {
context_data_val = (context_data_val << 1) | (value & 1);
if (context_data_position == 15) {
context_data_position = 0;
context_data_string += f(context_data_val);
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
}
context_enlargeIn--;
if (context_enlargeIn == 0) {
context_enlargeIn = Math.pow(2, context_numBits);
context_numBits++;
}
}
// Mark the end of the stream
value = 2;
for (i = 0; i < context_numBits; i++) {
context_data_val = (context_data_val << 1) | (value & 1);
if (context_data_position == 15) {
context_data_position = 0;
context_data_string += f(context_data_val);
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
// Flush the last char
while (true) {
context_data_val = (context_data_val << 1);
if (context_data_position == 15) {
context_data_string += f(context_data_val);
break;
}
else context_data_position++;
}
return context_data_string;
},
decompress: function (compressed) {
if (compressed == null) return "";
if (compressed == "") return null;
var dictionary = [],
next,
enlargeIn = 4,
dictSize = 4,
numBits = 3,
entry = "",
result = "",
i,
w,
bits, resb, maxpower, power,
c,
f = LZString._f,
data = {string: compressed, val: compressed.charCodeAt(0), position: 32768, index: 1};
for (i = 0; i < 3; i += 1) {
dictionary[i] = i;
}
bits = 0;
maxpower = Math.pow(2, 2);
power = 1;
while (power != maxpower) {
resb = data.val & data.position;
data.position >>= 1;
if (data.position == 0) {
data.position = 32768;
data.val = data.string.charCodeAt(data.index++);
}
bits |= (resb > 0 ? 1 : 0) * power;
power <<= 1;
}
switch (next = bits) {
case 0:
bits = 0;
maxpower = Math.pow(2, 8);
power = 1;
while (power != maxpower) {
resb = data.val & data.position;
data.position >>= 1;
if (data.position == 0) {
data.position = 32768;
data.val = data.string.charCodeAt(data.index++);
}
bits |= (resb > 0 ? 1 : 0) * power;
power <<= 1;
}
c = f(bits);
break;
case 1:
bits = 0;
maxpower = Math.pow(2, 16);
power = 1;
while (power != maxpower) {
resb = data.val & data.position;
data.position >>= 1;
if (data.position == 0) {
data.position = 32768;
data.val = data.string.charCodeAt(data.index++);
}
bits |= (resb > 0 ? 1 : 0) * power;
power <<= 1;
}
c = f(bits);
break;
case 2:
return "";
}
dictionary[3] = c;
w = result = c;
while (true) {
if (data.index > data.string.length) {
return "";
}
bits = 0;
maxpower = Math.pow(2, numBits);
power = 1;
while (power != maxpower) {
resb = data.val & data.position;
data.position >>= 1;
if (data.position == 0) {
data.position = 32768;
data.val = data.string.charCodeAt(data.index++);
}
bits |= (resb > 0 ? 1 : 0) * power;
power <<= 1;
}
switch (c = bits) {
case 0:
bits = 0;
maxpower = Math.pow(2, 8);
power = 1;
while (power != maxpower) {
resb = data.val & data.position;
data.position >>= 1;
if (data.position == 0) {
data.position = 32768;
data.val = data.string.charCodeAt(data.index++);
}
bits |= (resb > 0 ? 1 : 0) * power;
power <<= 1;
}
dictionary[dictSize++] = f(bits);
c = dictSize - 1;
enlargeIn--;
break;
case 1:
bits = 0;
maxpower = Math.pow(2, 16);
power = 1;
while (power != maxpower) {
resb = data.val & data.position;
data.position >>= 1;
if (data.position == 0) {
data.position = 32768;
data.val = data.string.charCodeAt(data.index++);
}
bits |= (resb > 0 ? 1 : 0) * power;
power <<= 1;
}
dictionary[dictSize++] = f(bits);
c = dictSize - 1;
enlargeIn--;
break;
case 2:
return result;
}
if (enlargeIn == 0) {
enlargeIn = Math.pow(2, numBits);
numBits++;
}
if (dictionary[c]) {
entry = dictionary[c];
} else {
if (c === dictSize) {
entry = w + w.charAt(0);
} else {
return null;
}
}
result += entry;
// Add w+entry[0] to the dictionary.
dictionary[dictSize++] = w + entry.charAt(0);
enlargeIn--;
w = entry;
if (enlargeIn == 0) {
enlargeIn = Math.pow(2, numBits);
numBits++;
}
}
}
};
if (typeof module !== 'undefined' && module != null) {
module.exports = LZString
}
var utilities = (function () {
/*
* Array.prototype.isArray
*
* Add property to enrich Array prototype, because instanceof does not differentiate between Object and Array
* http://stackoverflow.com/questions/767486/how-do-you-check-if-a-variable-is-an-array-in-javascript
*
*/
Array.prototype.isArray = true;
return {
/*
log
*/
log: function () {
'use strict';
/* global console */
try {
console.log.apply(console, arguments);
}
catch (e) {
}
},
/*
* Decorator to return the fn argument if test on condition passes,
* empty function otherwise
*/
conditionalFunction: function (condition, fn) {
'use strict';
return (condition) ? fn : function () {
};
},
/*
* isEmpty
*/
isEmpty: function (obj) {
'use strict';
// null and undefined are empty
if (obj === null) {
return true;
}
// Assume if it has a length property with a non-zero value
// that that property is correct.
if (obj.length && obj.length > 0) {
return false;
}
if (obj.length === 0) {
return true;
}
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
return false;
}
}
// Doesn't handle toString and toValue enumeration bugs in IE < 9
return true;
}
};
})();
var nestmsConfig = window.config.tracking,
namespace = nestmsConfig.namespace,
sCodeNP = nestmsConfig.sCodeNameSpace || false,
satellite = window[nestmsConfig.satelliteNameSpace] || false,
rawNestms = window[nestmsConfig.namespace] || false,
mustDisableOldScode = function () {
return (satellite && satellite.getVar('Must disable old Scode') === 'yes') ? true : false;
},
persistentStorage = (function () {
var now = function () {
var dateObj = new Date();
return dateObj.getTime();
},
name = namespace + 'Str',
sessionToken = (satellite && parseInt(satellite.readCookie(name), 10) > 0) ? parseInt(satellite.readCookie(name), 10) : now(),
load = function (key) {
return (isValid(persistentStorage.cache, key)) ? persistentStorage.cache[key].data : undefined;
},
save = function (key, value, expire) {
return false;
},
store = function (cache) {
if (!!compressor) {
persistentCache.compressEnabled = true;
}
return persistentCache.set(name, cache);
},
init = function () {
return false;
},
cached,
cache = {},
isValid = function (c, k) {
return cache.hasOwnProperty(k) && ((c[k].sessionToken === sessionToken || c[k].userToken === window[namespace].DataLayer.user.clubMemberId) && c[k].expire > now());
},
persistentCache = (window.persistentCache && !window.persistentCache.disabled) ? window.persistentCache : false,
compressor = window.LZString || false;
if (persistentCache) {
cached = persistentCache.get(name);
cache = typeof cached === 'object' ? cached : {};
init = function () {
var c = persistentStorage.cache;
if (satellite) {
satellite.setCookie(name, sessionToken);
}
for (var p in c) {
if (!isValid(c, p)) {
delete c[p];
}
}
return store(c);
};
save = function (key, value, expire) {
var expInt = parseInt(expire, 10) || 0,
exp = (expInt > 0) ? 1000 * 60 * expInt + now() : 1000 * 60 * 30 + now(),
cache = persistentStorage.cache;
cache[key] = {
expire: exp,
userToken: (window[namespace].DataLayer.user.clubMemberId === '') ? false : window[namespace].DataLayer.user.clubMemberId,
sessionToken: sessionToken,
data: value
};
return store(cache);
};
}
return {
cache: cache,
init: init,
load: load,
save: save
};
})(),
setDebugMode = function (debugMode, val) {
var t = typeof val === 'undefined',
d = (t) ? 'debugMode' : debugMode,
v = (t) ? debugMode : val,
bv = !!v;
if (typeof v !== 'boolean' && (d === 'debugMode' || d === 'tracelog')) {
utilities.log('enableTraceLog accepts only boolean values true or false');
} else {
nestmsConfig.debug[d] = v;
persistentStorage.save('debug', nestmsConfig.debug, 600);
if (satellite) {
satellite.setDebug(bv);
}
}
},
/*
* Exposed object for API and DataLayer
*/
Nestms = (function () {
return {
enableTraceLog: function (d, v) {
setDebugMode(d, v);
},
// define log function only if debugMode enabled
log: (persistentStorage.cache.debug && persistentStorage.cache.debug.data.debugMode) ? utilities.log : function () {},
DataLayer: {},
API: {
save: persistentStorage.save,
load: persistentStorage.load
}
};
})(),
/*
* Object to hide 'private' methods
*/
Lbt = (function () {
return {
enableTraceLog: function (b) {
setDebugMode('tracelog', b);
setDebugMode(b);
},
// expose utilities
utilities: utilities,
// define log function only if debugMode enabled
log: (persistentStorage.cache.debug && persistentStorage.cache.debug.data.tracelog) ? utilities.log : function () {},
// expose namespace and satellite from the config to the private obj
namespace: namespace,
satellite: satellite,
sCodeNP: sCodeNP,
sCodeLegacy: function () {
return window[sCodeNP] || false;
},
// define the internal data layer
dl: {
components: [],
products: [],
page: {},
order: {},
error: {}
},
resetOrder: false, // used on order-confirmation page to clean/remove order from the persistent storage
initPersStorage: persistentStorage.init,
cache: persistentStorage.cache,
save: persistentStorage.save,
load: persistentStorage.load,
customActions: {},
registerCustomAction: function (eventName, eventType, elementId) {
this.customActions[eventName] = {
'eventName': eventName,
'eventType': eventType,
'elementId': elementId
};
},
//check if the old legacy s_code must be disabled
mustDisableOldScode: mustDisableOldScode,
disableOldScode: function () {
if (satellite && this.mustDisableOldScode()) {
Nestms.log('Server-side s_code implementation successfully disabled.');
return {
msg: [
'Scode disabled, ',
'detected attempt to fire event : '
],
registerSCodeLegacyAction: function () {
var eventName = [].shift.call(arguments),
isNotTracked = true,
trackedEvents = satellite.directCallRules,
tl = trackedEvents.length,
debugMode = nestmsConfig.debug.debugMode ||
nestmsConfig.debug.tracelog,
params = {
oldScode: _Lbt.sCodeLegacy()
};
if (arguments.length > 0) {
params.parameters = arguments;
}
Lbt.registerCustomAction(eventName, 'sCodeLegacy', params);
if (trackedEvents.length > 0) {
for (var i = 0; i < tl; i++) {
if (trackedEvents[i].name === eventName) {
satellite.track(eventName);
isNotTracked = false;
}
}
}
// redirect for linktracking type tags, disabled in debug mode
if (isNotTracked && arguments[4] === 'navigate' && !debugMode) {
window.location = arguments[0].href;
}
},
t: function () {
this.registerSCodeLegacyAction('pageView');
window[Lbt.namespace].log(this.msg[0] + this.msg[1] + 'pageView');
return false;
},
tl: function () {
[].unshift.call(arguments, 'linkTracking');
this.registerSCodeLegacyAction.apply(this, arguments);
window[Lbt.namespace].log(this.msg[0] + this.msg[1] + 'linkTracking (redirect is disabled in debugMode)');
return false;
},
loadModule: function (n) {
window[Lbt.namespace].log(this.msg[0] + 'detected attempt to load module : ' + n);
},
c_w: function () {
[].unshift.call(arguments, 'writeCookie');
this.registerSCodeLegacyAction.apply(this, arguments);
return true;
},
c_r: satellite.readCookie,
m_i: function (n) {
return false;
},
Integrate: {}
};
} else { //see onPageBottom for disabling Analytics DTM tool
return window.s_gi(window.s_account);
}
},
/*
* methods are wrapped/decorated with utilities.conditionalFunction to return an empty function if satellite is not defined
* (in the case of Adobe script not included) to avoid 'not defined' errors
*/
/*
* If a page on load has some dynamic content, wait for it before
* sending the green light to satellite
*/
isPageFullyLoaded: true,
pageFullyLoaded: function () {
this.isPageFullyLoaded = true;
this.onPageBottom();
},
onPageBottom: utilities.conditionalFunction(satellite, function () {
satellite.pageBottom();
if (this.isPageFullyLoaded) {
this.fillDataLayer();
// if mustDisableOldScode is defined
if (this.mustDisableOldScode) {
if (!this.mustDisableOldScode() && (!nestmsConfig.debug.hasOwnProperty('sca') || !nestmsConfig.debug.sca)) {
var tools = satellite.tools;
for (var sc in tools) {
if (tools.hasOwnProperty(sc) && tools[sc].hasOwnProperty('settings') && tools[sc].settings.engine === "sc") {
satellite.tools[sc].settings.initTool = false;
}
}
}
}
this.registerCustomAction('dataLayerFullyLoaded','pageLoad',document);
satellite.track('dataLayerFullyLoaded');
} else {
this.log('Page bottom event delayed...');
}
}),
completePage: utilities.conditionalFunction(satellite, function () {
if (!window[namespace].DataLayer.page.hasOwnProperty('pageName')) {
window[namespace].DataLayer.page.pageName = (this.sCodeLegacy()) ? this.sCodeLegacy().pageName : (Object.prototype.hasOwnProperty.call(window,'pageTagName')) ? window.pageTagName : '';
}
if (!window[namespace].DataLayer.page.hasOwnProperty('breadcrumb')) {
window[namespace].DataLayer.page.breadcrumb = (this.sCodeLegacy()) ? [this.sCodeLegacy().channel] : (Object.prototype.hasOwnProperty.call(window,'pageTagsChannel')) ? [window.pageTagsChannel] : [];
}
}),
/*
* Validate obj properties against config defaults.
* obj structure has to be coherent with defaults structure.
*/
validateDataProperty: utilities.conditionalFunction(satellite, function (configDefaultProperty, obj) {
var that = this;
function nestedCheck(objToCheck, objValidRules) {
var isValid = true;
for (var prop in objToCheck) {
if (objToCheck.hasOwnProperty(prop)) {
// check if there is a validation rule defined
if (objValidRules.hasOwnProperty(prop)) {
if (typeof objToCheck[prop] === 'object' && !objToCheck[prop].isArray && objToCheck[prop] !== null) {
// this is a nested object, go inside to check
isValid = nestedCheck(objToCheck[prop], objValidRules[prop]);
}
else {
var validType = false,
validValue = false;
// basic type or array, validate
switch (objValidRules[prop].type) {
case 'string':
validType = typeof objToCheck[prop] === 'string';
if (validType) {
// check if the value is valid
if (objValidRules[prop].hasOwnProperty('allowedValues')) {
validValue = objValidRules[prop].allowedValues.indexOf(objToCheck[prop]) > 0;
}
else if (objValidRules[prop].hasOwnProperty('regexp')) {
var pattern = new RegExp(objValidRules[prop].regexp, 'g');
validValue = objToCheck[prop].match(pattern); // return null if no match
}
else {
validValue = objToCheck[prop] !== '';
}
}
break;
case 'array':
validType = objToCheck[prop].isArray;
if (validType) {
// check value
validValue = !Lbt.utilities.isEmpty(objToCheck[prop]);
}
break;
default:
that.log('Lbt: type', objValidRules[prop].type, 'not handled by validation');
if (!validType) {
that.log('Lbt: Type of', objToCheck[prop], 'not valid for', prop);
objToCheck[prop] = nestmsConfig.dtm.missingValue;
isValid = false;
}
if (!validValue) {
that.log('Lbt: Value', objToCheck[prop], 'not valid for', prop);
objToCheck[prop] = nestmsConfig.dtm.missingValue;
isValid = false;
}
}
}
} // else no validation rules defined for this property
if (!isValid) {
// exit because validation failed
return isValid;
}
}
}
}
if (nestmsConfig.defaults.hasOwnProperty(configDefaultProperty)) {
return nestedCheck(obj, nestmsConfig.defaults[configDefaultProperty]);
}
return true;
})
};
})();
Nestms.DataLayer.app = {};
Lbt.setApp = Lbt.utilities.conditionalFunction(satellite, function (app) {
if (app && !Lbt.utilities.isEmpty(app)) {
Lbt.validateDataProperty('app', app);
Nestms.DataLayer.app = app;
}
});
Nestms.DataLayer.page = {};
Lbt.setPage = Lbt.utilities.conditionalFunction(satellite, function (page) {
if (page && !Lbt.utilities.isEmpty(page)) {
Lbt.validateDataProperty('page', page);
// extend if page has been already filled
if (Nestms.DataLayer.page && !Lbt.utilities.isEmpty(Nestms.DataLayer.page)) {
for (var p in page) {
if (page.hasOwnProperty(p)) {
Nestms.DataLayer.page[p] = page[p];
}
}
} else {
Nestms.DataLayer.page = page;
}
}
});
Nestms.DataLayer.user = {};
Lbt.setUser = Lbt.utilities.conditionalFunction(satellite, function (user) {
Lbt.validateDataProperty('user', user);
Nestms.DataLayer.user = user;
});
Nestms.DataLayer.error = {};
Lbt.setError = Lbt.utilities.conditionalFunction(satellite, function (error) {
if (error && !Lbt.utilities.isEmpty(error)) {
Lbt.validateDataProperty('error', error);
Nestms.DataLayer.error = {
errorCode: error.errorCode,
errorType: error.errorType
};
Lbt.log('Lbt: error set', Nestms.DataLayer.error);
}
});
Nestms.DataLayer.orderRecap = {};
Lbt.setOrderRecap = function (orderRecap) {
if (orderRecap && !Lbt.utilities.isEmpty(orderRecap)) {
Nestms.DataLayer.orderRecap = orderRecap;
}
};
Lbt.init = function () {
// init
// load configuration from storage
nestmsConfig.debug = persistentStorage.load('debug') || nestmsConfig.debug;
var conf = nestmsConfig.debug,
sca = conf.hasOwnProperty('sca') && typeof conf.sca === 'string';
//include hardCoded nestms obj
if (rawNestms && rawNestms.DataLayer) {
if (rawNestms.DataLayer.app) {
this.setApp(rawNestms.DataLayer.app);
}
if (rawNestms.DataLayer.page) {
this.setPage(rawNestms.DataLayer.page);
}
if (rawNestms.DataLayer.user) {
this.setUser(rawNestms.DataLayer.user);
}
if (rawNestms.DataLayer.error) {
this.setError(rawNestms.DataLayer.error);
}
if (rawNestms.DataLayer.orderRecap) {
this.setOrderRecap(rawNestms.DataLayer.orderRecap);
}
if (satellite) {
this.registerCustomAction('dataLayerAppPageUserLoaded','pageLoad',document);
satellite.track('dataLayerAppPageUserLoaded');
}
}
// override satellite.firePageLoadEvent to prevent it of firing onPageBottom and DomReady events
// before the DataLayer complete initialisation and
// disable Analytics tools if old server side implementation is still in use.
// except if s_account is overwritten by calling nestms.setDebugMode('sca', [account ID])
if (satellite) {
if (sca) {
var tools = satellite.tools;
for (var sc in tools) {
if (tools.hasOwnProperty(sc) && tools[sc].settings.engine === "sc") {
satellite.tools[sc].settings.account = conf.sca;
}
}
}
}
return Nestms;
};
window[namespace] = Lbt.init();
window._Lbt = Lbt;
var satellite = Lbt.satellite,
lbtNamespace = 'lbt',
// component
cmpData = lbtNamespace + '-component',
cmpClass = '.' + lbtNamespace + '-component',
// product
prodData = lbtNamespace + '-product',
prodClass = '.' + lbtNamespace + '-product',
// page
pageData = lbtNamespace + '-page',
pageClass = '.' + lbtNamespace + '-page';
/* DATA LAYER ************************************************************/
/*
Nestms.DataLayer.components = {
elementId: {
type
element
elementId
contentId
actions: {
action
eventName
eventType
}
position
orderIndex
layout
dynamic
listStyle
step
state
info
parentComp
childComp
}
}
*/
Nestms.DataLayer.components = {};
Lbt.components = (function () {
function getComponentsByType(cmpType) {
var l = [];
for (var key in Nestms.DataLayer.components) {
if (Nestms.DataLayer.components.hasOwnProperty(key)) {
var current = Nestms.DataLayer.components[key];
if (current.type === cmpType) {
l.push(current);
}
}
}
return l;
}
function getParent(elementId) {
var cmp = Nestms.DataLayer.components[elementId];
if (cmp) {
if (cmp.hasOwnProperty('parentComp')) {
// previously cached
return Nestms.DataLayer.components[cmp.parentComp];
}
else {
// find the parent component by .class, avoiding to select itself (with closest())
var $parent = cmp.element.parent().closest(cmpClass);
if ($parent && $parent.length > 0 && $parent.attr('id') && Nestms.DataLayer.components[$parent.attr('id')]) {
// cache it
Nestms.DataLayer.components[elementId].parentComp = $parent.attr('id');
return Nestms.DataLayer.components[$parent.attr('id')];
}
}
}
}
function getChildren(elementId) {
var cmp = Nestms.DataLayer.components[elementId];
if (cmp) {
if (cmp.hasOwnProperty('childComp') && cmp.childComp.isArray) {
// previously cached
return Nestms.DataLayer.components[elementId].childComp.map(function (childId) {
return Nestms.DataLayer.components[childId];
});
}
else {
/*
* Given the parent component, find the component children, without
* selecting nested components (children with degree > first)
*/
var orderIndex = 1,
$parent = cmp.element;
Nestms.DataLayer.components[elementId].childComp = [];
var children = $parent.find(cmpClass).map(function () {
var $p = $(this).parents(cmpClass);
// find the immediate parent and compare it with the argument parent
if ($p.length > 0 && $p.first().attr('id') === $parent.attr('id') && Nestms.DataLayer.components[this.id]) {
// this is the immediate child of the list
// set the property orderIndex
Nestms.DataLayer.components[this.id].orderIndex = orderIndex.toString();
orderIndex += 1;
// cache it
Nestms.DataLayer.components[elementId].childComp.push(this.id);
return Nestms.DataLayer.components[this.id];
}
});
// if the component is a list, count and set the contentLength
if (cmp.hasOwnProperty('listStyle')) {
switch (cmp.listStyle) {
case 'grid':
case 'horizontal':
case 'vertical':
Nestms.DataLayer.components[elementId].contentLength = children.length.toString();
break;
}
}
return children;
}
}
}
function getPosition(elementId) {
var cmp = Nestms.DataLayer.components[elementId];
if (cmp) {
var childOffset = cmp.element.offset(),
parent = getParent(cmp.elementId);
// check if the element is an element of a list, by checking if the parent has the prop. listStyle
if (parent && parent.hasOwnProperty('listStyle')) {
// find children to set orderIndex
getChildren(parent.elementId);
// get the orderIndex in the list
var orderIndex = Nestms.DataLayer.components[elementId].orderIndex;
// calculate the position based on the list container
var parentOffset = parent.element.offset(),
pos = Helpers.getPosition({
parent: {w: parent.element.width(), h: parent.element.height(), top: parentOffset.top, left: parentOffset.left},
child: {top: childOffset.top, left: childOffset.left}
});
// extend the obj with orderIndex if defined
pos.orderIndex = orderIndex;
return pos;
}
// the parent is not a list, calculate its position relative to the site content
var jDocument = $(document),
jContainerWidth = Lbt.containerWidthClass ? $(Lbt.containerWidthClass) : jDocument, // use document if the class is not present
containerWidth = jContainerWidth.length ? jContainerWidth.width() : jDocument.width(),
containerHeight = jDocument.height(),
containerLeft = jContainerWidth.length ? jContainerWidth.offset().left : 0;
return Helpers.getPosition({
parent: {w: containerWidth, h: containerHeight, top: 0, left: containerLeft},
child: {top: childOffset.top, left: childOffset.left}
});
}
}
function highlight(elementId) {
var cmp = Nestms.DataLayer.components[elementId];
if (cmp) {
var el = document.getElementById(cmp.elementId);
if (el) {
el.style.border = '1px dotted red';
el.style.margin = '1px';
}
}
}
/*
* Enrich component obj with missing properties
*/
function _bindComponent(item) {
item.element = $(document.getElementById(item.elementId));
if (item.element) {
// state: change it only if not hard-coded
if (!item.hasOwnProperty('state')) {
item.state = (item.element.is(':visible')) ? 'active' : 'hidden';
}
// actions
if (item.hasOwnProperty('actions')) {
Lbt.registerCustomAction(item.actions.eventName, item.actions.eventType, item.elementId);
}
// sanitize
if (item.hasOwnProperty('contentId')) {
item.contentId = Helpers.sanitizeContentId(item.contentId);
}
// as last, if state selected, this is the currentProductId
if (item.state === 'selected' && item.hasOwnProperty('contentId')) {
Lbt.currentProductId = item.contentId;
}
return item;
}
else {
Lbt.log('Error: DOM id not bound to component', item);
}
}
function add(cmps) {
if (cmps && !Lbt.utilities.isEmpty(cmps)) {
if (cmps.isArray) {
cmps.map(function (item) {
if (!(item.elementId in Nestms.DataLayer.components)) {
item = _bindComponent(item);
if (item) {
Nestms.DataLayer.components[item.elementId] = item;
Lbt.log('Lbt: component added', item);
}
}
});
} else {
if (!(cmps.elementId in Nestms.DataLayer.components)) {
cmps = _bindComponent(cmps);
if (cmps) {
Nestms.DataLayer.components[cmps.elementId] = cmps;
Lbt.log('Lbt: component added', cmps);
}
}
}
}
}
return {
getComponentsByType: Lbt.utilities.conditionalFunction(satellite, getComponentsByType),
add: Lbt.utilities.conditionalFunction(satellite, add),
getParent: Lbt.utilities.conditionalFunction(satellite, getParent),
getChildren: Lbt.utilities.conditionalFunction(satellite, getChildren),
getPosition: Lbt.utilities.conditionalFunction(satellite, getPosition),
highlight: Lbt.utilities.conditionalFunction(satellite, highlight)
};
}) ();
/*
Nestms.DataLayer.products = {
productId: {
productId
price
techno
type
name
}
}
*/
Nestms.DataLayer.products = {};
Lbt.products = (function () {
// add one or multiple products to the data layer and return the ids of the added products
function add(prods) {
if (prods && !Lbt.utilities.isEmpty(prods)) {
if (prods.isArray) {
return prods.map(function (item) {
if (!(item.productId in Nestms.DataLayer.products)) {
item = prepareProduct(item);
Nestms.DataLayer.products[item.productId] = item;
Lbt.log('Lbt: product added', item);
}
return item.productId;
});
} else {
// single element
if (!(prods.productId in Nestms.DataLayer.products)) {
prods = prepareProduct(prods);
Nestms.DataLayer.products[prods.productId] = prods;
Lbt.log('Lbt: product added', prods);
}
return prods.productId;
}
}
}
function prepareProduct(p) {
p.productId = Helpers.sanitizeContentId(p.productId);
p.productIdLocale = Helpers.sanitizeContentId(p.productIdLocale);
p.price = Helpers.sanitizePrice(p.price);
p.type = Helpers.sanitizeTypes(p.type);
p.techno = (p.hasOwnProperty('techno') && p.techno.isArray) ? Helpers.getTechnos(p.techno) : {};
return p;
}
// return a product by its id or IdLocale
function getByIdOrLocale(productId) {
if (productId in Nestms.DataLayer.products) {
return Nestms.DataLayer.products[productId];
}
else {
for (var key in Nestms.DataLayer.products) {
if (Nestms.DataLayer.products.hasOwnProperty(key) && Nestms.DataLayer.products[key].productIdLocale === productId) {
return Nestms.DataLayer.products[key];
}
}
}
}
return {
add: Lbt.utilities.conditionalFunction(satellite, add),
getByIdOrLocale: Lbt.utilities.conditionalFunction(satellite, getByIdOrLocale)
};
}) ();
/*
Lbt.cart:
Nestms.DataLayer.cart: {
lastChange: {},
products: {
productId: {
product,
quantity
},
...
}
}
*/
Nestms.DataLayer.cart = {};
/* To use the cart:
* - setOrigin as first: the sourceElementId
* - add/remove products
* - notify: trigger the event cartUpdate
*/
// the cart is also stored on client-side because CartManager is storing only few info for each product
Lbt.cart = (function () {
function updateLastChange(qty, prevQty, productId, action){
Nestms.DataLayer.cart.lastChange = {
action: action,
productId: productId,
previousValue: prevQty,
currentValue: qty,
sourceElementId: Nestms.DataLayer.cart.lastChange.sourceElementId
};
Lbt.async.update({
eventName: 'cartUpdate',
eventType: {
cartEvent: action,
cartPreviousQty: prevQty,
cartCurentQty: qty
},
sourceElementId: Nestms.DataLayer.cart.lastChange.sourceElementId,
targetElementId: null,
contentId: productId,
success: true
});
}
function resetLastChange() {
Nestms.DataLayer.cart.lastChange = {
action: '', // added, removed, quantityChanged
productId: null, // product changed
previousValue: null,
currentValue: null,
sourceElementId: null
};
Lbt.async.reset();
}
function init() {
// on page load, retrieve the cart (if saved) from the client storage
Nestms.DataLayer.cart = Lbt.load('cart') || {
products: {}
};
resetLastChange();
Lbt.log('Lbt: cart init', Nestms.DataLayer.cart);
}
// keep track of the source component
function setOrigin(DOMElement) {
Nestms.DataLayer.cart.lastChange.sourceElementId = null;
// find all the parent components to retrieve the cmp type = 'product'
var jParents = $(DOMElement).parents(cmpClass);
if (jParents.length) {
for (var i = 0, len = jParents.length; i < len; i++) {
var elId = jParents[i].id,
cmp = Nestms.DataLayer.components[elId];
if (cmp && (cmp.type === 'product' || cmp.type === 'push')) {
Nestms.DataLayer.cart.lastChange.sourceElementId = cmp.elementId;
if (cmp.type === 'product') {
// if this cmp has a parent and it is of type 'push', the parent will be the sourceElementId
var parentCmp = Lbt.components.getParent(cmp.elementId);
// check if the parent of parentCmp is of type 'push'
if (parentCmp && parentCmp.type === 'push') {
Nestms.DataLayer.cart.lastChange.sourceElementId = parentCmp.elementId;
}
}
break;
}
} // end for
}
}
// update the cart and set lastEvent
function add(productId, quantity) {
productId = Helpers.sanitizeContentId(productId);
quantity = quantity.toString();
var updated = false,
p = getProduct(productId);
if (p) {
// product in the cart, just change the quantity
if (quantity !== Nestms.DataLayer.cart.products[p.productId].quantity) {
// product already in the cart, quantity changed
updateLastChange(quantity, Nestms.DataLayer.cart.products[p.productId].quantity, p.productId, 'quantityChanged');
// update quantity in the cart
Nestms.DataLayer.cart.products[p.productId].quantity = quantity;
updated = true;
}
} else {
// add a product to cart, it should be already in DataLayer.products
var product = Lbt.products.getByIdOrLocale(productId);
if (product) {
// change lastChange action
updateLastChange(quantity, null, product.productId, 'added');
// add product to the cart
Nestms.DataLayer.cart.products[product.productId] = {
product: product,
quantity: quantity
};
// set as currentProduct
Lbt.currentProductId = product.productId;
updated = true;
} else {
Lbt.log('Error: product with id', productId, 'not found in DataLayer.products');
}
}
if (updated) {
// update the local cart
Lbt.save('cart', Nestms.DataLayer.cart);
Lbt.log('Lbt: cart changed', Nestms.DataLayer.cart.lastChange);
}
}
function remove(productId) {
productId = Helpers.sanitizeContentId(productId);
var product = getProduct(productId);
if (product) {
// save lastChange and remove the product from the cart
updateLastChange(null, Nestms.DataLayer.cart.products[productId].quantity, productId, 'removed');
delete Nestms.DataLayer.cart.products[productId];
Lbt.save('cart', Nestms.DataLayer.cart);
Lbt.log('Lbt: product', productId, 'removed from the cart');
}
}
// find if a product is in the cart searching by productId and productIdLocale
function getProduct(productId) {
if (Nestms.DataLayer.cart.products && !Lbt.utilities.isEmpty(Nestms.DataLayer.cart.products)) {
if (productId in Nestms.DataLayer.cart.products) {
return Nestms.DataLayer.cart.products[productId].product;
}
for (var key in Nestms.DataLayer.cart.products) {
if (Nestms.DataLayer.cart.products.hasOwnProperty(key)) {
if (Nestms.DataLayer.cart.products[key].product.productIdLocale === productId) {
return Nestms.DataLayer.cart.products[key].product;
}
}
}
}
}
function empty() {
Nestms.DataLayer.cart = {
products: {}
};
resetLastChange();
Nestms.DataLayer.cart.lastChange.action = 'emptied';
Lbt.save('cart', Nestms.DataLayer.cart);
Lbt.log('Lbt: cart empty');
}
function notifyUpdate() {
Lbt.async.notify('cartUpdate');
}
return {
init: Lbt.utilities.conditionalFunction(satellite, init),
setOrigin: Lbt.utilities.conditionalFunction(satellite, setOrigin),
add: Lbt.utilities.conditionalFunction(satellite, add),
remove: Lbt.utilities.conditionalFunction(satellite, remove),
empty: Lbt.utilities.conditionalFunction(satellite, empty),
notifyUpdate: Lbt.utilities.conditionalFunction(satellite, notifyUpdate)
};
}) ();
/* API ********************************************************************/
Lbt.persStorageReady = Lbt.initPersStorage();
Nestms.API.showAvailableCustomActions = function () {
for (var key in Lbt.customActions) {
if (Lbt.customActions.hasOwnProperty(key)) {
var item = Lbt.customActions[key];
Nestms.log({
'eventName': item.eventName,
'eventType': item.eventType,
'component': Nestms.DataLayer.components[item.elementId]
});
}
}
};
/*
* Get the current product displayed or added to the cart
*/
Nestms.API.getCurrentProduct = function () {
if (Lbt.currentProductId) {
return Nestms.DataLayer.products[Lbt.currentProductId];
}
};
/*
* Get parent components of the component as argument
*/
Nestms.API.getCompParent = function (elementId) {
return Lbt.components.getParent(elementId);
};
/*
* Get children components of the component as argument
*/
Nestms.API.getCompChildren = function (elementId) {
return Lbt.components.getChildren(elementId);
};
/*
* Get the position of the component relative to the entire page
*/
Nestms.API.getCompPosition = function (elementId) {
return Lbt.components.getPosition(elementId);
};
/*
* Get the data related to the last async event
*/
Nestms.API.getLastEventData = function () {
if (Lbt.async.lastEvent.eventName) {
return Lbt.async.lastEvent;
}
};
/*
* Highlight the component passed as param
*/
Nestms.API.highlightComp = function (elementId) {
Lbt.components.highlight(elementId);
};
/* ASYNC ********************************************************************/
Lbt.async = {
_lastRequestId: 0,
// keep only the last async event
lastEvent: {
eventName: null,
eventType: null,
sourceElementId: null,
targetElementId: null,
contentId: null,
success: false
},
reset: function () {
this.lastEvent.success = false;
this.lastEvent.targetElementId = null;
this.lastEvent.contentId = null;
},
/*
* Set the async object to prepare async request
*/
init: Lbt.utilities.conditionalFunction(satellite, function (elementSource) {
this.reset();
var $elementSource = $(elementSource),
$cmpSource = $elementSource.closest(cmpClass),
cmp = null;
// find the cmp source
if ($cmpSource.length > 0) {
cmp = Nestms.DataLayer.components[$cmpSource.attr('id')];
if (cmp && !Lbt.utilities.isEmpty(cmp) && cmp.hasOwnProperty('actions')) {
// init
this.lastEvent.eventName = cmp.actions.eventName;
this.lastEvent.eventType = cmp.actions.eventType;
this.lastEvent.sourceElementId = cmp.elementId;
this._lastRequestId += 1;
}
else {
Lbt.log('Lbt: async INIT - origin component not found from', $cmpSource);
}
} else {
Lbt.log('Lbt: async INIT - origin component not found from', $cmpSource);
}
Lbt.log('Lbt: async INIT - set async event', this.lastEvent);
return this._lastRequestId;
}),
complete: Lbt.utilities.conditionalFunction(satellite, function (requestId, contentId, elementTarget) {
if (requestId === this._lastRequestId) {
contentId = Helpers.sanitizeContentId(contentId);
this.lastEvent.success = true;
// update the contentId if it set (if it is a product)
this.lastEvent.contentId = contentId || null;
if (contentId) {
// if the async event is for a product, save it as currentProduct
Lbt.currentProductId = contentId;
}
var $elementTarget = $(elementTarget),
cmp = null;
// some async calls has not element target (like add to cart)
if ($elementTarget.length > 0) {
// try to go up to find the component
var $cmpTarget = $elementTarget.closest(cmpClass);
if ($cmpTarget.length === 0) {
// try to go down
$cmpTarget = $elementTarget.find(cmpClass);
}
if ($cmpTarget.length > 0) {
cmp = Nestms.DataLayer.components[$cmpTarget.attr('id')];
if (cmp && !Lbt.utilities.isEmpty(cmp)) {
// init
this.lastEvent.targetElementId = cmp.elementId;
}
}
}
// update the targetElementId if set
if (this.lastEvent.targetElementId) {
cmp = Nestms.DataLayer.components[this.lastEvent.targetElementId];
if (cmp && !Lbt.utilities.isEmpty(cmp)) {
Nestms.DataLayer.components[this.lastEvent.targetElementId].contentId = contentId;
Lbt.log('Lbt: async COMPLETE - set target contentId to ', contentId);
}
}
this.notify();
}
}),
notify: Lbt.utilities.conditionalFunction(satellite, function (eventName) {
if (eventName) {
satellite.track(eventName);
}
else if (this.lastEvent.eventName) {
satellite.track(this.lastEvent.eventName);
} else {
Lbt.log('Lbt: async NOTIFY - Event name not set', this.lastEvent);
}
}),
update: Lbt.utilities.conditionalFunction(satellite, function (update) {
for (var k in update) {
if (update.hasOwnProperty(k) && this.lastEvent.hasOwnProperty(k)) {
this.lastEvent[k] = update[k];
}
}
})
};
/************************************************************************/
/*
* Change the state of the product component to 'selected'
*/
Lbt.currentSelectedProductId = null; // if the data layer is filled dynamically, the selected product is has to be set after
var previousSelectedProductCmpIds = [];
Lbt.setSelectedProduct = Lbt.utilities.conditionalFunction(satellite, function (productCode) {
// remove the previously selected components
previousSelectedProductCmpIds.map(function (item) {
Nestms.DataLayer.components[item].state = 'active';
});
// set the new selected components
Lbt.components.getComponentsByType('product').map(function (cmp) {
if (cmp.hasOwnProperty('contentId') && cmp.contentId === productCode) {
Nestms.DataLayer.components[cmp.elementId].state = 'selected';
previousSelectedProductCmpIds.push(cmp.elementId);
Lbt.currentProductId = productCode;
}
});
});
/*
* Fill the DataLayer for each property and clean them up afterwards
*/
Lbt.fillDataLayer = Lbt.utilities.conditionalFunction(satellite, function () {
// --- Components ---
Lbt.components.add(Lbt.dl.components);
Lbt.dl.components = [];
// --- Products ---
Lbt.products.add(Lbt.dl.products);
Lbt.dl.products = [];
// --- Page ---
Lbt.setPage(Lbt.dl.page);
Lbt.dl.page = {};
// --- Error ---
Lbt.setError(Lbt.dl.error);
Lbt.dl.error = {};
// eventually, set the selected product after filling the data layer
if (Lbt.currentSelectedProductId) {
Lbt.setSelectedProduct(Lbt.currentSelectedProductId);
}
});
/*
* Find in the DOM, optionally from the element as arg, needed for async request
*/
Lbt.parseDOM = Lbt.utilities.conditionalFunction(satellite, function () {
try {
// by default, parse all the document
var DOMElement = (arguments.length === 0) ? 'body' : arguments[0];
$(DOMElement).find(cmpClass + ', ' + prodClass + ', ' + pageClass).map(function () {
var $this = $(this),
cmp = $this.data(cmpData), // component object
prod = $this.data(prodData), // product object
page = $this.data(pageData); // page object
// check if this element is a component
if (cmp) {
Lbt.components.add(cmp);
}
if (prod) {
Lbt.products.add(prod);
}
if (page) {
Lbt.setPage(page);
}
});
}
catch (e) {
Lbt.log(e);
}
});
Lbt.highlightCmps = function () {
for (var key in Nestms.DataLayer.components) {
if (Nestms.DataLayer.components.hasOwnProperty(key)) {
Lbt.components.highlight(key);
}
}
};
/* HELPERS ********************************************************************/
var Helpers = {
/*
* getPosition: given a jQuery element, returns a human readable position of the element
* relative to the container
* the function expects as param an object with the following structure:
* {
* parent: {w: containerWidth, h: containerHeight, top: containerTop, left: containerLeft},
* child: {top: child.top, left: child.left}
* }
*/
getPosition: function (obj) {
var childTop = obj.child.top - obj.parent.top,
childLeft = obj.child.left - obj.parent.left,
horizPercent = parseInt(100 * childLeft / obj.parent.w, 10),
verticalPercent = parseInt(100 * childTop / obj.parent.h, 10);
return {
horizontal: (horizPercent <= 33) ? 'left' : ((horizPercent <= 66) ? 'center' : 'right'),
vertical: (verticalPercent <= 33) ? 'top' : ((verticalPercent <= 66) ? 'center' : 'bottom')
};
},
/*
* Parse a productId/contentId and sanitize it
*/
sanitizeContentId: function (productId) {
if (productId) {
if (typeof productId === 'string') {
// remove extra single or double quotes
return productId.replace(/'*'*/g, '');
} // convert to string
else {
return productId.toString();
}
}
},
/*
* Parse a currency-price string and return only the price
*/
sanitizePrice: function (price) {
if (price) {
if (typeof price === 'string') {
return parseFloat(price);
} // convert to string
else {
return price.toString();
}
}
},
/*
* Since product types given by back-end are not standard,
* return a standard version of type
*/
sanitizeTypes: function (type) {
// normally, type should be a string
if (type) {
switch (type.toLowerCase()) {
case 'capsule':
case 'capsules':
case 'c':
return 'capsule';
case 'machine':
case 'machines':
case 'm':
return 'machine';
case 'accessory':
case 'accessories':
case 'accessoire':
case 'a':
return 'accessory';
case 'g':
case 'giftcard':
case 'giftcards':
return 'giftCard';
case 'sparepart':
case 's':
case 'spareparts':
return 'spareParts';
case 'food':
case 'foods':
case 'f':
return 'food';
default:
Lbt.log('Product type', type, 'not recognised');
}
}
else {
return type;
}
},
/*
* Given a list of technologies, return a 'standard' tracking obj
*/
getTechnos: function (techList) {
// lowercase everything
var l = techList.map(function (item) {
return item.toLowerCase();
});
return {
'OriginalLine': (l.indexOf('original') >= 0) ? 1 : 0,
'VertuoLine': (l.indexOf('vertuo') >= 0) ? 1 : 0,
'Pro': (l.indexOf('pro') >= 0) ? 1 : 0
};
}
};
// expose sanitizeContentId
Lbt.sanitizeContentId = Helpers.sanitizeContentId;
// load the cart on page load
Lbt.cart.init();
Lbt.custom = {};
jQuery.noConflict();
(function($) {
Nespresso = {
init: function() {
this.backToTop();
this.addToCarFromBox();
this.stickyHeader();
this.passStrength();
this.layerNavigation();
this.toggleCustomerType();
this.passwordHint();
this.phoneMask();
},
backToTop: function () {
$('.back-to-top').on('click', function() {
$('html, body').animate({scrollTop:0}, '500', 'swing');
return false;
});
},
toggleCustomerType: function() {
var customerTypeContainer = $('.customer-type');
customerTypeContainer.each(function() {
var radioControl = $(this).find('input[name*="is_company"]'),
isCompany = radioControl.eq(1).is(':checked'),
companyNameWrapper = $(this).find('.name-companyname'),
customerPrefix = $(this).parents('.form-list').find('.customer-name-prefix'),
prefixCaption = customerPrefix.find('.name-prefix label .caption'),
firstNameCaption = customerPrefix.find('.name-firstname label .caption'),
lastNameCaption = customerPrefix.find('.name-lastname label .caption'),
labelPrefix = '<span class="contact-caption">' + Translator.translate('Contact') + ' </span>';
if(isCompany) {
toggleCompanyName(true);
}
radioControl.on('change', function(){
if($(this).attr('id').indexOf('yes') >= 0) {
toggleCompanyName(true);
} else {
toggleCompanyName(false);
}
});
function toggleCompanyName(state) {
if(state) {
companyNameWrapper.show();
prefixCaption.text(prefixCaption.text().toLowerCase());
firstNameCaption.text(firstNameCaption.text().toLowerCase());
lastNameCaption.text(lastNameCaption.text().toLowerCase());
$(labelPrefix).insertBefore(prefixCaption);
$(labelPrefix).insertBefore(firstNameCaption);
$(labelPrefix).insertBefore(lastNameCaption);
} else {
companyNameWrapper.hide();
customerPrefix.find('.contact-caption').remove();
prefixCaption.text(toTitleCase(prefixCaption.text()));
firstNameCaption.text(toTitleCase(firstNameCaption.text()));
lastNameCaption.text(toTitleCase(lastNameCaption.text()));
}
}
});
function toTitleCase(value)
{
return value.replace(/\w+/g, function(text){return text.charAt(0).toUpperCase() + text.substr(1).toLowerCase();});
}
},
addToCarFromBox: function() {
$('.add-to-cart-placeholder').on('click', function() {
var qtyBox = $(this).siblings('.qty-box');
$('.qty-box').not(qtyBox).slideUp('fast');
qtyBox.slideToggle('fast');
});
$('.qty-box').each(function() {
var $this = $(this);
$this.find('td').on('click', function() {
$this.find('[id^=qty]').val($(this).html()).change();
$this.find('.btn-cart').trigger('click');
});
});
$('html').click(function() {
$('.qty-box').slideUp('fast');
});
$('.add-to-cart-buttons').click(function(event){
event.stopPropagation();
});
},
//password strength indicator
passStrength: function() {
var verdictWeak = Translator.translate('Weak'),
verdictMedium = Translator.translate('Medium'),
verdictStrong = Translator.translate('Strong'),
verdictVeryStrong = Translator.translate('Very Strong');
if($('body').hasClass('customer-account-create') || $('body').hasClass('customer-account-edit') || $('body').hasClass('customer-account-resetpassword') || $('body').hasClass('customer-account-changeforgotten') || $('body').hasClass('checkout-onepage-index') ){
var options = {
minChar: 8,
scores: [17, 26, 40, 50],
showVerdicts: true,
raisePower: 1.4
};
options.ui = {
showProgressBar: true,
showVerdicts: true,
showVerdictsInsideProgressBar: true,
verdicts: [verdictWeak, verdictMedium, verdictStrong, verdictStrong, verdictVeryStrong]
};
options.rules = {
ruleScores: {
wordNotEmail: -100,
wordLength: -100
},
activated: {
wordSequences: false,
wordNotEmail: true,
wordLength: true
}
};
if ( $('body').hasClass('checkout-onepage-index') ) {
$('#billing\\:customer_password').pwstrength(options);
}
else {
$('input[name="password"]').pwstrength(options);
}
}
},
stickyHeader: function() {
if(!$('.checkout-onepage-index').length) {
var headerContainer = $('#header-wrapper'),
headerPreNav = $('#header-pre-nav'),
mainContainer = $('.top-container').length ? $('.top-container') : $('.main-container');
var handleHeader = function() {
if(Modernizr.mq('screen and (min-width: ' + (bp.large + 1) + 'px)')) {
var scrolledTop = $(window).scrollTop(),
mainContainerTop = mainContainer.offset().top;
if(scrolledTop > mainContainerTop) {
if(!headerContainer.hasClass('fixed-header')){
headerContainer.addClass('fixed-header');
headerContainer.hide();
headerPreNav.hide();
mainContainer.css('margin-top',mainContainerTop + 'px');
headerContainer.slideDown('fast');
}
} else {
if(headerContainer.hasClass('fixed-header')){
headerContainer.removeClass('fixed-header');
headerPreNav.show();
mainContainer.attr('style','');
}
}
} else {
headerContainer.removeClass('fixed-header');
mainContainer.attr('style','');
}
};
$(window).scroll(function () {
handleHeader();
});
$( window ).resize(function() {
handleHeader();
});
}
},
layerNavigation: function() {
$('.toggle-filters').on('click', function(e){
$('.toggle-filters.active').not(this)
.removeClass('active')
.siblings('ol').slideToggle('fast');
var $this = $(this);
$this.siblings('ol').slideToggle('fast', function() {
$this.toggleClass('active');
});
e.stopPropagation();
});
$('body').on('click', function(e) {
$('.toggle-filters.active')
.removeClass('active')
.siblings('ol').slideToggle('fast');
});
},
passwordHint: function() {
$('.has-tooltip')
.on('focus', function(){
$(this).siblings('.input-tooltip').show();
})
.on('blur', function(){
$(this).siblings('.input-tooltip').hide();
});
},
phoneMask: function() {
var pattern, tooltip;
$.each($('input[id*="telephone_number"]'), function() {
if ($(this).val().length) {
var select = $(this).parents('.input-box').find('select[id*="telephone_number_country"]');
getPattern($(this));
setMask(select);
}
});
$('input[id*="telephone_number"]').on('focus', function() {
var select = $(this).parents('.input-box').find('select[id*="telephone_number_country"]');
getPattern($(this));
setMask(select);
if (! pattern.test($(this).val())) {
inputTooltip($(this), 'show');
} else {
inputTooltip($(this), 'hide');
}
});
$('input[id*="telephone_number"]').on('keyup', function() {
getPattern($(this));
if (! pattern.test($(this).val())) {
inputTooltip($(this), 'show');
} else {
inputTooltip($(this), 'hide');
}
});
$('select[id*="telephone_number_country"]').change(function() {
$(this).parents('.input-box').find('input[id*="telephone_number"]').val('');
setMask($(this));
});
function getPattern(elem) {
var select = elem.parents('.input-box').find('select[id*="telephone_number_country"]');
if (select.val() === defaultPhoneCountry) {
pattern = /^\+7\(\d{3}\)\d{3}-\d{4}$/;
tooltip = 'ru';
} else {
pattern = /^\d{10}$/;
tooltip = 'default';
}
}
function setMask(select) {
var input = select.parents('.input-box').find('input[id*="telephone_number"]');
if (select.val() === defaultPhoneCountry) {
input.mask('+7(999)999-9999');
input.attr('placeholder', '+7(___)___-____');
} else {
input.mask('9999999999');
input.attr('placeholder', '__________');
}
}
function inputTooltip(input, action) {
var ru_tooltip = input.siblings('.ru-input-tooltip');
var alt_tooltip = input.siblings('.alternative-tooltip');
switch (action) {
case 'show':
if (tooltip == 'ru') {
ru_tooltip.addClass('input-tooltip').show();
alt_tooltip.removeClass('input-tooltip').hide();
} else if (tooltip == 'default') {
alt_tooltip.addClass('input-tooltip').show();
ru_tooltip.removeClass('input-tooltip').hide();
}
break;
case 'hide':
ru_tooltip.removeClass('input-tooltip').hide();
alt_tooltip.removeClass('input-tooltip').hide();
break;
}
}
}
};
$(function() {
Nespresso.init();
});
})(jQuery);
/**
* Here will be added all custom validations
*/
var Translator = new Translate();
Validation.add('validate-cemail',Translator.translate('Please make sure your email address match'),function(v){
var conf = $('email_address_confirmation') ? $('email_address_confirmation') : $$('.validate-cemail')[0];
var email = false;
if ($('email_address')) {
email = $('email_address');
}
var emailElements = $$('.validate-email');
for (var i = 0; i < emailElements.size(); i++) {
var emailElement = emailElements[i];
if (emailElement.up('form').id === conf.up('form').id) {
email = emailElement;
}
}
// solves IE7 match for confirmation email
return (email.value === v);
});
Validation.add('validate-char-email',Translator.translate('Please enter another email address with allowed characters. Characters allowed are . _ - '),function(v) {
//return Validation.get('IsEmpty').test(v) || /^\w+([.-]?\w+)?[.-]*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(v);
return Validation.get('IsEmpty').test(v) || /^[^<>?()[\]{}«»\\,;:\+=%#^\s"'\*\/“~`‘\|$&!]+@*(([[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z0-9_-]+\.+)*[a-zA-Z0-9_-]*))$/gm.test(v);
});
Validation.add('validate-password-max-length',Translator.translate('Please enter maximum 15 characters. Leading or trailing spaces will be ignored.'), function(v){
var pass=v.strip(); /*strip leading and trailing spaces*/
return !(!pass.length<6 && pass.length > 15);
});
Validation.add('validate-nesoa-telephone',Translator.translate('Please insert a number (10 digits) according to the following format 9851234567.'), function(v){
return Validation.get('IsEmpty').test(v) || /^\d{3}\d{7}$/.test(v);
});
Validation.add('validate-nesoa-telephone-ru',Translator.translate('Phone number has an incorrect format, please fill the field following next example: +7(916)123-4567'), function(v){
return Validation.get('IsEmpty').test(v) || /^\+7\(\d{3}\)\d{3}[-.]?\d{4}\b$/.test(v);
});
Validation.add('validate-nesoa-zip',Translator.translate('Please enter 6 digits for postal code.'), function(v){
return Validation.get('IsEmpty').test(v) || /^\d{6}$/.test(v);
});
Validation.add('validate-cyrillic',Translator.translate('Please use only Russian letters'), function(v){
return Validation.get('IsEmpty').test(v) || /^[а-яА-ЯЁё0-9 -.,/]+$/.test(v);
});
Validation.add('validate-cyrillic-only',Translator.translate('Please use only Russian letters'), function(v){
return Validation.get('IsEmpty').test(v) || /^[а-яА-ЯЁё ]+$/.test(v);
});
Validation.add('swatch-color',Translator.translate('Please choose a color for the machine.'), function(v){
return !Validation.get('IsEmpty').test(v);
});
Validation.add('required-machine-reg-code', 'The code is missing. Please enter the code if you have it or choose "No".', function (v) {
var code = v.strip();
return !($('machine_code_reg').hasClassName('required-machine-reg-code') && code.length < 1);
});
/**
* //NOSONAR
* This plugin is doing the ajax call for submitting the add to cart action and also is handling the minicart
* markup and the success/error messages.
*
* The plugin can be called as in the following example:
* ....
* <div class="product-list">
* ...
* <form action="add-to-cart" class="add-to-cart-form" type="post">
* <button type=submit>Add to Cart</button>
* </form>
*
* </div>
* .....
*
* jQuery('.product-list').AjaxAddToCart({formSelector: '.add-to-cart-form'})
*
* @category skin
* @package nespresso_default
* @author rradu@optaros.com
*
*/
(function($) {
$.fn.AjaxAddToCart = function(options) {
options = $.extend({
varienForm: true, // set it to true in order to instantiate a varienForm and validate it before submitting
formSelector: null, // selector for the form that is gonna be submitted
cartSelector: '#header-cart', // selector for the minicart container
cartHeaderSelector: '.skip-cart', // selector for the minicart header
openCart: true, // whether to open or not the minicart once the ajax call is finished
closeCart: true, // whether to close or not the minicart after a configurable period of time
cartTimeout: 3000, // the time the minicart stays opened
qtySelector: 'div.header-minicart span.count', // selector for the minicart qty element in header
submitButtonSelector: '.btn-cart', // selector for the button that submits the form
submitButtonClass: 'loader', // class to add on the button during the ajax call
showMessages: true, // whether to show or not success/error messages after adding product to cart
clearMessages: true, // whether to remove or not the success/error messages after a configurable period of time
messagesTimeout: 3000, // the time the errors are shown
messagesInCart: true, // whether to show the messages in cart or not, if its set to false the messages will be displayed into a configurable container
messagesContainerSelector: '.col-main', // if the previous option is false, the container for error messages should be specified
cartSuccessMessagesSelector: '#minicart-success-message', // selector for success message container in cart
cartErrorMessagesSelector: '#minicart-error-message', //selector for error message container in cart
trackDTM: false,
trackDDM: false, // Digital Data Manager module
// in both callbacks the form is accessible using arguments[0]
startAjaxCallback: function(){}, // callback that is executed at the same time with the ajax call
finishAjaxCallback: function(){} // callback that is executed once the ajax call is finished ( success or not)
},options);
var messagesTimeout;
var cartTimeout;
var $this = {
updateMiniCart : function(data) {
if(data) {
$(options.cartSelector).html(data.sidebar);
if (data.qty && data.qty > 0) {
$(options.cartHeaderSelector).removeClass('no-count');
}
$(options.cartHeaderSelector + ' > .label').html(data.cart_header);
}
},
showMiniCart : function() {
clearTimeout(cartTimeout);
function setActive() {
$(options.cartSelector).siblings('a').addClass('skip-active');
if (Modernizr.mq('screen and (min-width: ' + (bp.large + 1) + 'px)')) {
$(options.cartSelector).slideDown(150, 'swing', function () {
$(this).addClass('skip-active');
$(this).css('display', ''); // Remove styling leftovers from slideDown
});
} else {
$(options.cartSelector).addClass('skip-active');
}
}
if(Modernizr.mq('screen and (max-width: ' + bp.large + 'px)')) {
$('body').animate({scrollTop: 0}, '500', 'swing', setActive);
} else {
setActive();
}
},
closeMiniCart: function() {
cartTimeout = setTimeout(function() {
$(options.cartSelector).siblings('a').removeClass('skip-active');
if (Modernizr.mq('screen and (min-width: ' + (bp.large + 1) + 'px)')) {
$(options.cartSelector).slideUp(150, 'swing', function () {
$(this).removeClass('skip-active');
$(this).css('display', ''); // Remove styling leftovers from slideUp
});
} else {
$(options.cartSelector).removeClass('skip-active');
}
}, options.cartTimeout);
},
showMessage: function(message, messageType) {
clearTimeout(messagesTimeout);
options.messagesInCart ? $this.showMessageInCart(message, messageType) : $this.showMessageOutsideCart(message, messageType);
},
showMessageOutsideCart: function(message, messageType) {
var messageContainer = $(options.messagesContainerSelector + ' .messages');
var content = '<ul class="messages"><li class="' + messageType + '-msg"><ul><li><span>' + message + '</span></li></ul></li></ul>';
if(messageContainer.length) {
messageContainer.replaceWith(content);
} else {
$(options.messagesContainerSelector).prepend(content);
}
},
showMessageInCart: function(message, messageType) {
if(messageType === 'error' || messageType === 'notice') {
$(options.cartSuccessMessagesSelector).hide().html('');
$(options.cartErrorMessagesSelector).html(message).fadeIn('slow');
} else if(messageType === 'success') {
$(options.cartErrorMessagesSelector).hide().html('');
$(options.cartSuccessMessagesSelector).html(message).fadeIn('slow');
}
},
clearMessage: function() {
messagesTimeout = setTimeout(function(){
if(options.messagesInCart) {
$(options.cartSuccessMessagesSelector).fadeOut('slow').html('');
$(options.cartErrorMessagesSelector).fadeOut('slow').html('');
} else {
$(options.messagesContainerSelector + ' .messages').html('');
}
},options.messagesTimeout);
},
bindForm : function(target) {
target.delegate(options.formSelector, 'submit', function(event) {
$this.ajaxCall($(this));
event.preventDefault();
});
},
bindVarienForm: function() {
$(options.formSelector).each(function() {
var $form = $(this),
productAddToCartForm = new VarienForm($form.attr('id'));
$(this).on('submit',function(e) {
$form.find('.qty-box').slideUp('fast');
if(productAddToCartForm.validator.validate()) {
$this.ajaxCall($(productAddToCartForm.form));
e.preventDefault();
}
});
});
},
submitForm : function(form) {
$this.ajaxCall($(form));
},
handleLoader: function(form, state) {
var button = $(options.submitButtonSelector,form);
var qtyBox = button.parents('.qty-box');
var buttonPlaceholder = qtyBox.siblings('.add-to-cart-placeholder');
var qtyInput = qtyBox.find('[id^=qty]');
if(button) {
if(state) {
buttonPlaceholder.addClass(options.submitButtonClass);
} else {
buttonPlaceholder.removeClass(options.submitButtonClass);
qtyInput.val('').change();
}
buttonPlaceholder.prop('disabled', state);
}
},
updateDTM: function(data) {
if(data.messageType === 'success') {
_Lbt.cart.add(data.productId, data.productQty);
_Lbt.cart.notifyUpdate();
}
},
updateDDM: function(data, form) {
if(data.messageType === 'success' && window.digitalData) {
var productId = $(form).find('input[name="product"]').val() || $(form).parents('li.item').data('product-id');
var qty = $(form).find('input[name="qty"]').val();
window.digitalData.events.push({
'category': 'Ecommerce',
'name': 'Added Product',
'product': '' + productId,
'quantity': +qty
});
}
},
ajaxCall : function(form) {
options.startAjaxCallback(form);
$this.handleLoader(form, true);
$.ajax({
url: form.attr('action'),
dataType: 'json',
type: 'post',
data: form.serialize()})
.done(function(data) {
if(options.trackDDM) {
$this.updateDDM(data, form);
}
$this.updateMiniCart(data);
if(options.openCart) {
$this.showMiniCart();
if(options.closeCart) {
$this.closeMiniCart();
}
}
if(options.trackDTM) {
$this.updateDTM(data);
}
if(options.showMessages && data.message) {
$this.showMessage(data.message, data.messageType);
}
if(options.clearMessages && data.message) {
$this.clearMessage();
}
})
.always(function() {
$this.handleLoader(form, false);
options.finishAjaxCallback(form);
});
}
};
if(options.varienForm) {
$this.bindVarienForm();
} else {
$this.bindForm($(this));
}
return $this;
};
})(jQuery);