/* 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: ']*>([\\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,'>'); } 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 '#'; } 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+/) : []; } function isIterable(obj) { // checks for null and undefined if (obj == null) { return false; } return typeof obj[Symbol.iterator] === 'function'; } if (isIterable($A)) { 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 '#'; } 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(''); 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 = ""; 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 = "test"; 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 = ""; 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(' -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: ['', '
', 1], TBODY: ['', '
', 2], TR: ['', '
', 3], TD: ['
', '
', 4], 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 "#"; } }); 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 "#".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 = ""; 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 = ""; 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 = "

"; 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 = "
"; 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 "#"; } }); 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); } }); })(); /*! jQuery v1.12.0 | (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="1.12.0",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!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));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||function(a){return"array"===n.type(a)},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},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!k.call(a,"constructor")&&!k.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(!l.ownFirst)for(b in a)return k.call(a,b);for(b in a);return void 0===b||k.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?i[j.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},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){var d;if(b){if(h)return h.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[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&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=e.call(arguments,2),d=function(){return a.apply(b||this,c.concat(e.call(arguments)))},d.guid=a.guid=a.guid||n.guid++,d):void 0},now:function(){return+new Date},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.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;++db;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.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="",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 n.inArray(a,b)>-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=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},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.charAt(0)&&">"===a.charAt(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}if(f=d.getElementById(e[2]),f&&f.parentNode){if(f.id!==e[2])return A.find(a);this.length=1,this[0]=f}return this.context=d,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof 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,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))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?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):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){do a=a[b];while(a&&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 n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document: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]||(e=n.uniqueSort(e)),D.test(a)&&(e=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-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=!0,c||j.disable(),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.addEventListener?(d.removeEventListener("DOMContentLoaded",K),a.removeEventListener("load",K)):(d.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(d.addEventListener||"load"===a.event.type||"complete"===d.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===d.readyState)a.setTimeout(n.ready);else if(d.addEventListener)d.addEventListener("DOMContentLoaded",K),a.addEventListener("load",K);else{d.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&d.documentElement}catch(e){}c&&c.doScroll&&!function f(){if(!n.isReady){try{c.doScroll("left")}catch(b){return a.setTimeout(f,50)}J(),n.ready()}}()}return I.promise(b)},n.ready.promise();var L;for(L in n(l))break;l.ownFirst="0"===L,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c,e;c=d.getElementsByTagName("body")[0],c&&c.style&&(b=d.createElement("div"),e=d.createElement("div"),e.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(e).appendChild(b),"undefined"!=typeof b.style.zoom&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",l.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(e))}),function(){var a=d.createElement("div");l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}a=null}();var M=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b},N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1; return!0}function R(a,b,d,e){if(M(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f}}function S(a,b,c){if(M(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=void 0)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),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=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(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._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthh;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},Z=/^(?:checkbox|radio)$/i,$=/<([\w:-]+)/,_=/^$|\/(?:java|ecma)script/i,aa=/^\s+/,ba="abbr|article|aside|audio|bdi|canvas|data|datalist|details|dialog|figcaption|figure|footer|header|hgroup|main|mark|meter|nav|output|picture|progress|section|summary|template|time|video";function ca(a){var b=ba.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}!function(){var a=d.createElement("div"),b=d.createDocumentFragment(),c=d.createElement("input");a.innerHTML="
a",l.leadingWhitespace=3===a.firstChild.nodeType,l.tbody=!a.getElementsByTagName("tbody").length,l.htmlSerialize=!!a.getElementsByTagName("link").length,l.html5Clone="<:nav>"!==d.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,b.appendChild(c),l.appendChecked=c.checked,a.innerHTML="",l.noCloneChecked=!!a.cloneNode(!0).lastChild.defaultValue,b.appendChild(a),c=d.createElement("input"),c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),a.appendChild(c),l.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!!a.addEventListener,a[n.expando]=1,l.attributes=!a.getAttribute(n.expando)}();var da={option:[1,""],legend:[1,"
","
"],area:[1,"",""],param:[1,"",""],thead:[1,"","
"],tr:[2,"","
"],col:[2,"","
"],td:[3,"","
"],_default:l.htmlSerialize?[0,"",""]:[1,"X
","
"]};da.optgroup=da.option,da.tbody=da.tfoot=da.colgroup=da.caption=da.thead,da.th=da.td;function ea(a,b){var c,d,e=0,f="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,ea(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function fa(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}var ga=/<|&#?\w+;/,ha=/r;r++)if(g=a[r],g||0===g)if("object"===n.type(g))n.merge(q,g.nodeType?[g]:g);else if(ga.test(g)){i=i||p.appendChild(b.createElement("div")),j=($.exec(g)||["",""])[1].toLowerCase(),m=da[j]||da._default,i.innerHTML=m[1]+n.htmlPrefilter(g)+m[2],f=m[0];while(f--)i=i.lastChild;if(!l.leadingWhitespace&&aa.test(g)&&q.push(b.createTextNode(aa.exec(g)[0])),!l.tbody){g="table"!==j||ha.test(g)?""!==m[1]||ha.test(g)?0:i:i.firstChild,f=g&&g.childNodes.length;while(f--)n.nodeName(k=g.childNodes[f],"tbody")&&!k.childNodes.length&&g.removeChild(k)}n.merge(q,i.childNodes),i.textContent="";while(i.firstChild)i.removeChild(i.firstChild);i=p.lastChild}else q.push(b.createTextNode(g));i&&p.removeChild(i),l.appendChecked||n.grep(ea(q,"input"),ia),r=0;while(g=q[r++])if(d&&n.inArray(g,d)>-1)e&&e.push(g);else if(h=n.contains(g.ownerDocument,g),i=ea(p.appendChild(g),"script"),h&&fa(i),c){f=0;while(g=i[f++])_.test(g.type||"")&&c.push(g)}return i=null,p}!function(){var b,c,e=d.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b]=c in a)||(e.setAttribute(c,"t"),l[b]=e.attributes[c].expando===!1);e=null}();var ka=/^(?:input|select|textarea)$/i,la=/^key/,ma=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,na=/^(?:focusinfocus|focusoutblur)$/,oa=/^([^.]*)(?:\.(.+)|)/;function pa(){return!0}function qa(){return!1}function ra(){try{return d.activeElement}catch(a){}}function sa(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)sa(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=qa;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._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return"undefined"==typeof n||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(G)||[""],h=b.length;while(h--)f=oa.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=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(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(G)||[""],j=b.length;while(j--)if(h=oa.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=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},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(i=m=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!na.test(q+n.event.triggered)&&(q.indexOf(".")>-1&&(r=q.split("."),q=r.shift(),r.sort()),h=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]),l=n.event.special[q]||{},f||!l.trigger||l.trigger.apply(e,c)!==!1)){if(!f&&!l.noBubble&&!n.isWindow(e)){for(j=l.delegateType||q,na.test(j+q)||(i=i.parentNode);i;i=i.parentNode)p.push(i),m=i;m===(e.ownerDocument||d)&&p.push(m.defaultView||m.parentWindow||a)}o=0;while((i=p[o++])&&!b.isPropagationStopped())b.type=o>1?j:l.bindType||q,g=(n._data(i,"events")||{})[b.type]&&n._data(i,"handle"),g&&g.apply(i,c),g=h&&i[h],g&&g.apply&&M(i)&&(b.result=g.apply(i,c),b.result===!1&&b.preventDefault());if(b.type=q,!f&&!b.isDefaultPrevented()&&(!l._default||l._default.apply(p.pop(),c)===!1)&&M(e)&&h&&e[q]&&!n.isWindow(e)){m=e[h],m&&(e[h]=null),n.event.triggered=q;try{e[q]()}catch(s){}n.event.triggered=void 0,m&&(e[h]=m)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,d,f,g,h=[],i=e.call(arguments),j=(n._data(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]","i"),va=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,wa=/\s*$/g,Aa=ca(d),Ba=Aa.appendChild(d.createElement("div"));function Ca(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 Da(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function Ea(a){var b=ya.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Fa(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Ga(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(Da(b).text=a.text,Ea(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&Z.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}function Ha(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&&xa.test(q))return a.each(function(e){var f=a.eq(e);r&&(b[0]=q.call(this,e,f.html())),Ha(f,b,c,d)});if(o&&(k=ja(b,a[0].ownerDocument,!1,a,d),e=k.firstChild,1===k.childNodes.length&&(k=e),e||d)){for(i=n.map(ea(k,"script"),Da),h=i.length;o>m;m++)g=k,m!==p&&(g=n.clone(g,!0,!0),h&&n.merge(i,ea(g,"script"))),c.call(a[m],g,m);if(h)for(j=i[i.length-1].ownerDocument,n.map(i,Ea),m=0;h>m;m++)g=i[m],_.test(g.type||"")&&!n._data(g,"globalEval")&&n.contains(j,g)&&(g.src?n._evalUrl&&n._evalUrl(g.src):n.globalEval((g.text||g.textContent||g.innerHTML||"").replace(za,"")));k=e=null}return a}function Ia(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(ea(d)),d.parentNode&&(c&&n.contains(d.ownerDocument,d)&&fa(ea(d,"script")),d.parentNode.removeChild(d));return a}n.extend({htmlPrefilter:function(a){return a.replace(va,"<$1>")},clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!ua.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(Ba.innerHTML=a.outerHTML,Ba.removeChild(f=Ba.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=ea(f),h=ea(a),g=0;null!=(e=h[g]);++g)d[g]&&Ga(e,d[g]);if(b)if(c)for(h=h||ea(a),d=d||ea(f),g=0;null!=(e=h[g]);g++)Fa(e,d[g]);else Fa(a,f);return d=ea(f,"script"),d.length>0&&fa(d,!i&&ea(a,"script")),d=h=e=null,f},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.attributes,m=n.event.special;null!=(d=a[h]);h++)if((b||M(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k||"undefined"==typeof d.removeAttribute?d[i]=void 0:d.removeAttribute(i),c.push(f))}}}),n.fn.extend({domManip:Ha,detach:function(a){return Ia(this,a,!0)},remove:function(a){return Ia(this,a)},text:function(a){return Y(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||d).createTextNode(a))},null,a,arguments.length)},append:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.appendChild(a)}})},prepend:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return Ha(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return Ha(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(ea(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}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 Y(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(ta,""):void 0;if("string"==typeof a&&!wa.test(a)&&(l.htmlSerialize||!ua.test(a))&&(l.leadingWhitespace||!aa.test(a))&&!da[($.exec(a)||["",""])[1].toLowerCase()]){a=n.htmlPrefilter(a);try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(ea(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=[];return Ha(this,arguments,function(b){var c=this.parentNode;n.inArray(this,a)<0&&(n.cleanData(ea(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=0,e=[],f=n(a),h=f.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(f[d])[b](c),g.apply(e,c.get());return this.pushStack(e)}});var Ja,Ka={HTML:"block",BODY:"block"};function La(a,b){var c=n(b.createElement(a)).appendTo(b.body),d=n.css(c[0],"display");return c.detach(),d}function Ma(a){var b=d,c=Ka[a];return c||(c=La(a,b),"none"!==c&&c||(Ja=(Ja||n("'); 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("
  • " + elem.substr(0, entry.length) + "" + elem.substr(entry.length) + "
  • "); 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("
  • " + elem.substr(0, foundPos) + "" + elem.substr(foundPos, entry.length) + "" + elem.substr( foundPos + entry.length) + "
  • "); 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 "
      " + ret.join('') + "
    "; } }, options || { }); } }); // AJAX in-place editor and collection editor // Full rewrite by Christophe Porteneuve (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) && (sliderValuethis.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 * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE_AFL.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * 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-2019 Magento, Inc. (http://www.magento.com) * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) */ function popWin(url,win,para) { var win = window.open(url,win,para); win.focus(); } function setLocation(url){ window.location.href = encodeURI(url); } function setPLocation(url, setFocus){ if( setFocus ) { window.opener.focus(); } window.opener.location.href = encodeURI(url); } /** * @deprecated */ 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(); var date = new Date; this.curyear = date.getFullYear(); }, 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(year < 1900) error = this.errorTextModifier(this.validateDataErrorText); 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(); return (year>=1900 && year<=this.curyear); }, validateDataErrorType: 'year', validateDataErrorText: 'Please enter a valid year (1900-%d).', errorTextModifier: function(text) { text = Translator.translate(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 * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE_AFL.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * 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-2019 Magento, Inc. (http://www.magento.com) * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) */ 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 = transport.responseJSON || transport.responseText.evalJSON(true) || {}; 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 = ''; Element.insert(child, {before: html}); Element.remove(child); } } else{ var child = $(this.cache[this.currLoader]['child']); if (child){ var html = ''; 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 * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE_AFL.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * 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-2019 Magento, Inc. (http://www.magento.com) * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) */ /** * @classDescription simple Navigation with replacing old handlers * @param {String} id id of ul element with navigation lists * @param {Object} settings object with settings */ var mainNav = function() { var main = { obj_nav : $(arguments[0]) || $("nav"), settings : { show_delay : 0, hide_delay : 0, _ie6 : /MSIE 6.+Win/.test(navigator.userAgent), _ie7 : /MSIE 7.+Win/.test(navigator.userAgent) }, init : function(obj, level) { obj.lists = obj.childElements(); obj.lists.each(function(el,ind){ main.handlNavElement(el); if((main.settings._ie6 || main.settings._ie7) && level){ main.ieFixZIndex(el, ind, obj.lists.size()); } }); if(main.settings._ie6 && !level){ document.execCommand("BackgroundImageCache", false, true); } }, handlNavElement : function(list) { if(list !== undefined){ list.onmouseover = function(){ main.fireNavEvent(this,true); }; list.onmouseout = function(){ main.fireNavEvent(this,false); }; if(list.down("ul")){ main.init(list.down("ul"), true); } } }, ieFixZIndex : function(el, i, l) { if(el.tagName.toString().toLowerCase().indexOf("iframe") == -1){ el.style.zIndex = l - i; } else { el.onmouseover = "null"; el.onmouseout = "null"; } }, fireNavEvent : function(elm,ev) { if(ev){ elm.addClassName("over"); elm.down("a").addClassName("over"); if (elm.childElements()[1]) { main.show(elm.childElements()[1]); } } else { elm.removeClassName("over"); elm.down("a").removeClassName("over"); if (elm.childElements()[1]) { main.hide(elm.childElements()[1]); } } }, show : function (sub_elm) { if (sub_elm.hide_time_id) { clearTimeout(sub_elm.hide_time_id); } sub_elm.show_time_id = setTimeout(function() { if (!sub_elm.hasClassName("shown-sub")) { sub_elm.addClassName("shown-sub"); } }, main.settings.show_delay); }, hide : function (sub_elm) { if (sub_elm.show_time_id) { clearTimeout(sub_elm.show_time_id); } sub_elm.hide_time_id = setTimeout(function(){ if (sub_elm.hasClassName("shown-sub")) { sub_elm.removeClassName("shown-sub"); } }, main.settings.hide_delay); } }; if (arguments[1]) { main.settings = Object.extend(main.settings, arguments[1]); } if (main.obj_nav) { main.init(main.obj_nav, false); } }; document.observe("dom:loaded", function() { //run navigation without delays and with default id="#nav" //mainNav(); //run navigation with delays mainNav("nav", {"show_delay":"100","hide_delay":"100"}); }); /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE_AFL.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * 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-2019 Magento, Inc. (http://www.magento.com) * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) */ 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 * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE_AFL.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * 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-2019 Magento, Inc. (http://www.magento.com) * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) */ // 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)); }; /** * Lightbox * * This libary is used to create a lightbox in a web application. This library * requires the Prototype 1.6 library and Script.aculo.us core, effects, and dragdrop * libraries. To use, add a div containing the content to be displayed anywhere on * the page. To create the lightbox, add the following code: * * var test; * * Event.observe(window, 'load', function () { * test = new Lightbox('idOfMyDiv'); * }); * * Event.observe('lightboxLink', 'click', function () { * test.open(); * }); * * Event.observe('closeLink', 'click', function () { * test.close(); * }); * */ var Lightbox = Class.create({ open : function () { this._centerWindow(this.container); this._fade('open', this.container); }, close : function () { this._fade('close', this.container); }, _fade : function fadeBg(userAction,whichDiv){ if(userAction=='close'){ new Effect.Opacity('bg_fade', {duration:.2, from:0.6, to:0, afterFinish:this._makeInvisible, afterUpdate:this._hideLayer(whichDiv)}); }else{ new Effect.Opacity('bg_fade', {duration:.2, from:0, to:0.6, beforeUpdate:this._makeVisible, afterFinish:this._showLayer(whichDiv)}); } }, _makeVisible : function makeVisible(){ $("bg_fade").style.visibility="visible"; }, _makeInvisible : function makeInvisible(){ $("bg_fade").style.visibility="hidden"; }, _showLayer : function showLayer(userAction){ $(userAction).style.display="block"; }, _hideLayer : function hideLayer(userAction){ $(userAction).style.display="none"; }, _centerWindow : function centerWindow(element) { var windowHeight = parseFloat($(element).getHeight())/2; var windowWidth = parseFloat($(element).getWidth())/2; if(typeof window.innerHeight != 'undefined') { $(element).style.top = Math.round(document.body.offsetTop + ((window.innerHeight - $(element).getHeight()))/2)+'px'; $(element).style.left = Math.round(document.body.offsetLeft + ((window.innerWidth - $(element).getWidth()))/2)+'px'; } else { $(element).style.top = Math.round(document.body.offsetTop + ((document.documentElement.offsetHeight - $(element).getHeight()))/2)+'px'; $(element).style.left = Math.round(document.body.offsetLeft + ((document.documentElement.offsetWidth - $(element).getWidth()))/2)+'px'; } }, initialize : function(containerDiv) { this.container = containerDiv; if($('bg_fade') == null) { var screen = new Element('div', {'id': 'bg_fade'}); document.body.appendChild(screen); } this._hideLayer(this.container); } }); if("undefined"!=typeof jQuery){var mega=jQuery.noConflict();const eff_hover=1,eff_animation=2,eff_toggle=3,Slide=0,Blind=1;var MEGAMENU=function(e,i,t,s,a){this.isMobile=navigator.userAgent.match(/iPhone|iPad|iPod/i)||navigator.userAgent.match(/Android/i)||navigator.userAgent.match(/BlackBerry/i)||navigator.userAgent.match(/Opera Mini/i)||navigator.userAgent.match(/IEMobile/i),this.menu=e,this.effect=parseInt(i[0]),this.mobile_effect=parseInt(i[1]),this.change=t,this.arr=s,this.responsive=parseInt(a),this.init()};MEGAMENU.prototype={init:function(){this.option(),this.setWidth(this.width_default),this.setPosition(this.width_default),this.categoriesLevel(),this.categoriesDynamic(),this.categoriesMobile(),this.applyEvent(),this.mobile()},option:function(){this.ms_level0=this.menu.children(".ms-level0"),this.label=this.ms_level0.children(".ms-label"),this.submenu=this.ms_level0.children(".ms-submenu"),this.sub_left=this.ms_level0.children(".sub_left"),this.sub_right=this.ms_level0.children(".sub_right"),this.categoryParent=this.ms_level0.find(".ms-submenu .ms-category-level .parent"),this.dynamicParent=this.ms_level0.find(".ms-submenu .ms-category-dynamic .col-level .parent"),this.anchor=this.menu.find(".anchor_mbmenu .anchor_mbmenu_text"),this.mblabel=this.ms_level0.children(".mb-label"),this.mbreturn=this.ms_level0.find(".mb-return"),this.mblevel=this.ms_level0.find(".mb-submenu .mb-level-click"),this.menu_id=this.menu.attr("id"),this.width_default=this.menu.outerWidth()},applyEvent:function(){if(null!=this.isMobile)this.toggle();else switch(this.effect){case eff_animation:this.slide();break;case eff_toggle:this.toggle();break;default:this.fade()}},updateScreen:function(){this.width_default=this.menu.outerWidth(),this.setWidth(this.width_default),this.setPosition(this.width_default)},mobile:function(){var e=this.menu;switch(this.anchor.bind("click",function(){return $_this=mega(this),$_this.hasClass("flag")?(e.removeClass("active"),$_this.removeClass("flag")):(e.addClass("active"),$_this.addClass("flag")),!1}),this.mobile_effect){case Slide:this.mobileSlide();break;default:this.mobileBlind()}},fade:function(){this.ms_level0.bind("mouseenter",function(){var e=mega(this);e.addClass("active"),e.children(".ms-submenu").stop().fadeIn(150)}),this.ms_level0.bind("mouseleave",function(){var e=mega(this);e.removeClass("active"),e.children(".ms-submenu").hide()})},slide:function(){this.ms_level0.bind("mouseenter",function(){var e=mega(this);e.addClass("active"),e.children(".ms-submenu").stop().slideDown(150)}),this.ms_level0.bind("mouseleave",function(){var e=mega(this);e.removeClass("active"),e.children(".ms-submenu").hide()})},toggle:function(){var e=this.menu_id,i=this.change,t=this.responsive;this.label.bind("click",function(){var s=mega(this);return s.hasClass("anchor_text")?void 0:(s.hasClass("flag")?(s.removeClass("flag"),s.parent().removeClass("active"),s.parent().children(".ms-submenu").hide()):(mega("#"+e+" .ms-level0").removeClass("active"),mega("#"+e+" .ms-label").removeClass("flag"),mega("#"+e+" .ms-submenu").hide(),s.addClass("flag"),s.parent().addClass("active"),s.parent().children(".ms-submenu").slideDown(150)),mega(window).width()>i||!t?!1:!0)})},mobileSlide:function(){var e=this.menu_id;mclick=this.mblabel,mclick.parent().children(".mb-submenu").removeClass("blind"),mclick.parent().children(".mb-submenu").addClass("slide"),this.mblabel.bind("click",function(){var i=mega(this);mega("#"+e+" .ms-level0").removeClass("mbactive"),i.parent().addClass("mbactive"),i.parent().children(".mb-submenu").animate({left:0},300)}),this.mbreturn.bind("click",function(){mega(this);mclick.parent().children(".mb-submenu").animate({left:"100%"},300,function(){mclick.parent().removeClass("mbactive")})})},mobileBlind:function(){var e=this.menu_id;this.mblabel.bind("click",function(){var i=mega(this);i.hasClass("glyphicon-minus")?(i.removeClass("glyphicon-minus"),i.parent().removeClass("mbactive"),i.parent().children(".mb-submenu").slideUp(200)):(mega("#"+e+" .ms-level0").removeClass("mbactive"),mega("#"+e+" .mb-label").removeClass("glyphicon-minus"),mega("#"+e+" .mb-submenu").slideUp(200),i.addClass("glyphicon-minus"),i.parent().addClass("mbactive"),i.parent().children(".mb-submenu").slideDown(200))})},setWidth:function(e){for(var i=0;ie&&(i=e-$_this.outerWidth()),0>i&&(i=0),$_this.css({left:i+"px"})}else $_this.css({left:0})}),this.sub_right.each(function(){if($_this=mega(this),$_this.hasClass("position_auto")){var i=e-$_this.parent().position().left-$_this.parent().outerWidth();$_this.outerWidth()+i>e&&(i=e-$_this.outerWidth()),0>i&&(i=0),$_this.css({right:i+"px"})}else $_this.css({right:0})})},categoriesLevel:function(){this.categoryParent.length&&(this.categoryParent.bind("mouseenter",function(){var e=mega(this);e.addClass("active")}),this.categoryParent.bind("mouseleave",function(){var e=mega(this);e.removeClass("active")}))},categoriesDynamic:function(){this.dynamicParent.length&&this.dynamicParent.bind("mouseenter",function(){var e=mega(this),i=e.find("i.information"),t=e.parentsUntil(".ms-submenu"),s=i.attr("title");t.find(".col-level .parent").removeClass("active"),e.addClass("active"),t.find(".ms-category-dynamic .col-dynamic").removeClass("active"),t.find("#"+s).addClass("active")})},categoriesMobile:function(){this.mblevel.length&&this.mblevel.bind("click",function(){var e=mega(this);e.hasClass("glyphicon-minus")?(e.removeClass("glyphicon-minus"),e.parent().parent().removeClass("active")):(e.addClass("glyphicon-minus"),e.parent().parent().addClass("active"))})}};var LEFTMENU=function(e,i,t,s,a,n){this.menu=e,this.main_div=i,this.effect=parseInt(t[0]),this.mobile_effect=parseInt(t[1]),this.change=s,this.arr=a,this.responsive=parseInt(n),this.init()};LEFTMENU.prototype={init:function(){this.isMobile=navigator.userAgent.match(/iPhone|iPad|iPod/i)||navigator.userAgent.match(/Android/i)||navigator.userAgent.match(/BlackBerry/i)||navigator.userAgent.match(/Opera Mini/i)||navigator.userAgent.match(/IEMobile/i),this.option(),this.setWidth(this.width_default,this.main_width),this.categoriesLevel(),this.categoriesDynamic(),this.categoriesMobile(),this.applyEvent(),this.mobile()},option:function(){this.ms_level0=this.menu.children(".msl-level0"),this.label=this.ms_level0.children(".msl-label"),this.submenu=this.ms_level0.children(".msl-submenu"),this.sub_left=this.ms_level0.children(".sub_left"),this.sub_right=this.ms_level0.children(".sub_right"),this.categoryParent=this.ms_level0.find(".msl-submenu .ms-category-level .parent"),this.dynamicParent=this.ms_level0.find(".msl-submenu .ms-category-dynamic .col-level .parent"),this.anchor=this.menu.find(".anchor_mbmenu .anchor_mbmenu_text"),this.mblabel=this.ms_level0.children(".mb-label"),this.mbreturn=this.ms_level0.find(".mb-return"),this.mblevel=this.ms_level0.find(".lmb-submenu .mb-level-click"),this.width_default=this.menu.outerWidth(),this.main_width=this.main_div.outerWidth(),this.menu_id=this.menu.attr("id")},updateScreen:function(){this.width_default=this.menu.outerWidth(),this.main_width=this.main_div.outerWidth(),this.setWidth(this.width_default,this.main_width)},applyEvent:function(){if(null!=this.isMobile)this.toggle();else switch(this.effect){case eff_animation:this.slide();break;case eff_toggle:this.toggle();break;default:this.fade()}},mobile:function(){var e=this.menu;switch(this.anchor.bind("click",function(){return $_this=mega(this),$_this.hasClass("flag")?(e.removeClass("active"),$_this.removeClass("flag")):(e.addClass("active"),$_this.addClass("flag")),!1}),this.mobile_effect){case Slide:this.mobileSlide();break;default:this.mobileBlind()}},fade:function(){this.ms_level0.bind("mouseenter",function(){var e=mega(this);e.addClass("active"),e.children(".msl-submenu").stop().fadeIn(150)}),this.ms_level0.bind("mouseleave",function(){var e=mega(this);e.removeClass("active"),e.children(".msl-submenu").hide()})},slide:function(){this.ms_level0.bind("mouseenter",function(){var e=mega(this);e.addClass("active"),e.children(".msl-submenu").stop().slideDown(150)}),this.ms_level0.bind("mouseleave",function(){var e=mega(this);e.removeClass("active"),e.children(".msl-submenu").hide()})},toggle:function(){var e=this.menu_id,i=this.change,t=this.responsive;this.label.bind("click",function(){var s=mega(this);return s.hasClass("anchor_text")?void 0:(s.hasClass("flag")?(s.removeClass("flag"),s.parent().removeClass("active"),s.parent().children(".msl-submenu").hide()):(mega("#"+e+" .msl-level0").removeClass("active"),mega("#"+e+" .msl-label").removeClass("flag"),mega("#"+e+" .msl-submenu").hide(),s.addClass("flag"),s.parent().addClass("active"),s.parent().children(".msl-submenu").slideDown(150)),mega(window).width()>i||!t?!1:!0)})},mobileSlide:function(){var e=this.menu_id;left_click=this.mblabel,left_click.parent().children(".lmb-submenu").removeClass("blind"),this.mblabel.bind("click",function(){var i=mega(this);mega("#"+e+" .msl-level0").removeClass("mbactive"),i.parent().addClass("mbactive"),i.parent().children(".lmb-submenu").animate({left:0},300)}),this.mbreturn.bind("click",function(){mega(this);left_click.parent().children(".lmb-submenu").animate({left:"100%"},300,function(){left_click.parent().removeClass("mbactive")})})},mobileBlind:function(){var e=this.menu_id;this.mblabel.bind("click",function(){var i=mega(this);i.hasClass("glyphicon-minus")?(i.removeClass("glyphicon-minus"),i.parent().removeClass("mbactive"),i.parent().children(".lmb-submenu").slideUp(200)):(mega("#"+e+" .ms-level0").removeClass("mbactive"),mega("#"+e+" .mb-label").removeClass("glyphicon-minus"),mega("#"+e+" .lmb-submenu").slideUp(200),i.addClass("glyphicon-minus"),i.parent().addClass("mbactive"),i.parent().children(".lmb-submenu").slideDown(200))})},setWidth:function(e,i){for(var t=i-e,s=0;s 0) { $updateBtn.add($updateBtnMiniCart) .prop('disabled', false) .removeClass('disabled'); } else { $updateBtn.add($updateBtnMiniCart) .prop('disabled', true) .addClass('disabled'); } }); $(document) .off('keydown.qtyValidate', '.cart-item-quantity, .check-qty, #qty') .on('keydown.qtyValidate', '.cart-item-quantity, .check-qty, #qty', function(e){ var kc = e.keyCode; if ($.inArray(kc, [8,9,46,37,39]) !== -1) return; if ((kc >= 48 && kc <= 57) || (kc >= 96 && kc <= 105)) return; e.preventDefault(); }); $(document) .off('keyup.qtyValidate', '.cart-item-quantity, .check-qty, #qty') .on('keyup.qtyValidate', '.cart-item-quantity, .check-qty, #qty', function(){ var $this = $(this), val = $this.val().replace(/\D/g, ''); if (val.length > 0) { val = val.replace(/^0+/, ''); if (val === '') val = '1'; } $this.val(val); }); $updateBtn.on('click', function(e){ e.preventDefault(); if (this.disabled) return; var $form = $('#shopping-cart-form'); if ($form.length) { $('.form-loader-truper').show(); $form.find('.cart_plus, .cart_min').prop('disabled', true); $form.submit(); } }); $updateBtnMiniCart.on('click', function(e){ e.preventDefault(); if (this.disabled) return; var postData = { form_key: window.FORM_KEY }; $('#cart-sidebar .item').each(function(){ var id = $(this).data('item-id'), qty = parseInt($(this).find('input.qty').val(),10) || 0; if (id) postData['ids['+id+']'] = qty; }); if (Object.keys(postData).length <= 1) return; $.ajax({ url: '/checkout/cart/ajaxUpdate/uenc/' + uenc + '/', type: 'POST', dataType: 'json', data: postData, beforeSend: function(){ $('.form-loader-truper').show(); }, success: function(res){ if (res.sidebarHtml) { $('.block-cart .block-content').html(res.sidebarHtml); } $('#minicart-success-message') .text('El producto se actualizó correctamente') .show() .fadeOut(3000); }, error: function(jqXHR, textStatus, errorThrown){ console.error('Error Ajax:', textStatus, errorThrown); console.log('Response:', jqXHR.responseText); }, complete: function(){ $('.form-loader-truper').hide(); } }); }); window.productAddToCartForm = new VarienForm('product_addtocart_form'); window.productAddToCartForm.submit = function(button, url) { if (this.validator.validate()) { var form = this.form, oldUrl = form.action; if (url) form.action = url; try { form.submit(); } catch (e) {} form.action = oldUrl; if (button && button != 'undefined') button.disabled = true; } }.bind(window.productAddToCartForm); window.productAddToCartForm.submitLight = function(button, url) { if (this.validator) { var nv = Validation.methods; delete Validation.methods['required-entry']; delete Validation.methods['validate-one-required']; delete Validation.methods['validate-one-required-by-name']; for (var m in Validation.methods) { if (/^validate-datetime-/i.test(m)) delete Validation.methods[m]; } if (this.validator.validate()) { if (url) this.form.action = url; this.form.submit(); } Object.extend(Validation.methods, nv); } }.bind(window.productAddToCartForm); }); /*! modernizr 3.6.0 (Custom Build) | MIT * * https://modernizr.com/download/?-applicationcache-backgroundsize-borderimage-borderradius-boxshadow-cors-cssanimations-csscolumns-cssgradients-cssreflections-cssremunit-cssscrollbar-csstransforms-csstransforms3d-csstransitions-devicemotion_deviceorientation-fileinput-filereader-filesystem-flexbox-flexboxlegacy-fontface-formattribute-formvalidation-fullscreen-generatedcontent-hashchange-history-hsla-ie8compat-input-inputtypes-json-localstorage-multiplebgs-opacity-overflowscrolling-placeholder-postmessage-rgba-sessionstorage-strictmode-textshadow-addtest-atrule-domprefixes-hasevent-mq-prefixed-prefixedcss-prefixedcssvalue-prefixes-setclasses-testallprops-testprop-teststyles !*/ !function(e,t,n){function r(e,t){return typeof e===t}function i(){var e,t,n,i,o,s,a;for(var l in T)if(T.hasOwnProperty(l)){if(e=[],t=T[l],t.name&&(e.push(t.name.toLowerCase()),t.options&&t.options.aliases&&t.options.aliases.length))for(n=0;nf;f++)if(m=e[f],g=I.style[m],l(m,"-")&&(m=a(m)),I.style[m]!==n){if(o||r(i,"undefined"))return d(),"pfx"==t?m:!0;try{I.style[m]=i}catch(y){}if(I.style[m]!=g)return d(),"pfx"==t?m:!0}return d(),!1}function v(e,t,n,i,o){var s=e.charAt(0).toUpperCase()+e.slice(1),a=(e+" "+z.join(s+" ")+s).split(" ");return r(t,"string")||r(t,"undefined")?g(a,t,i,o):(a=(e+" "+A.join(s+" ")+s).split(" "),f(a,t,n))}function y(e,t,r){return v(e,n,n,t,r)}function b(e,t){if("object"==typeof e)for(var n in e)J(e,n)&&b(n,e[n]);else{e=e.toLowerCase();var r=e.split("."),i=Modernizr[r[0]];if(2==r.length&&(i=i[r[1]]),"undefined"!=typeof i)return Modernizr;t="function"==typeof t?t():t,1==r.length?Modernizr[r[0]]=t:(!Modernizr[r[0]]||Modernizr[r[0]]instanceof Boolean||(Modernizr[r[0]]=new Boolean(Modernizr[r[0]])),Modernizr[r[0]][r[1]]=t),o([(t&&0!=t?"":"no-")+r.join("-")]),Modernizr._trigger(e,t)}return Modernizr}var x=[],T=[],S={_version:"3.6.0",_config:{classPrefix:"",enableClasses:!0,enableJSClass:!0,usePrefixes:!0},_q:[],on:function(e,t){var n=this;setTimeout(function(){t(n[e])},0)},addTest:function(e,t,n){T.push({name:e,fn:t,options:n})},addAsyncTest:function(e){T.push({name:null,fn:e})}},Modernizr=function(){};Modernizr.prototype=S,Modernizr=new Modernizr,Modernizr.addTest("applicationcache","applicationCache"in e),Modernizr.addTest("cors","XMLHttpRequest"in e&&"withCredentials"in new XMLHttpRequest),Modernizr.addTest("history",function(){var t=navigator.userAgent;return-1===t.indexOf("Android 2.")&&-1===t.indexOf("Android 4.0")||-1===t.indexOf("Mobile Safari")||-1!==t.indexOf("Chrome")||-1!==t.indexOf("Windows Phone")||"file:"===location.protocol?e.history&&"pushState"in e.history:!1}),Modernizr.addTest("ie8compat",!e.addEventListener&&!!t.documentMode&&7===t.documentMode),Modernizr.addTest("json","JSON"in e&&"parse"in JSON&&"stringify"in JSON),Modernizr.addTest("postmessage","postMessage"in e),Modernizr.addTest("strictmode",function(){"use strict";return!this}()),Modernizr.addTest("devicemotion","DeviceMotionEvent"in e),Modernizr.addTest("deviceorientation","DeviceOrientationEvent"in e),Modernizr.addTest("filereader",!!(e.File&&e.FileList&&e.FileReader)),Modernizr.addTest("localstorage",function(){var e="modernizr";try{return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch(t){return!1}}),Modernizr.addTest("sessionstorage",function(){var e="modernizr";try{return sessionStorage.setItem(e,e),sessionStorage.removeItem(e),!0}catch(t){return!1}});var C=S._config.usePrefixes?" -webkit- -moz- -o- -ms- ".split(" "):["",""];S._prefixes=C;var w=t.documentElement,_="svg"===w.nodeName.toLowerCase(),k="Moz O ms Webkit",A=S._config.usePrefixes?k.toLowerCase().split(" "):[];S._domPrefixes=A;var z=S._config.usePrefixes?k.split(" "):[];S._cssomPrefixes=z;var E=function(t){var r,i=C.length,o=e.CSSRule;if("undefined"==typeof o)return n;if(!t)return!1;if(t=t.replace(/^@/,""),r=t.replace(/-/g,"_").toUpperCase()+"_RULE",r in o)return"@"+t;for(var s=0;i>s;s++){var a=C[s],l=a.toUpperCase()+"_"+r;if(l in o)return"@-"+a.toLowerCase()+"-"+t}return!1};S.atRule=E;var O=function(){function e(e,t){var i;return e?(t&&"string"!=typeof t||(t=s(t||"div")),e="on"+e,i=e in t,!i&&r&&(t.setAttribute||(t=s("div")),t.setAttribute(e,""),i="function"==typeof t[e],t[e]!==n&&(t[e]=n),t.removeAttribute(e)),i):!1}var r=!("onblur"in t.documentElement);return e}();S.hasEvent=O,Modernizr.addTest("hashchange",function(){return O("hashchange",e)===!1?!1:t.documentMode===n||t.documentMode>7}),Modernizr.addTest("fileinput",function(){if(navigator.userAgent.match(/(Android (1.0|1.1|1.5|1.6|2.0|2.1))|(Windows Phone (OS 7|8.0))|(XBLWP)|(ZuneWP)|(w(eb)?OSBrowser)|(webOS)|(Kindle\/(1.0|2.0|2.5|3.0))/))return!1;var e=s("input");return e.type="file",!e.disabled}),Modernizr.addTest("formattribute",function(){var e,n=s("form"),r=s("input"),i=s("div"),o="formtest"+(new Date).getTime(),a=!1;n.id=o;try{r.setAttribute("form",o)}catch(l){t.createAttribute&&(e=t.createAttribute("form"),e.nodeValue=o,r.setAttributeNode(e))}return i.appendChild(n),i.appendChild(r),w.appendChild(i),a=n.elements&&1===n.elements.length&&r.form==n,i.parentNode.removeChild(i),a}),Modernizr.addTest("placeholder","placeholder"in s("input")&&"placeholder"in s("textarea")),Modernizr.addTest("cssgradients",function(){for(var e,t="background-image:",n="gradient(linear,left top,right bottom,from(#9f9),to(white));",r="",i=0,o=C.length-1;o>i;i++)e=0===i?"to ":"",r+=t+C[i]+"linear-gradient("+e+"left top, #9f9, white);";Modernizr._config.usePrefixes&&(r+=t+"-webkit-"+n);var a=s("a"),l=a.style;return l.cssText=r,(""+l.backgroundImage).indexOf("gradient")>-1}),Modernizr.addTest("multiplebgs",function(){var e=s("a").style;return e.cssText="background:url(https://),url(https://),red url(https://)",/(url\s*\(.*?){3}/.test(e.background)}),Modernizr.addTest("opacity",function(){var e=s("a").style;return e.cssText=C.join("opacity:.55;"),/^0.55$/.test(e.opacity)}),Modernizr.addTest("cssremunit",function(){var e=s("a").style;try{e.fontSize="3rem"}catch(t){}return/rem/.test(e.fontSize)}),Modernizr.addTest("rgba",function(){var e=s("a").style;return e.cssText="background-color:rgba(150,255,150,.5)",(""+e.backgroundColor).indexOf("rgba")>-1});var P=s("input"),L="autocomplete autofocus list placeholder max min multiple pattern required step".split(" "),R={};Modernizr.input=function(t){for(var n=0,r=t.length;r>n;n++)R[t[n]]=!!(t[n]in P);return R.list&&(R.list=!(!s("datalist")||!e.HTMLDataListElement)),R}(L);var M="search tel url email datetime date month week time datetime-local number range color".split(" "),N={};Modernizr.inputtypes=function(e){for(var r,i,o,s=e.length,a="1)",l=0;s>l;l++)P.setAttribute("type",r=e[l]),o="text"!==P.type&&"style"in P,o&&(P.value=a,P.style.cssText="position:absolute;visibility:hidden;",/^range$/.test(r)&&P.style.WebkitAppearance!==n?(w.appendChild(P),i=t.defaultView,o=i.getComputedStyle&&"textfield"!==i.getComputedStyle(P,null).WebkitAppearance&&0!==P.offsetHeight,w.removeChild(P)):/^(search|tel)$/.test(r)||(o=/^(url|email)$/.test(r)?P.checkValidity&&P.checkValidity()===!1:P.value!=a)),N[e[l]]=!!o;return N}(M),Modernizr.addTest("hsla",function(){var e=s("a").style;return e.cssText="background-color:hsla(120,40%,100%,.5)",l(e.backgroundColor,"rgba")||l(e.backgroundColor,"hsla")});var B="CSS"in e&&"supports"in e.CSS,j="supportsCSS"in e;Modernizr.addTest("supports",B||j);var q=S.testStyles=u,V=function(){var e=navigator.userAgent,t=e.match(/w(eb)?osbrowser/gi),n=e.match(/windows phone/gi)&&e.match(/iemobile\/([0-9])+/gi)&&parseFloat(RegExp.$1)>=9;return t||n}();V?Modernizr.addTest("fontface",!1):q('@font-face {font-family:"font";src:url("https://")}',function(e,n){var r=t.getElementById("smodernizr"),i=r.sheet||r.styleSheet,o=i?i.cssRules&&i.cssRules[0]?i.cssRules[0].cssText:i.cssText||"":"",s=/src/i.test(o)&&0===o.indexOf(n.split(" ")[0]);Modernizr.addTest("fontface",s)}),Modernizr.addTest("formvalidation",function(){var t=s("form");if(!("checkValidity"in t&&"addEventListener"in t))return!1;if("reportValidity"in t)return!0;var n,r=!1;return Modernizr.formvalidationapi=!0,t.addEventListener("submit",function(t){(!e.opera||e.operamini)&&t.preventDefault(),t.stopPropagation()},!1),t.innerHTML='',q("#modernizr form{position:absolute;top:-99999em}",function(e){e.appendChild(t),n=t.getElementsByTagName("input")[0],n.addEventListener("invalid",function(e){r=!0,e.preventDefault(),e.stopPropagation()},!1),Modernizr.formvalidationmessage=!!n.validationMessage,t.getElementsByTagName("button")[0].click()}),r}),q('#modernizr{font:0/0 a}#modernizr:after{content:":)";visibility:hidden;font:7px/1 a}',function(e){Modernizr.addTest("generatedcontent",e.offsetHeight>=6)}),q("#modernizr{overflow: scroll; width: 40px; height: 40px; }#"+C.join("scrollbar{width:10px} #modernizr::").split("#").slice(1).join("#")+"scrollbar{width:10px}",function(e){Modernizr.addTest("cssscrollbar","scrollWidth"in e&&30==e.scrollWidth)});var W={elem:s("modernizr")};Modernizr._q.push(function(){delete W.elem});var I={style:W.elem.style};Modernizr._q.unshift(function(){delete I.style});var F=S.testProp=function(e,t,r){return g([e],n,t,r)};Modernizr.addTest("textshadow",F("textShadow","1px 1px")),S.testAllProps=v;var $=S.prefixed=function(e,t,n){return 0===e.indexOf("@")?E(e):(-1!=e.indexOf("-")&&(e=a(e)),t?v(e,t,n):v(e,"pfx"))};Modernizr.addTest("fullscreen",!(!$("exitFullscreen",t,!1)&&!$("cancelFullScreen",t,!1))),Modernizr.addTest("filesystem",!!$("requestFileSystem",e)),S.testAllProps=y,Modernizr.addTest("csstransitions",y("transition","all",!0)),Modernizr.addTest("cssanimations",y("animationName","a",!0)),Modernizr.addTest("backgroundsize",y("backgroundSize","100%",!0)),Modernizr.addTest("borderimage",y("borderImage","url() 1",!0)),Modernizr.addTest("borderradius",y("borderRadius","0px",!0)),Modernizr.addTest("boxshadow",y("boxShadow","1px 1px",!0)),function(){Modernizr.addTest("csscolumns",function(){var e=!1,t=y("columnCount");try{e=!!t,e&&(e=new Boolean(e))}catch(n){}return e});for(var e,t,n=["Width","Span","Fill","Gap","Rule","RuleColor","RuleStyle","RuleWidth","BreakBefore","BreakAfter","BreakInside"],r=0;r8 || !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 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 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 * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE_AFL.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * 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-2017 X.commerce, Inc. and affiliates (http://www.magento.com) * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) */ // ============================================= // 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, large: 979, 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.medium + "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(); } }; // ============================================== // jQuery Init // ============================================== // Use $j(document).ready() because Magento executes Prototype inline $j(document).ready(function () { // ============================================== // Shared Vars // ============================================== // Document var w = $j(window); var d = $j(document); var body = $j('body'); 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') ? 1 : 0; // 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(); }); $j('#header-minilogin').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.medium + 'px)', { match: function () { $j('.page-header-container .store-language-container').prepend($j('.form-language')); }, unmatch: function () { $j('.header-language-container .store-language-container').prepend($j('.form-language')); } }); // ============================================== // Enquire JS // ============================================== enquire.register('screen and (min-width: ' + (bp.medium + 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: //
    //
    Trigger
    //
    Content that should show when
    //
    // // JS: jQuery('.block-title').toggleSingle(); // // 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) // ============================================== $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 = new Array(dts, panes); //Create a ul for tabs if necessary. if (hasTabs) { var ul = jQuery('
      '); dts.each(function () { var dt = jQuery(this); var li = jQuery('
    • '); 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'); } }); // ============================================== // 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('div.category-products').length) { enquire.register('screen and (max-width: ' + bp.medium + 'px)', { match: function () { $j('.col-left-first').insertBefore($j('div.category-products')); }, 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) // ============================================== enquire.register('(max-width: ' + bp.medium + '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 () { if(this.toggleElements.length > 0){ this.toggleElements.toggleSingle(); } }, unmatch: function () { if(this.toggleElements.length > 0){ 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 = 10; // 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.medium + "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(document).on('click','.product-image-thumbs .thumb-link',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) { ProductMediaManager.initZoom(); }); ProductMediaManager.initZoom(); ProductMediaManager.wireThumbnails(); $j(document).trigger('product-media-loaded', ProductMediaManager); } }; $j(document).ready(function() { ProductMediaManager.init(); }); /*! * 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:"
      {{title}}
      {{desc}}
      ",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.currSlider;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:""}),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.timea.event.special.swipe.horizontalDistanceThreshold&&Math.abs(f.coords[1]-e.coords[1])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); /*! * 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 * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE_AFL.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * 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://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) */ function Minicart(options) { this.formKey = options.formKey; this.previousVal = null; this.defaultErrorMessage = 'Error occurred. Try to refresh page.'; this.selectors = { itemRemove: '#cart-sidebar .remove', container: '#minicart-content', minicartContent: '#minicart-content', inputQty: '.cart-item-quantity', qty: 'div.top-bar-cart span.cart-qty', overlay: '.minicart-wrapper', error: '#minicart-error-message', success: '#minicart-success-message', quantityButtonPrefix: '#qbutton-', quantityInputPrefix: '#qinput-', quantityButtonClass: '.quantity-button' }; 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) { cart.updateCartQty(result.qty); cart.updateContentOnRemove(result, el.closest('li')); } 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); } }, 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')); } } 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.minicartContent).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); } }, isValidQty: function(val) { return (val.length > 0) && (val - 0 == 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'); } }; AmAjaxLogin = Class.create(); AmAjaxLogin.prototype = { options : null, url : null, timer: 0, srcImageProgress : null, loggedIn : null, hideFrame: null, initialize : function(options) { this.url = options['send_url']; this.options = options; this.srcImageProgress = options['src_image_progress']; this.loggedIn = options['logged_in']; }, /*start helper functions*/ updateHeader : function() { if($$('.header-container')[0]){ var url = this.url.replace(this.url.substring(this.url.length-6, this.url.length), 'header');// new Ajax.Request(url, { method: 'post', onSuccess: function(transport) { if(transport.responseText) { var response = transport.responseText; var holderDiv = document.createElement('div'); holderDiv = $(holderDiv); holderDiv.innerHTML = response; text = ""; holderDiv.childElements().each(function(div){ if(div.hasClassName("header-container")) text += div.innerHTML; }) if(text) $$('.header-container')[0].innerHTML = text; AmAjaxLoginLoad('a[href*="customer/account/login/"]'); AmAjaxLogoutLoad('a[href*="customer/account/logout/"]'); } }.bind(this), }); } }, showAnimation: function() { var progress = document.createElement('div'); progress = jQuery(progress); // fix for IE progress.attr('id','amprogress'); var container = document.createElement('div'); container = jQuery(container); // fix for IE container.attr('id','amimg_container'); container.appendTo(progress); var img = document.createElement('img'); img = jQuery(img); // fix for IE img.attr('src', this.srcImageProgress); img.appendTo(container); container.width('150px'); var width = container.width(); width = "-" + width/2 + "px" ; container.css("margin-left", width); progress.hide().appendTo('body').fadeIn(); }, hideAnimation: function() { /* if($('amprogress')) { jQuery('#amprogress').fadeOut(function() { if($('amprogress')) $('amprogress').remove(); }); }*/ if($('amprogress')) { $('amprogress').remove(); } this.cancelHideFrame(); }, //add parametr from form on product view page addFormParam: function(id) { postData = ""; var form = $(id); if(form) { var len=form.elements.length-1; var validator = new Validation(form); if (validator.validate()) { postData = jQuery(form).serialize(); } } return postData; }, showMessage: function(response) { if($('am-ajaxlogin-container'))$('am-ajaxlogin-container').remove(); var container = document.createElement('div'); container = $(container); container.id = 'am-ajaxlogin-container'; $$('body')[0].appendChild(container); var hideDiv = document.createElement('div'); hideDiv = $(hideDiv); hideDiv.id = 'hideDiv'; Event.observe(hideDiv, 'click', function(){AmAjaxLoginObj.hideMessage()} ); container.appendChild(hideDiv); var loginBox = document.createElement('div'); loginBox = $(loginBox); loginBox.id = 'am-ajaxlogin'; container.appendChild(loginBox); var closeBox = document.createElement('div'); closeBox = $(closeBox); closeBox.id = 'am-ajaxlogin-close'; closeBox.innerHTML = 'X'; loginBox.appendChild(closeBox); Event.observe(closeBox, 'click', function(){AmAjaxLoginObj.hideMessage()} ); var titleBox = document.createElement('div'); titleBox = $(titleBox); titleBox.id = 'am-ajaxlogin-title'; titleBox.innerHTML = response.title; loginBox.appendChild(titleBox); if(response.error){ var errorBox = document.createElement('div'); errorBox = $(errorBox); errorBox.id = 'am-ajaxlogin-error'; text = response.error.replace(new RegExp('<', 'g'), "<"); text = text.replace(new RegExp('>', 'g'), ">"); errorBox.innerHTML = text; loginBox.appendChild(errorBox); } var messageBox = document.createElement('div'); messageBox = $(messageBox); messageBox.id = 'am-ajaxlogin-message'; messageBox.innerHTML = response.message; loginBox.appendChild(messageBox); if(response.redirect && response.is_error == "2"){ if(response.redirect == "1") { location.reload(); } else { window.location = response.redirect; } } try { eval(response.script); } catch(e) { console.debug(e); } }, hideMessage: function() { if($('am-ajaxlogin-container')) { this.hideFrame = new Effect.Opacity('am-ajaxlogin-container', { from: 1.0, to: 0, duration: 0.2, afterFinish: function () { $('am-ajaxlogin-container').remove(); } }); } }, /*end helper functions*/ /*start login functions*/ login: function() { var postData = this.addFormParam('amajaxlogin-login-form'); if('' == postData) return false; this.showAnimation(); var url = this.url.replace(this.url.substring(this.url.length-6, this.url.length), 'login');// replace ajax to login new Ajax.Request(url, { method: 'post', postBody : postData, onComplete: function() { this.hideAnimation(); }.bind(this), onSuccess: function(transport) { var response = transport.responseText.evalJSON() if (transport.responseText.isJSON() && response) { this.hideAnimation(); this.showMessage(response); if(response.is_error == "2"){ this.updateHeader(); if($$('body')[0].hasClassName('customer-account-index') || $$('body')[0].hasClassName('checkout-onepage-index') || $$('body')[0].hasClassName('customer-account-login') ) { window.location.reload(); } } } }.bind(this), onFailure: function() { this.hideAnimation(); }.bind(this) }); return false; }, logoutAjax: function() { this.showAnimation(); var url = this.url.replace(this.url.substring(this.url.length-6, this.url.length), 'logout');// replace ajax to login this.timer = 0; new Ajax.Request(url, { method: 'post', onComplete: function() { this.hideAnimation(); }.bind(this), onSuccess: function(transport) { var response = transport.responseText.evalJSON() if (transport.responseText.isJSON() && response) { this.hideAnimation(); this.showMessage(response); if(response.is_error == "2"){ this.updateHeader(); if($$('body')[0].hasClassName('customer-account-index') || $$('body')[0].hasClassName('checkout-onepage-index') || $$('body')[0].hasClassName('customer-account-login') ) { window.location.reload(); } } } }.bind(this), onFailure: function() { this.hideAnimation(); }.bind(this) }); return false; }, sendLoginAjax : function() { new Ajax.Request(this.url, { method: 'post', onCreate: function() { this.showAnimation(); }.bind(this), onComplete: function() { this.hideAnimation(); }.bind(this), onSuccess: function(transport) { var response = transport.responseText.evalJSON(); if (transport.responseText.isJSON() && response) { this.hideAnimation(); this.showMessage(response); } }.bind(this), onFailure: function() { this.hideAnimation(); }.bind(this) }); return false; }, /*end login functions*/ /*start forgot functions*/ forgotPassword: function(){ this.hideMessage(); this.showAnimation(); var url = this.url.replace(this.url.substring(this.url.length-6, this.url.length), 'forgotPassword');// replace ajax to forgotPassword new Ajax.Request(url, { method: 'post', onComplete: function() { this.hideAnimation(); }.bind(this), onSuccess: function(transport) { var response = transport.responseText.evalJSON() if (transport.responseText.isJSON() && response) { this.hideAnimation(); this.showMessage(response); } }.bind(this), onFailure: function() { this.hideAnimation(); }.bind(this) }); return false; }, forgotPasswordSend: function(){ var postData = this.addFormParam('amajaxlogin-form-validate'); if('' == postData) return false; this.hideMessage(); this.showAnimation(); var url = this.url.replace(this.url.substring(this.url.length-6, this.url.length), 'forgotpasswordpost');// replace ajax to forgotpasswordpost new Ajax.Request(url, { method: 'post', postBody : postData, onComplete: function() { this.hideAnimation(); }.bind(this), onSuccess: function(transport) { var response = transport.responseText.evalJSON() if (transport.responseText.isJSON() && response) { this.hideAnimation(); this.showMessage(response); } }.bind(this), onFailure: function() { this.hideAnimation(); }.bind(this) }); return false; }, /*end forgot functions*/ /*start facebook functions*/ loginS: function (img, tim) { if(!img || this.timer) return; if(tim) this.timer = 1; var postData = img.getAttribute("data"); var iframe = createIframe("am_ajax_login_iframe", postData, 0); this.hideMessage(); this.showAnimation(); jQuery(iframe).load(function(event){ AmAjaxLoginObj.hideAnimation(); var iframe = Event.element(event); if(iframe.contentDocument || iframe.contentWindow.document){ var innerDoc = iframe.contentDocument || iframe.contentWindow.document; } else{ var innerDoc = iframe; } if(iframe && innerDoc.getElementsByTagName("plaintext").length) { iframe = jQuery(iframe); var answer = iframe.contents().find("plaintext").html(); response = answer.evalJSON(); AmAjaxLoginObj.showMessage(response); if(response.is_error == "2"){ AmAjaxLoginObj.updateHeader(); } if($$('body')[0].hasClassName('customer-account-index') || $$('body')[0].hasClassName('checkout-onepage-index') || $$('body')[0].hasClassName('customer-account-login') ) { window.location.reload(); } } iframe.remove(); }); }, loginTw: function (img) { if(!img) return; this.img = img this.timer = 0; var postData = img.getAttribute("dataTw"); this.newWindow = window.open(postData, 'Sample','toolbar=no,width=590,height=590,left=0,top=0, status=no,scrollbars=no,resize=no'); window.amtimer = setInterval(function() { if (AmAjaxLoginObj.newWindow.closed) { AmAjaxLoginObj.loginS(AmAjaxLoginObj.img, 1) ; while ((amtimer--)>0) { window.clearInterval(amtimer); } } } , 200); }, cancelHideFrame: function () { if (this.hideFrame) { this.hideFrame.cancel(); this.hideFrame = null; } } } function AmAjaxLoginLoad(buttonClass){ if(!AmAjaxLoginObj.loggedIn) { buttonClass += ', ul.links li a[href$="customer/account/"]'; $$('ul.links li a[href$="wishlist/"]').each(function(link){ link.onclick = ''; Event.observe(link, 'click', loadLoginWithAjax); }); } $$(buttonClass).each(function(link){ link.onclick = ''; Event.observe(link, 'click', loadLoginWithAjax); }); } function AmAjaxLogoutLoad(buttonClass){ $$(buttonClass).each(function(link){ link.onclick = ''; Event.observe(link, 'click', loadLogoutWithAjax); }) } function loadLoginWithAjax(event) { event.preventDefault(); AmAjaxLoginObj.sendLoginAjax(); } function loadLogoutWithAjax(event) { event.preventDefault(); AmAjaxLoginObj.logoutAjax(); } /*document.observe("dom:loaded", function() { AmAjaxLoginLoad('a[href*="customer/account/login/"]'); AmAjaxLogoutLoad('a[href*="customer/account/logout/"]'); });*/ function createIframe(name, src, debug) { src = src || 'javascript:false'; var tmpElem = document.createElement('div'); tmpElem.innerHTML = '"; $(this.getId() +"_table_content").innerHTML = content; this.content = $(this.element.id + "_content"); }, getURL: function() { return this.options.url ? this.options.url : null; }, refresh: function() { if (this.options.url) $(this.element.getAttribute('id') + '_content').src = this.options.url; }, // Stores position/size in a cookie, by default named with window id setCookie: function(name, expires, path, domain, secure) { name = name || this.element.id; this.cookie = [name, expires, path, domain, secure]; // Get cookie var value = WindowUtilities.getCookie(name); // If exists if (value) { var values = value.split(','); var x = values[0].split(':'); var y = values[1].split(':'); var w = parseFloat(values[2]), h = parseFloat(values[3]); var mini = values[4]; var maxi = values[5]; this.setSize(w, h); if (mini == "true") this.doMinimize = true; // Minimize will be done at onload window event else if (maxi == "true") this.doMaximize = true; // Maximize will be done at onload window event this.useLeft = x[0] == "l"; this.useTop = y[0] == "t"; this.element.setStyle(this.useLeft ? {left: x[1]} : {right: x[1]}); this.element.setStyle(this.useTop ? {top: y[1]} : {bottom: y[1]}); } }, // Gets window ID getId: function() { return this.element.id; }, // Detroys itself when closing setDestroyOnClose: function() { this.options.destroyOnClose = true; }, setConstraint: function(bool, padding) { this.constraint = bool; this.constraintPad = Object.extend(this.constraintPad, padding || {}); // Reset location to apply constraint if (this.useTop && this.useLeft) this.setLocation(parseFloat(this.element.style.top), parseFloat(this.element.style.left)); }, // initDrag event _initDrag: function(event) { // No resize on minimized window if (Event.element(event) == this.sizer && this.isMinimized()) return; // No move on maximzed window if (Event.element(event) != this.sizer && this.isMaximized()) return; if (Prototype.Browser.IE && this.heightN === 0) this._getWindowBorderSize(); // Get pointer X,Y this.pointer = [this._round(Event.pointerX(event), this.options.gridX), this._round(Event.pointerY(event), this.options.gridY)]; if (this.options.wiredDrag) this.currentDrag = this._createWiredElement(); else this.currentDrag = this.element; // Resize if (Event.element(event) == this.sizer) { this.doResize = true; this.widthOrg = this.width; this.heightOrg = this.height; this.bottomOrg = parseFloat(this.element.getStyle('bottom')); this.rightOrg = parseFloat(this.element.getStyle('right')); this._notify("onStartResize"); } else { this.doResize = false; // Check if click on close button, var closeButton = $(this.getId() + '_close'); if (closeButton && Position.within(closeButton, this.pointer[0], this.pointer[1])) { this.currentDrag = null; return; } this.toFront(); if (! this.options.draggable) return; this._notify("onStartMove"); } // Register global event to capture mouseUp and mouseMove Event.observe(document, "mouseup", this.eventMouseUp, false); Event.observe(document, "mousemove", this.eventMouseMove, false); // Add an invisible div to keep catching mouse event over iframes WindowUtilities.disableScreen('__invisible__', '__invisible__', this.overlayOpacity); // Stop selection while dragging document.body.ondrag = function () { return false; }; document.body.onselectstart = function () { return false; }; this.currentDrag.show(); Event.stop(event); }, _round: function(val, round) { return round == 1 ? val : val = Math.floor(val / round) * round; }, // updateDrag event _updateDrag: function(event) { var pointer = [this._round(Event.pointerX(event), this.options.gridX), this._round(Event.pointerY(event), this.options.gridY)]; var dx = pointer[0] - this.pointer[0]; var dy = pointer[1] - this.pointer[1]; // Resize case, update width/height if (this.doResize) { var w = this.widthOrg + dx; var h = this.heightOrg + dy; dx = this.width - this.widthOrg; dy = this.height - this.heightOrg; // Check if it's a right position, update it to keep upper-left corner at the same position if (this.useLeft) w = this._updateWidthConstraint(w); else this.currentDrag.setStyle({right: (this.rightOrg -dx) + 'px'}); // Check if it's a bottom position, update it to keep upper-left corner at the same position if (this.useTop) h = this._updateHeightConstraint(h); else this.currentDrag.setStyle({bottom: (this.bottomOrg -dy) + 'px'}); this.setSize(w , h); this._notify("onResize"); } // Move case, update top/left else { this.pointer = pointer; if (this.useLeft) { var left = parseFloat(this.currentDrag.getStyle('left')) + dx; var newLeft = this._updateLeftConstraint(left); // Keep mouse pointer correct this.pointer[0] += newLeft-left; this.currentDrag.setStyle({left: newLeft + 'px'}); } else this.currentDrag.setStyle({right: parseFloat(this.currentDrag.getStyle('right')) - dx + 'px'}); if (this.useTop) { var top = parseFloat(this.currentDrag.getStyle('top')) + dy; var newTop = this._updateTopConstraint(top); // Keep mouse pointer correct this.pointer[1] += newTop - top; this.currentDrag.setStyle({top: newTop + 'px'}); } else this.currentDrag.setStyle({bottom: parseFloat(this.currentDrag.getStyle('bottom')) - dy + 'px'}); this._notify("onMove"); } if (this.iefix) this._fixIEOverlapping(); this._removeStoreLocation(); Event.stop(event); }, // endDrag callback _endDrag: function(event) { // Remove temporary div over iframes WindowUtilities.enableScreen('__invisible__'); if (this.doResize) this._notify("onEndResize"); else this._notify("onEndMove"); // Release event observing Event.stopObserving(document, "mouseup", this.eventMouseUp,false); Event.stopObserving(document, "mousemove", this.eventMouseMove, false); Event.stop(event); this._hideWiredElement(); // Store new location/size if need be this._saveCookie(); // Restore selection document.body.ondrag = null; document.body.onselectstart = null; }, _updateLeftConstraint: function(left) { if (this.constraint && this.useLeft && this.useTop) { var width = this.options.parent == document.body ? WindowUtilities.getPageSize().windowWidth : this.options.parent.getDimensions().width; if (left < this.constraintPad.left) left = this.constraintPad.left; if (left + this.width + this.widthE + this.widthW > width - this.constraintPad.right) left = width - this.constraintPad.right - this.width - this.widthE - this.widthW; } return left; }, _updateTopConstraint: function(top) { if (this.constraint && this.useLeft && this.useTop) { var height = this.options.parent == document.body ? WindowUtilities.getPageSize().windowHeight : this.options.parent.getDimensions().height; var h = this.height + this.heightN + this.heightS; if (top < this.constraintPad.top) top = this.constraintPad.top; if (top + h > height - this.constraintPad.bottom) top = height - this.constraintPad.bottom - h; } return top; }, _updateWidthConstraint: function(w) { if (this.constraint && this.useLeft && this.useTop) { var width = this.options.parent == document.body ? WindowUtilities.getPageSize().windowWidth : this.options.parent.getDimensions().width; var left = parseFloat(this.element.getStyle("left")); if (left + w + this.widthE + this.widthW > width - this.constraintPad.right) w = width - this.constraintPad.right - left - this.widthE - this.widthW; } return w; }, _updateHeightConstraint: function(h) { if (this.constraint && this.useLeft && this.useTop) { var height = this.options.parent == document.body ? WindowUtilities.getPageSize().windowHeight : this.options.parent.getDimensions().height; var top = parseFloat(this.element.getStyle("top")); if (top + h + this.heightN + this.heightS > height - this.constraintPad.bottom) h = height - this.constraintPad.bottom - top - this.heightN - this.heightS; } return h; }, // Creates HTML window code _createWindow: function(id) { var className = this.options.className; var win = document.createElement("div"); win.setAttribute('id', id); win.className = "dialog"; if (this.options.windowClassName) { win.className += ' ' + this.options.windowClassName; } var content; if (this.options.url) content= ""; else content ="
      "; var closeDiv = this.options.closable ? "
      " : ""; var minDiv = this.options.minimizable ? "
      " : ""; var maxDiv = this.options.maximizable ? "
      " : ""; var seAttributes = this.options.resizable ? "class='" + className + "_sizer' id='" + id + "_sizer'" : "class='" + className + "_se'"; var blank = "../themes/default/blank.gif"; win.innerHTML = closeDiv + minDiv + maxDiv + "" + "
      " + "" + "" + "" + "" + "" + "
      "+ this.options.title +"
      " + "" + "" + "" + "" + "" + "" + "
      " + content + "
      " + "" + "" + "" + "" + "" + "" + "
      "; Element.hide(win); this.options.parent.insertBefore(win, this.options.parent.firstChild); Event.observe($(id + "_content"), "load", this.options.onload); return win; }, changeClassName: function(newClassName) { var className = this.options.className; var id = this.getId(); $A(["_close", "_minimize", "_maximize", "_sizer", "_content"]).each( function(value) { this._toggleClassName($(id + value), className + value, newClassName + value); }.bind(this) ); this._toggleClassName($(id + "_top"), className + "_title", newClassName + "_title"); $$("#" + id + " td").each(function(td) {td.className = td.className.sub(className,newClassName); }); this.options.className = newClassName; }, _toggleClassName: function(element, oldClassName, newClassName) { if (element) { element.removeClassName(oldClassName); element.addClassName(newClassName); } }, // Sets window location setLocation: function(top, left) { top = this._updateTopConstraint(top); left = this._updateLeftConstraint(left); var e = this.currentDrag || this.element; e.setStyle({top: top + 'px'}); e.setStyle({left: left + 'px'}); this.useLeft = true; this.useTop = true; }, getLocation: function() { var location = {}; if (this.useTop) location = Object.extend(location, {top: this.element.getStyle("top")}); else location = Object.extend(location, {bottom: this.element.getStyle("bottom")}); if (this.useLeft) location = Object.extend(location, {left: this.element.getStyle("left")}); else location = Object.extend(location, {right: this.element.getStyle("right")}); return location; }, // Gets window size getSize: function() { return {width: this.width, height: this.height}; }, // Sets window size setSize: function(width, height, useEffect) { width = parseFloat(width); height = parseFloat(height); // Check min and max size if (!this.minimized && width < this.options.minWidth) width = this.options.minWidth; if (!this.minimized && height < this.options.minHeight) height = this.options.minHeight; if (this.options. maxHeight && height > this.options. maxHeight) height = this.options. maxHeight; if (this.options. maxWidth && width > this.options. maxWidth) width = this.options. maxWidth; if (this.useTop && this.useLeft && Window.hasEffectLib && Effect.ResizeWindow && useEffect) { new Effect.ResizeWindow(this, null, null, width, height, {duration: Window.resizeEffectDuration}); } else { this.width = width; this.height = height; var e = this.currentDrag ? this.currentDrag : this.element; e.setStyle({width: width + this.widthW + this.widthE + "px"}); e.setStyle({height: height + this.heightN + this.heightS + "px"}); // Update content size if (!this.currentDrag || this.currentDrag == this.element) { var content = $(this.element.id + '_content'); content.setStyle({height: height + 'px'}); content.setStyle({width: width + 'px'}); } } }, updateHeight: function() { this.setSize(this.width, this.content.scrollHeight, true); }, updateWidth: function() { this.setSize(this.content.scrollWidth, this.height, true); }, // Brings window to front toFront: function() { if (this.element.style.zIndex < Windows.maxZIndex) this.setZIndex(Windows.maxZIndex + 1); if (this.iefix) this._fixIEOverlapping(); }, getBounds: function(insideOnly) { if (! this.width || !this.height || !this.visible) this.computeBounds(); var w = this.width; var h = this.height; if (!insideOnly) { w += this.widthW + this.widthE; h += this.heightN + this.heightS; } var bounds = Object.extend(this.getLocation(), {width: w + "px", height: h + "px"}); return bounds; }, computeBounds: function() { if (! this.width || !this.height) { var size = WindowUtilities._computeSize(this.content.innerHTML, this.content.id, this.width, this.height, 0, this.options.className); if (this.height) this.width = size + 5; else this.height = size + 5; } this.setSize(this.width, this.height); if (this.centered) this._center(this.centerTop, this.centerLeft); }, // Displays window modal state or not show: function(modal) { this.visible = true; if (modal) { // Hack for Safari !! if (typeof this.overlayOpacity == "undefined") { var that = this; setTimeout(function() {that.show(modal);}, 10); return; } Windows.addModalWindow(this); this.modal = true; this.setZIndex(Windows.maxZIndex + 1); Windows.unsetOverflow(this); } else if (!this.element.style.zIndex) this.setZIndex(Windows.maxZIndex + 1); // To restore overflow if need be if (this.oldStyle) this.getContent().setStyle({overflow: this.oldStyle}); this.computeBounds(); this._notify("onBeforeShow"); if (this.options.showEffect != Element.show && this.options.showEffectOptions) this.options.showEffect(this.element, this.options.showEffectOptions); else this.options.showEffect(this.element); this._checkIEOverlapping(); WindowUtilities.focusedWindow = this; this._notify("onShow"); $(this.element.id + '_focus_anchor').focus(); }, // Displays window modal state or not at the center of the page showCenter: function(modal, top, left) { this.centered = true; this.centerTop = top; this.centerLeft = left; this.show(modal); }, isVisible: function() { return this.visible; }, _center: function(top, left) { var windowScroll = WindowUtilities.getWindowScroll(this.options.parent); var pageSize = WindowUtilities.getPageSize(this.options.parent); if (typeof top == "undefined") top = (pageSize.windowHeight - (this.height + this.heightN + this.heightS))/2; top += windowScroll.top; if (typeof left == "undefined") left = (pageSize.windowWidth - (this.width + this.widthW + this.widthE))/2; left += windowScroll.left; this.setLocation(top, left); this.toFront(); }, _recenter: function(event) { if (this.centered) { var pageSize = WindowUtilities.getPageSize(this.options.parent); var windowScroll = WindowUtilities.getWindowScroll(this.options.parent); // Check for this stupid IE that sends dumb events if (this.pageSize && this.pageSize.windowWidth == pageSize.windowWidth && this.pageSize.windowHeight == pageSize.windowHeight && this.windowScroll.left == windowScroll.left && this.windowScroll.top == windowScroll.top) return; this.pageSize = pageSize; this.windowScroll = windowScroll; // set height of Overlay to take up whole page and show if ($('overlay_modal')) $('overlay_modal').setStyle({height: (pageSize.pageHeight + 'px')}); if (this.options.recenterAuto) this._center(this.centerTop, this.centerLeft); } }, // Hides window hide: function() { this.visible = false; if (this.modal) { Windows.removeModalWindow(this); Windows.resetOverflow(); } // To avoid bug on scrolling bar this.oldStyle = this.getContent().getStyle('overflow') || "auto"; this.getContent().setStyle({overflow: "hidden"}); this.options.hideEffect(this.element, this.options.hideEffectOptions); if(this.iefix) this.iefix.hide(); if (!this.doNotNotifyHide) this._notify("onHide"); }, close: function() { // Asks closeCallback if exists if (this.visible) { if (this.options.closeCallback && ! this.options.closeCallback(this)) return; if (this.options.destroyOnClose) { var destroyFunc = this.destroy.bind(this); if (this.options.hideEffectOptions.afterFinish) { var func = this.options.hideEffectOptions.afterFinish; this.options.hideEffectOptions.afterFinish = function() {func();destroyFunc(); }; } else this.options.hideEffectOptions.afterFinish = function() {destroyFunc(); }; } Windows.updateFocusedWindow(); this.doNotNotifyHide = true; this.hide(); this.doNotNotifyHide = false; this._notify("onClose"); } }, minimize: function() { if (this.resizing) return; var r2 = $(this.getId() + "_row2"); if (!this.minimized) { this.minimized = true; var dh = r2.getDimensions().height; this.r2Height = dh; var h = this.element.getHeight() - dh; if (this.useLeft && this.useTop && Window.hasEffectLib && Effect.ResizeWindow) { new Effect.ResizeWindow(this, null, null, null, this.height -dh, {duration: Window.resizeEffectDuration}); } else { this.height -= dh; this.element.setStyle({height: h + "px"}); r2.hide(); } if (! this.useTop) { var bottom = parseFloat(this.element.getStyle('bottom')); this.element.setStyle({bottom: (bottom + dh) + 'px'}); } } else { this.minimized = false; var dh = this.r2Height; this.r2Height = null; if (this.useLeft && this.useTop && Window.hasEffectLib && Effect.ResizeWindow) { new Effect.ResizeWindow(this, null, null, null, this.height + dh, {duration: Window.resizeEffectDuration}); } else { var h = this.element.getHeight() + dh; this.height += dh; this.element.setStyle({height: h + "px"}); r2.show(); } if (! this.useTop) { var bottom = parseFloat(this.element.getStyle('bottom')); this.element.setStyle({bottom: (bottom - dh) + 'px'}); } this.toFront(); } this._notify("onMinimize"); // Store new location/size if need be this._saveCookie(); }, maximize: function() { if (this.isMinimized() || this.resizing) return; if (Prototype.Browser.IE && this.heightN === 0) this._getWindowBorderSize(); if (this.storedLocation !== null) { this._restoreLocation(); if(this.iefix) this.iefix.hide(); } else { this._storeLocation(); Windows.unsetOverflow(this); var windowScroll = WindowUtilities.getWindowScroll(this.options.parent); var pageSize = WindowUtilities.getPageSize(this.options.parent); var left = windowScroll.left; var top = windowScroll.top; if (this.options.parent != document.body) { windowScroll = {top:0, left:0, bottom:0, right:0}; var dim = this.options.parent.getDimensions(); pageSize.windowWidth = dim.width; pageSize.windowHeight = dim.height; top = 0; left = 0; } if (this.constraint) { pageSize.windowWidth -= Math.max(0, this.constraintPad.left) + Math.max(0, this.constraintPad.right); pageSize.windowHeight -= Math.max(0, this.constraintPad.top) + Math.max(0, this.constraintPad.bottom); left += Math.max(0, this.constraintPad.left); top += Math.max(0, this.constraintPad.top); } var width = pageSize.windowWidth - this.widthW - this.widthE; var height= pageSize.windowHeight - this.heightN - this.heightS; if (this.useLeft && this.useTop && Window.hasEffectLib && Effect.ResizeWindow) { new Effect.ResizeWindow(this, top, left, width, height, {duration: Window.resizeEffectDuration}); } else { this.setSize(width, height); this.element.setStyle(this.useLeft ? {left: left} : {right: left}); this.element.setStyle(this.useTop ? {top: top} : {bottom: top}); } this.toFront(); if (this.iefix) this._fixIEOverlapping(); } this._notify("onMaximize"); // Store new location/size if need be this._saveCookie(); }, isMinimized: function() { return this.minimized; }, isMaximized: function() { return (this.storedLocation !== null); }, setOpacity: function(opacity) { if (Element.setOpacity) Element.setOpacity(this.element, opacity); }, setZIndex: function(zindex) { this.element.setStyle({zIndex: zindex}); Windows.updateZindex(zindex, this); }, setTitle: function(newTitle) { if (!newTitle || newTitle == "") newTitle = " "; Element.update(this.element.id + '_top', newTitle); }, getTitle: function() { return $(this.element.id + '_top').innerHTML; }, setStatusBar: function(element) { var statusBar = $(this.getId() + "_bottom"); if (typeof(element) == "object") { if (this.bottombar.firstChild) this.bottombar.replaceChild(element, this.bottombar.firstChild); else this.bottombar.appendChild(element); } else this.bottombar.innerHTML = element; }, _checkIEOverlapping: function() { if(!this.iefix && (navigator.appVersion.indexOf('MSIE')>0) && (navigator.userAgent.indexOf('Opera')<0) && (this.element.getStyle('position')=='absolute')) { new Insertion.After(this.element.id, ''); this.iefix = $(this.element.id+'_iefix'); } if(this.iefix) setTimeout(this._fixIEOverlapping.bind(this), 50); }, _fixIEOverlapping: function() { Position.clone(this.element, this.iefix); this.iefix.style.zIndex = this.element.style.zIndex - 1; this.iefix.show(); }, _keyUp: function(event) { if (27 == event.keyCode && this.options.closeOnEsc) { this.close(); } }, _getWindowBorderSize: function(event) { // Hack to get real window border size!! var div = this._createHiddenDiv(this.options.className + "_n"); this.heightN = Element.getDimensions(div).height; div.parentNode.removeChild(div); var div = this._createHiddenDiv(this.options.className + "_s"); this.heightS = Element.getDimensions(div).height; div.parentNode.removeChild(div); var div = this._createHiddenDiv(this.options.className + "_e"); this.widthE = Element.getDimensions(div).width; div.parentNode.removeChild(div); var div = this._createHiddenDiv(this.options.className + "_w"); this.widthW = Element.getDimensions(div).width; div.parentNode.removeChild(div); var div = document.createElement("div"); div.className = "overlay_" + this.options.className ; document.body.appendChild(div); //alert("no timeout:\nopacity: " + div.getStyle("opacity") + "\nwidth: " + document.defaultView.getComputedStyle(div, null).width); var that = this; // Workaround for Safari!! setTimeout(function() {that.overlayOpacity = ($(div).getStyle("opacity")); div.parentNode.removeChild(div);}, 10); // Workaround for IE!! if (Prototype.Browser.IE) { this.heightS = $(this.getId() +"_row3").getDimensions().height; this.heightN = $(this.getId() +"_row1").getDimensions().height; } // Safari size fix if (Prototype.Browser.WebKit && Prototype.Browser.WebKitVersion < 420) this.setSize(this.width, this.height); if (this.doMaximize) this.maximize(); if (this.doMinimize) this.minimize(); }, _createHiddenDiv: function(className) { var objBody = document.body; var win = document.createElement("div"); win.setAttribute('id', this.element.id+ "_tmp"); win.className = className; win.style.display = 'none'; win.innerHTML = ''; objBody.insertBefore(win, objBody.firstChild); return win; }, _storeLocation: function() { if (this.storedLocation === null) { this.storedLocation = {useTop: this.useTop, useLeft: this.useLeft, top: this.element.getStyle('top'), bottom: this.element.getStyle('bottom'), left: this.element.getStyle('left'), right: this.element.getStyle('right'), width: this.width, height: this.height }; } }, _restoreLocation: function() { if (this.storedLocation !== null) { this.useLeft = this.storedLocation.useLeft; this.useTop = this.storedLocation.useTop; if (this.useLeft && this.useTop && Window.hasEffectLib && Effect.ResizeWindow) new Effect.ResizeWindow(this, this.storedLocation.top, this.storedLocation.left, this.storedLocation.width, this.storedLocation.height, {duration: Window.resizeEffectDuration}); else { this.element.setStyle(this.useLeft ? {left: this.storedLocation.left} : {right: this.storedLocation.right}); this.element.setStyle(this.useTop ? {top: this.storedLocation.top} : {bottom: this.storedLocation.bottom}); this.setSize(this.storedLocation.width, this.storedLocation.height); } Windows.resetOverflow(); this._removeStoreLocation(); } }, _removeStoreLocation: function() { this.storedLocation = null; }, _saveCookie: function() { if (this.cookie) { var value = ""; if (this.useLeft) value += "l:" + (this.storedLocation ? this.storedLocation.left : this.element.getStyle('left')); else value += "r:" + (this.storedLocation ? this.storedLocation.right : this.element.getStyle('right')); if (this.useTop) value += ",t:" + (this.storedLocation ? this.storedLocation.top : this.element.getStyle('top')); else value += ",b:" + (this.storedLocation ? this.storedLocation.bottom :this.element.getStyle('bottom')); value += "," + (this.storedLocation ? this.storedLocation.width : this.width); value += "," + (this.storedLocation ? this.storedLocation.height : this.height); value += "," + this.isMinimized(); value += "," + this.isMaximized(); WindowUtilities.setCookie(value, this.cookie); } }, _createWiredElement: function() { if (! this.wiredElement) { if (Prototype.Browser.IE) this._getWindowBorderSize(); var div = document.createElement("div"); div.className = "wired_frame " + this.options.className + "_wired_frame"; div.style.position = 'absolute'; this.options.parent.insertBefore(div, this.options.parent.firstChild); this.wiredElement = $(div); } if (this.useLeft) this.wiredElement.setStyle({left: this.element.getStyle('left')}); else this.wiredElement.setStyle({right: this.element.getStyle('right')}); if (this.useTop) this.wiredElement.setStyle({top: this.element.getStyle('top')}); else this.wiredElement.setStyle({bottom: this.element.getStyle('bottom')}); var dim = this.element.getDimensions(); this.wiredElement.setStyle({width: dim.width + "px", height: dim.height +"px"}); this.wiredElement.setStyle({zIndex: Windows.maxZIndex+30}); return this.wiredElement; }, _hideWiredElement: function() { if (! this.wiredElement || ! this.currentDrag) return; if (this.currentDrag == this.element) this.currentDrag = null; else { if (this.useLeft) this.element.setStyle({left: this.currentDrag.getStyle('left')}); else this.element.setStyle({right: this.currentDrag.getStyle('right')}); if (this.useTop) this.element.setStyle({top: this.currentDrag.getStyle('top')}); else this.element.setStyle({bottom: this.currentDrag.getStyle('bottom')}); this.currentDrag.hide(); this.currentDrag = null; if (this.doResize) this.setSize(this.width, this.height); } }, _notify: function(eventName) { if (this.options[eventName]) this.options[eventName](this); else Windows.notify(eventName, this); } }; // Windows containers, register all page windows var Windows = { windows: [], modalWindows: [], observers: [], focusedWindow: null, maxZIndex: 0, overlayShowEffectOptions: {duration: 0.5}, overlayHideEffectOptions: {duration: 0.5}, addObserver: function(observer) { this.removeObserver(observer); this.observers.push(observer); }, removeObserver: function(observer) { this.observers = this.observers.reject( function(o) { return o==observer; }); }, // onDestroy onStartResize onStartMove onResize onMove onEndResize onEndMove onFocus onBlur onBeforeShow onShow onHide onMinimize onMaximize onClose notify: function(eventName, win) { this.observers.each( function(o) {if(o[eventName]) o[eventName](eventName, win);}); }, // Gets window from its id getWindow: function(id) { return this.windows.detect(function(d) { return d.getId() ==id; }); }, // Gets the last focused window getFocusedWindow: function() { return this.focusedWindow; }, updateFocusedWindow: function() { this.focusedWindow = this.windows.length >=2 ? this.windows[this.windows.length-2] : null; }, // Registers a new window (called by Windows constructor) register: function(win) { this.windows.push(win); }, // Add a modal window in the stack addModalWindow: function(win) { // Disable screen if first modal window if (this.modalWindows.length === 0) { WindowUtilities.disableScreen(win.options.className, 'overlay_modal', win.overlayOpacity, win.getId(), win.options.parent); } else { // Move overlay over all windows if (Window.keepMultiModalWindow) { $('overlay_modal').style.zIndex = Windows.maxZIndex + 1; Windows.maxZIndex += 1; WindowUtilities._hideSelect(this.modalWindows.last().getId()); } // Hide current modal window else this.modalWindows.last().element.hide(); // Fucking IE select issue WindowUtilities._showSelect(win.getId()); } this.modalWindows.push(win); }, removeModalWindow: function(win) { this.modalWindows.pop(); // No more modal windows if (this.modalWindows.length === 0) WindowUtilities.enableScreen(); else { if (Window.keepMultiModalWindow) { this.modalWindows.last().toFront(); WindowUtilities._showSelect(this.modalWindows.last().getId()); } else this.modalWindows.last().element.show(); } }, // Unregisters a window (called by Windows destructor) unregister: function(win) { this.windows = this.windows.reject(function(d) { return d==win; }); }, // Closes all windows closeAll: function() { this.windows.each( function(w) {Windows.close(w.getId());} ); }, closeAllModalWindows: function() { WindowUtilities.enableScreen(); this.modalWindows.each( function(win) {if (win) win.close();}); }, // Minimizes a window with its id minimize: function(id, event) { var win = this.getWindow(id); if (win && win.visible) win.minimize(); Event.stop(event); }, // Maximizes a window with its id maximize: function(id, event) { var win = this.getWindow(id); if (win && win.visible) win.maximize(); Event.stop(event); }, // Closes a window with its id close: function(id, event) { var win = this.getWindow(id); if (win) win.close(); if (event) Event.stop(event); }, blur: function(id) { var win = this.getWindow(id); if (!win) return; if (win.options.blurClassName) win.changeClassName(win.options.blurClassName); if (this.focusedWindow == win) this.focusedWindow = null; win._notify("onBlur"); }, focus: function(id) { var win = this.getWindow(id); if (!win) return; if (this.focusedWindow) this.blur(this.focusedWindow.getId()); if (win.options.focusClassName) win.changeClassName(win.options.focusClassName); this.focusedWindow = win; win._notify("onFocus"); }, unsetOverflow: function(except) { this.windows.each(function(d) { d.oldOverflow = d.getContent().getStyle("overflow") || "auto" ; d.getContent().setStyle({overflow: "hidden"}); }); if (except && except.oldOverflow) except.getContent().setStyle({overflow: except.oldOverflow}); }, resetOverflow: function() { this.windows.each(function(d) { if (d.oldOverflow) d.getContent().setStyle({overflow: d.oldOverflow}); }); }, updateZindex: function(zindex, win) { if (zindex > this.maxZIndex) { this.maxZIndex = zindex; if (this.focusedWindow) this.blur(this.focusedWindow.getId()); } this.focusedWindow = win; if (this.focusedWindow) this.focus(this.focusedWindow.getId()); } }; var Dialog = { dialogId: null, onCompleteFunc: null, callFunc: null, parameters: null, confirm: function(content, parameters) { // Get Ajax return before if (content && typeof content != "string") { Dialog._runAjaxRequest(content, parameters, Dialog.confirm); return; } content = content || ""; parameters = parameters || {}; var okLabel = parameters.okLabel ? parameters.okLabel : "Ok"; var cancelLabel = parameters.cancelLabel ? parameters.cancelLabel : "Cancel"; // Backward compatibility parameters = Object.extend(parameters, parameters.windowParameters || {}); parameters.windowParameters = parameters.windowParameters || {}; parameters.className = parameters.className || "alert"; var okButtonClass = "class ='" + (parameters.buttonClass ? parameters.buttonClass + " " : "") + " ok_button'"; var cancelButtonClass = "class ='" + (parameters.buttonClass ? parameters.buttonClass + " " : "") + " cancel_button'"; /* var content = "\
      " + content + "
      \
      \ \ \
      \ "; */ var content = "
      " + content + "
      " + "
      " + "" + "" + "
      "; return this._openDialog(content, parameters); }, alert: function(content, parameters) { // Get Ajax return before if (content && typeof content != "string") { Dialog._runAjaxRequest(content, parameters, Dialog.alert); return; } content = content || ""; parameters = parameters || {}; var okLabel = parameters.okLabel ? parameters.okLabel : "Ok"; // Backward compatibility parameters = Object.extend(parameters, parameters.windowParameters || {}); parameters.windowParameters = parameters.windowParameters || {}; parameters.className = parameters.className || "alert"; var okButtonClass = "class ='" + (parameters.buttonClass ? parameters.buttonClass + " " : "") + " ok_button'"; /* var content = "\
      " + content + "
      \
      \ \
      "; */ var content = "
      " + content + "
      " + "
      " + "" + "
      "; return this._openDialog(content, parameters); }, info: function(content, parameters) { // Get Ajax return before if (content && typeof content != "string") { Dialog._runAjaxRequest(content, parameters, Dialog.info); return; } content = content || ""; // Backward compatibility parameters = parameters || {}; parameters = Object.extend(parameters, parameters.windowParameters || {}); parameters.windowParameters = parameters.windowParameters || {}; parameters.className = parameters.className || "alert"; var content = ""; if (parameters.showProgress) content += ""; parameters.ok = null; parameters.cancel = null; return this._openDialog(content, parameters); }, setInfoMessage: function(message) { $('modal_dialog_message').update(message); }, closeInfo: function() { Windows.close(this.dialogId); }, _openDialog: function(content, parameters) { var className = parameters.className; if (! parameters.height && ! parameters.width) { parameters.width = WindowUtilities.getPageSize(parameters.options.parent || document.body).pageWidth / 2; } if (parameters.id) this.dialogId = parameters.id; else { var t = new Date(); this.dialogId = 'modal_dialog_' + t.getTime(); parameters.id = this.dialogId; } // compute height or width if need be if (! parameters.height || ! parameters.width) { var size = WindowUtilities._computeSize(content, this.dialogId, parameters.width, parameters.height, 5, className); if (parameters.height) parameters.width = size + 5; else parameters.height = size + 5; } parameters.effectOptions = parameters.effectOptions ; parameters.resizable = parameters.resizable || false; parameters.minimizable = parameters.minimizable || false; parameters.maximizable = parameters.maximizable || false; parameters.draggable = parameters.draggable || false; parameters.closable = parameters.closable || false; var win = new Window(parameters); win.getContent().innerHTML = content; win.showCenter(true, parameters.top, parameters.left); win.setDestroyOnClose(); win.cancelCallback = parameters.onCancel || parameters.cancel; win.okCallback = parameters.onOk || parameters.ok; return win; }, _getAjaxContent: function(originalRequest) { Dialog.callFunc(originalRequest.responseText, Dialog.parameters); }, _runAjaxRequest: function(message, parameters, callFunc) { if (message.options === null) message.options = {}; Dialog.onCompleteFunc = message.options.onComplete; Dialog.parameters = parameters; Dialog.callFunc = callFunc; message.options.onComplete = Dialog._getAjaxContent; new Ajax.Request(message.url, message.options); }, okCallback: function() { var win = Windows.focusedWindow; if (!win.okCallback || win.okCallback(win)) { // Remove onclick on button $$("#" + win.getId()+" input").each(function(element) {element.onclick=null;}); win.close(); } }, cancelCallback: function() { var win = Windows.focusedWindow; // Remove onclick on button $$("#" + win.getId()+" input").each(function(element) {element.onclick=null;}); win.close(); if (win.cancelCallback) win.cancelCallback(win); } }; /* Based on Lightbox JS: Fullsize Image Overlays by Lokesh Dhakar - http://www.huddletogether.com For more information on this script, visit: http://huddletogether.com/projects/lightbox/ Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/ (basically, do anything you want, just leave my name and link) */ if (Prototype.Browser.WebKit) { var array = navigator.userAgent.match(new RegExp(/AppleWebKit\/([\d\.\+]*)/)); Prototype.Browser.WebKitVersion = parseFloat(array[1]); } var WindowUtilities = { // From dragdrop.js getWindowScroll: function(parent) { var T, L, W, H; parent = parent || document.body; if (parent != document.body) { T = parent.scrollTop; L = parent.scrollLeft; W = parent.scrollWidth; H = parent.scrollHeight; } else { var w = window; 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 }; }, // // getPageSize() // Returns array with page width, height and window width, height // Core code from - quirksmode.org // Edit for Firefox by pHaez // getPageSize: function(parent){ parent = parent || document.body; var windowWidth, windowHeight; var pageHeight, pageWidth; if (parent != document.body) { windowWidth = parent.getWidth(); windowHeight = parent.getHeight(); pageWidth = parent.scrollWidth; pageHeight = parent.scrollHeight; } else { var xScroll, yScroll; if (window.innerHeight && window.scrollMaxY) { xScroll = document.body.scrollWidth; yScroll = window.innerHeight + window.scrollMaxY; } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac xScroll = document.body.scrollWidth; yScroll = document.body.scrollHeight; } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari xScroll = document.body.offsetWidth; yScroll = document.body.offsetHeight; } if (self.innerHeight) { // all except Explorer windowWidth = document.documentElement.clientWidth;//self.innerWidth; windowHeight = self.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode windowWidth = document.documentElement.clientWidth; windowHeight = document.documentElement.clientHeight; } else if (document.body) { // other Explorers windowWidth = document.body.clientWidth; windowHeight = document.body.clientHeight; } // for small pages with total height less then height of the viewport if(yScroll < windowHeight){ pageHeight = windowHeight; } else { pageHeight = yScroll; } // for small pages with total width less then width of the viewport if(xScroll < windowWidth){ pageWidth = windowWidth; } else { pageWidth = xScroll; } } return {pageWidth: pageWidth ,pageHeight: pageHeight , windowWidth: windowWidth, windowHeight: windowHeight}; }, disableScreen: function(className, overlayId, overlayOpacity, contentId, parent) { WindowUtilities.initLightbox(overlayId, className, function() { this._disableScreen(className, overlayId, overlayOpacity, contentId); }.bind(this), parent || document.body); }, _disableScreen: function(className, overlayId, overlayOpacity, contentId) { // prep objects var objOverlay = $(overlayId); var pageSize = WindowUtilities.getPageSize(objOverlay.parentNode); // Hide select boxes as they will 'peek' through the image in IE, store old value if (contentId && Prototype.Browser.IE) { WindowUtilities._hideSelect(); WindowUtilities._showSelect(contentId); } // set height of Overlay to take up whole page and show objOverlay.style.height = (pageSize.pageHeight + 'px'); objOverlay.style.display = 'none'; if (overlayId == "overlay_modal" && Window.hasEffectLib && Windows.overlayShowEffectOptions) { objOverlay.overlayOpacity = overlayOpacity; new Effect.Appear(objOverlay, Object.extend({from: 0, to: overlayOpacity}, Windows.overlayShowEffectOptions)); } else objOverlay.style.display = "block"; }, enableScreen: function(id) { id = id || 'overlay_modal'; var objOverlay = $(id); if (objOverlay) { // hide lightbox and overlay if (id == "overlay_modal" && Window.hasEffectLib && Windows.overlayHideEffectOptions) new Effect.Fade(objOverlay, Object.extend({from: objOverlay.overlayOpacity, to:0}, Windows.overlayHideEffectOptions)); else { objOverlay.style.display = 'none'; objOverlay.parentNode.removeChild(objOverlay); } // make select boxes visible using old value if (id != "__invisible__") WindowUtilities._showSelect(); } }, _hideSelect: function(id) { if (Prototype.Browser.IE) { id = id === null ? "" : "#" + id + " "; $$(id + 'select').each(function(element) { if (! WindowUtilities.isDefined(element.oldVisibility)) { element.oldVisibility = element.style.visibility ? element.style.visibility : "visible"; element.style.visibility = "hidden"; } }); } }, _showSelect: function(id) { if (Prototype.Browser.IE) { id = id === null ? "" : "#" + id + " "; $$(id + 'select').each(function(element) { if (WindowUtilities.isDefined(element.oldVisibility)) { // Why?? Ask IE try { element.style.visibility = element.oldVisibility; } catch(e) { element.style.visibility = "visible"; } element.oldVisibility = null; } else { if (element.style.visibility) element.style.visibility = "visible"; } }); } }, isDefined: function(object) { return typeof(object) != "undefined" && object !== null; }, // initLightbox() // Function runs on window load, going through link tags looking for rel="lightbox". // These links receive onclick events that enable the lightbox display for their targets. // The function also inserts html markup at the top of the page which will be used as a // container for the overlay pattern and the inline image. initLightbox: function(id, className, doneHandler, parent) { // Already done, just update zIndex if ($(id)) { Element.setStyle(id, {zIndex: Windows.maxZIndex + 1}); Windows.maxZIndex++; doneHandler(); } // create overlay div and hardcode some functional styles (aesthetic styles are in CSS file) else { var objOverlay = document.createElement("div"); objOverlay.setAttribute('id', id); objOverlay.className = "overlay_" + className; objOverlay.style.display = 'none'; objOverlay.style.position = 'absolute'; objOverlay.style.top = '0'; objOverlay.style.left = '0'; objOverlay.style.zIndex = Windows.maxZIndex + 1; Windows.maxZIndex++; objOverlay.style.width = '100%'; parent.insertBefore(objOverlay, parent.firstChild); if (Prototype.Browser.WebKit && id == "overlay_modal") { setTimeout(function() {doneHandler();}, 10); } else doneHandler(); } }, setCookie: function(value, parameters) { document.cookie= parameters[0] + "=" + escape(value) + ((parameters[1]) ? "; expires=" + parameters[1].toGMTString() : "") + ((parameters[2]) ? "; path=" + parameters[2] : "") + ((parameters[3]) ? "; domain=" + parameters[3] : "") + ((parameters[4]) ? "; secure" : ""); }, getCookie: function(name) { var dc = document.cookie; var prefix = name + "="; var begin = dc.indexOf("; " + prefix); if (begin == -1) { begin = dc.indexOf(prefix); if (begin !== 0) return null; } else { begin += 2; } var end = document.cookie.indexOf(";", begin); if (end == -1) { end = dc.length; } return unescape(dc.substring(begin + prefix.length, end)); }, _computeSize: function(content, id, width, height, margin, className) { var objBody = document.body; var tmpObj = document.createElement("div"); tmpObj.setAttribute('id', id); tmpObj.className = className + "_content"; if (height) tmpObj.style.height = height + "px"; else tmpObj.style.width = width + "px"; tmpObj.style.position = 'absolute'; tmpObj.style.top = '0'; tmpObj.style.left = '0'; tmpObj.style.display = 'none'; tmpObj.innerHTML = content; objBody.insertBefore(tmpObj, objBody.firstChild); var size; if (height) size = $(tmpObj).getDimensions().width + margin; else size = $(tmpObj).getDimensions().height + margin; objBody.removeChild(tmpObj); return size; } }; document.addEventListener("DOMContentLoaded", function () { var iframeLoaded = false; document.querySelectorAll('a[data-target-element="#header-minilogin"]').forEach(function (element) { element.addEventListener('click', function () { if (!iframeLoaded) { // Google iframe var googleContainer = document.getElementById('am-ajax-google-container'); if (googleContainer) { var googleIframe = document.createElement('iframe'); googleIframe.src = googleContainer.getAttribute('data-iframe-src'); googleIframe.width = '236'; googleIframe.height = '40'; googleIframe.scrolling = 'no'; googleIframe.style.border = '0'; googleContainer.appendChild(googleIframe); } // Facebook iframe var facebookContainer = document.getElementById('am-ajax-facebook-container'); if (facebookContainer) { var facebookIframe = document.createElement('iframe'); facebookIframe.src = facebookContainer.getAttribute('data-iframe-src'); facebookIframe.width = '236'; facebookIframe.height = '40'; facebookIframe.scrolling = 'no'; facebookIframe.style.border = '0'; facebookContainer.appendChild(facebookIframe); } // Twitter HTML var twitterContainer = document.getElementById('am-ajax-twitter-container'); if (twitterContainer) { twitterContainer.innerHTML = twitterContainer.getAttribute('data-twitter-html'); } iframeLoaded = true; } }); }); });