/** -- M O O T O O L S C O R E -- **/ /* --- name: Core description: The core of MooTools, contains all the base functions and the Native and Hash implementations. Required by all the other scripts. license: MIT-style license. copyright: Copyright (c) 2006-2008 [Valerio Proietti](http://mad4milk.net/). authors: The MooTools production team (http://mootools.net/developers/) inspiration: - Class implementation inspired by [Base.js](http://dean.edwards.name/weblog/2006/03/base/) Copyright (c) 2006 Dean Edwards, [GNU Lesser General Public License](http://opensource.org/licenses/lgpl-license.php) - Some functionality inspired by [Prototype.js](http://prototypejs.org) Copyright (c) 2005-2007 Sam Stephenson, [MIT License](http://opensource.org/licenses/mit-license.php) provides: [MooTools, Native, Hash.base, Array.each, $util] ... */ var MooTools = { 'version': '1.2.5', 'build': '008d8f0f2fcc2044e54fdd3635341aaab274e757' }; var Native = function(options){ options = options || {}; var name = options.name; var legacy = options.legacy; var protect = options.protect; var methods = options.implement; var generics = options.generics; var initialize = options.initialize; var afterImplement = options.afterImplement || function(){}; var object = initialize || legacy; generics = generics !== false; object.constructor = Native; object.$family = {name: 'native'}; if (legacy && initialize) object.prototype = legacy.prototype; object.prototype.constructor = object; if (name){ var family = name.toLowerCase(); object.prototype.$family = {name: family}; Native.typize(object, family); } var add = function(obj, name, method, force){ if (!protect || force || !obj.prototype[name]) obj.prototype[name] = method; if (generics) Native.genericize(obj, name, protect); afterImplement.call(obj, name, method); return obj; }; object.alias = function(a1, a2, a3){ if (typeof a1 == 'string'){ var pa1 = this.prototype[a1]; if ((a1 = pa1)) return add(this, a2, a1, a3); } for (var a in a1) this.alias(a, a1[a], a2); return this; }; object.implement = function(a1, a2, a3){ if (typeof a1 == 'string') return add(this, a1, a2, a3); for (var p in a1) add(this, p, a1[p], a2); return this; }; if (methods) object.implement(methods); return object; }; Native.genericize = function(object, property, check){ if ((!check || !object[property]) && typeof object.prototype[property] == 'function') object[property] = function(){ var args = Array.prototype.slice.call(arguments); return object.prototype[property].apply(args.shift(), args); }; }; Native.implement = function(objects, properties){ for (var i = 0, l = objects.length; i < l; i++) objects[i].implement(properties); }; Native.typize = function(object, family){ if (!object.type) object.type = function(item){ return ($type(item) === family); }; }; (function(){ var natives = {'Array': Array, 'Date': Date, 'Function': Function, 'Number': Number, 'RegExp': RegExp, 'String': String}; for (var n in natives) new Native({name: n, initialize: natives[n], protect: true}); var types = {'boolean': Boolean, 'native': Native, 'object': Object}; for (var t in types) Native.typize(types[t], t); var generics = { 'Array': ["concat", "indexOf", "join", "lastIndexOf", "pop", "push", "reverse", "shift", "slice", "sort", "splice", "toString", "unshift", "valueOf"], 'String': ["charAt", "charCodeAt", "concat", "indexOf", "lastIndexOf", "match", "replace", "search", "slice", "split", "substr", "substring", "toLowerCase", "toUpperCase", "valueOf"] }; for (var g in generics){ for (var i = generics[g].length; i--;) Native.genericize(natives[g], generics[g][i], true); } })(); var Hash = new Native({ name: 'Hash', initialize: function(object){ if ($type(object) == 'hash') object = $unlink(object.getClean()); for (var key in object) this[key] = object[key]; return this; } }); Hash.implement({ forEach: function(fn, bind){ for (var key in this){ if (this.hasOwnProperty(key)) fn.call(bind, this[key], key, this); } }, getClean: function(){ var clean = {}; for (var key in this){ if (this.hasOwnProperty(key)) clean[key] = this[key]; } return clean; }, getLength: function(){ var length = 0; for (var key in this){ if (this.hasOwnProperty(key)) length++; } return length; } }); Hash.alias('forEach', 'each'); Array.implement({ forEach: function(fn, bind){ for (var i = 0, l = this.length; i < l; i++) fn.call(bind, this[i], i, this); } }); Array.alias('forEach', 'each'); function $A(iterable){ if (iterable.item){ var l = iterable.length, array = new Array(l); while (l--) array[l] = iterable[l]; return array; } return Array.prototype.slice.call(iterable); }; function $arguments(i){ return function(){ return arguments[i]; }; }; function $chk(obj){ return !!(obj || obj === 0); }; function $clear(timer){ clearTimeout(timer); clearInterval(timer); return null; }; function $defined(obj){ return (obj != undefined); }; function $each(iterable, fn, bind){ var type = $type(iterable); ((type == 'arguments' || type == 'collection' || type == 'array') ? Array : Hash).each(iterable, fn, bind); }; function $empty(){}; function $extend(original, extended){ for (var key in (extended || {})) original[key] = extended[key]; return original; }; function $H(object){ return new Hash(object); }; function $lambda(value){ return ($type(value) == 'function') ? value : function(){ return value; }; }; function $merge(){ var args = Array.slice(arguments); args.unshift({}); return $mixin.apply(null, args); }; function $mixin(mix){ for (var i = 1, l = arguments.length; i < l; i++){ var object = arguments[i]; if ($type(object) != 'object') continue; for (var key in object){ var op = object[key], mp = mix[key]; mix[key] = (mp && $type(op) == 'object' && $type(mp) == 'object') ? $mixin(mp, op) : $unlink(op); } } return mix; }; function $pick(){ for (var i = 0, l = arguments.length; i < l; i++){ if (arguments[i] != undefined) return arguments[i]; } return null; }; function $random(min, max){ return Math.floor(Math.random() * (max - min + 1) + min); }; function $splat(obj){ var type = $type(obj); return (type) ? ((type != 'array' && type != 'arguments') ? [obj] : obj) : []; }; var $time = Date.now || function(){ return +new Date; }; function $try(){ for (var i = 0, l = arguments.length; i < l; i++){ try { return arguments[i](); } catch(e){} } return null; }; function $type(obj){ if (obj == undefined) return false; if (obj.$family) return (obj.$family.name == 'number' && !isFinite(obj)) ? false : obj.$family.name; if (obj.nodeName){ switch (obj.nodeType){ case 1: return 'element'; case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace'; } } else if (typeof obj.length == 'number'){ if (obj.callee) return 'arguments'; else if (obj.item) return 'collection'; } return typeof obj; }; function $unlink(object){ var unlinked; switch ($type(object)){ case 'object': unlinked = {}; for (var p in object) unlinked[p] = $unlink(object[p]); break; case 'hash': unlinked = new Hash(object); break; case 'array': unlinked = []; for (var i = 0, l = object.length; i < l; i++) unlinked[i] = $unlink(object[i]); break; default: return object; } return unlinked; }; /* --- name: Array description: Contains Array Prototypes like each, contains, and erase. license: MIT-style license. requires: [$util, Array.each] provides: Array ... */ Array.implement({ every: function(fn, bind){ for (var i = 0, l = this.length; i < l; i++){ if (!fn.call(bind, this[i], i, this)) return false; } return true; }, filter: function(fn, bind){ var results = []; for (var i = 0, l = this.length; i < l; i++){ if (fn.call(bind, this[i], i, this)) results.push(this[i]); } return results; }, clean: function(){ return this.filter($defined); }, indexOf: function(item, from){ var len = this.length; for (var i = (from < 0) ? Math.max(0, len + from) : from || 0; i < len; i++){ if (this[i] === item) return i; } return -1; }, map: function(fn, bind){ var results = []; for (var i = 0, l = this.length; i < l; i++) results[i] = fn.call(bind, this[i], i, this); return results; }, some: function(fn, bind){ for (var i = 0, l = this.length; i < l; i++){ if (fn.call(bind, this[i], i, this)) return true; } return false; }, associate: function(keys){ var obj = {}, length = Math.min(this.length, keys.length); for (var i = 0; i < length; i++) obj[keys[i]] = this[i]; return obj; }, link: function(object){ var result = {}; for (var i = 0, l = this.length; i < l; i++){ for (var key in object){ if (object[key](this[i])){ result[key] = this[i]; delete object[key]; break; } } } return result; }, contains: function(item, from){ return this.indexOf(item, from) != -1; }, extend: function(array){ for (var i = 0, j = array.length; i < j; i++) this.push(array[i]); return this; }, getLast: function(){ return (this.length) ? this[this.length - 1] : null; }, getRandom: function(){ return (this.length) ? this[$random(0, this.length - 1)] : null; }, include: function(item){ if (!this.contains(item)) this.push(item); return this; }, combine: function(array){ for (var i = 0, l = array.length; i < l; i++) this.include(array[i]); return this; }, erase: function(item){ for (var i = this.length; i--; i){ if (this[i] === item) this.splice(i, 1); } return this; }, empty: function(){ this.length = 0; return this; }, flatten: function(){ var array = []; for (var i = 0, l = this.length; i < l; i++){ var type = $type(this[i]); if (!type) continue; array = array.concat((type == 'array' || type == 'collection' || type == 'arguments') ? Array.flatten(this[i]) : this[i]); } return array; }, hexToRgb: function(array){ if (this.length != 3) return null; var rgb = this.map(function(value){ if (value.length == 1) value += value; return value.toInt(16); }); return (array) ? rgb : 'rgb(' + rgb + ')'; }, rgbToHex: function(array){ if (this.length < 3) return null; if (this.length == 4 && this[3] == 0 && !array) return 'transparent'; var hex = []; for (var i = 0; i < 3; i++){ var bit = (this[i] - 0).toString(16); hex.push((bit.length == 1) ? '0' + bit : bit); } return (array) ? hex : '#' + hex.join(''); } }); /* --- name: String description: Contains String Prototypes like camelCase, capitalize, test, and toInt. license: MIT-style license. requires: Native provides: String ... */ String.implement({ test: function(regex, params){ return ((typeof regex == 'string') ? new RegExp(regex, params) : regex).test(this); }, contains: function(string, separator){ return (separator) ? (separator + this + separator).indexOf(separator + string + separator) > -1 : this.indexOf(string) > -1; }, trim: function(){ return this.replace(/^\s+|\s+$/g, ''); }, clean: function(){ return this.replace(/\s+/g, ' ').trim(); }, camelCase: function(){ return this.replace(/-\D/g, function(match){ return match.charAt(1).toUpperCase(); }); }, hyphenate: function(){ return this.replace(/[A-Z]/g, function(match){ return ('-' + match.charAt(0).toLowerCase()); }); }, capitalize: function(){ return this.replace(/\b[a-z]/g, function(match){ return match.toUpperCase(); }); }, escapeRegExp: function(){ return this.replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1'); }, toInt: function(base){ return parseInt(this, base || 10); }, toFloat: function(){ return parseFloat(this); }, hexToRgb: function(array){ var hex = this.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/); return (hex) ? hex.slice(1).hexToRgb(array) : null; }, rgbToHex: function(array){ var rgb = this.match(/\d{1,3}/g); return (rgb) ? rgb.rgbToHex(array) : null; }, stripScripts: function(option){ var scripts = ''; var text = this.replace(/]*>([\s\S]*?)<\/script>/gi, function(){ scripts += arguments[1] + '\n'; return ''; }); if (option === true) $exec(scripts); else if ($type(option) == 'function') option(scripts, text); return text; }, substitute: function(object, regexp){ return this.replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name){ if (match.charAt(0) == '\\') return match.slice(1); return (object[name] != undefined) ? object[name] : ''; }); } }); /* --- name: Function description: Contains Function Prototypes like create, bind, pass, and delay. license: MIT-style license. requires: [Native, $util] provides: Function ... */ try { delete Function.prototype.bind; } catch(e){} Function.implement({ extend: function(properties){ for (var property in properties) this[property] = properties[property]; return this; }, create: function(options){ var self = this; options = options || {}; return function(event){ var args = options.arguments; args = (args != undefined) ? $splat(args) : Array.slice(arguments, (options.event) ? 1 : 0); if (options.event) args = [event || window.event].extend(args); var returns = function(){ return self.apply(options.bind || null, args); }; if (options.delay) return setTimeout(returns, options.delay); if (options.periodical) return setInterval(returns, options.periodical); if (options.attempt) return $try(returns); return returns(); }; }, run: function(args, bind){ return this.apply(bind, $splat(args)); }, pass: function(args, bind){ return this.create({bind: bind, arguments: args}); }, bind: function(bind, args){ return this.create({bind: bind, arguments: args}); }, bindWithEvent: function(bind, args){ return this.create({bind: bind, arguments: args, event: true}); }, attempt: function(args, bind){ return this.create({bind: bind, arguments: args, attempt: true})(); }, delay: function(delay, bind, args){ return this.create({bind: bind, arguments: args, delay: delay})(); }, periodical: function(periodical, bind, args){ return this.create({bind: bind, arguments: args, periodical: periodical})(); } }); /* --- name: Number description: Contains Number Prototypes like limit, round, times, and ceil. license: MIT-style license. requires: [Native, $util] provides: Number ... */ Number.implement({ limit: function(min, max){ return Math.min(max, Math.max(min, this)); }, round: function(precision){ precision = Math.pow(10, precision || 0); return Math.round(this * precision) / precision; }, times: function(fn, bind){ for (var i = 0; i < this; i++) fn.call(bind, i, this); }, toFloat: function(){ return parseFloat(this); }, toInt: function(base){ return parseInt(this, base || 10); } }); Number.alias('times', 'each'); (function(math){ var methods = {}; math.each(function(name){ if (!Number[name]) methods[name] = function(){ return Math[name].apply(null, [this].concat($A(arguments))); }; }); Number.implement(methods); })(['abs', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'exp', 'floor', 'log', 'max', 'min', 'pow', 'sin', 'sqrt', 'tan']); /* --- name: Hash description: Contains Hash Prototypes. Provides a means for overcoming the JavaScript practical impossibility of extending native Objects. license: MIT-style license. requires: Hash.base provides: Hash ... */ Hash.implement({ has: Object.prototype.hasOwnProperty, keyOf: function(value){ for (var key in this){ if (this.hasOwnProperty(key) && this[key] === value) return key; } return null; }, hasValue: function(value){ return (Hash.keyOf(this, value) !== null); }, extend: function(properties){ Hash.each(properties || {}, function(value, key){ Hash.set(this, key, value); }, this); return this; }, combine: function(properties){ Hash.each(properties || {}, function(value, key){ Hash.include(this, key, value); }, this); return this; }, erase: function(key){ if (this.hasOwnProperty(key)) delete this[key]; return this; }, get: function(key){ return (this.hasOwnProperty(key)) ? this[key] : null; }, set: function(key, value){ if (!this[key] || this.hasOwnProperty(key)) this[key] = value; return this; }, empty: function(){ Hash.each(this, function(value, key){ delete this[key]; }, this); return this; }, include: function(key, value){ if (this[key] == undefined) this[key] = value; return this; }, map: function(fn, bind){ var results = new Hash; Hash.each(this, function(value, key){ results.set(key, fn.call(bind, value, key, this)); }, this); return results; }, filter: function(fn, bind){ var results = new Hash; Hash.each(this, function(value, key){ if (fn.call(bind, value, key, this)) results.set(key, value); }, this); return results; }, every: function(fn, bind){ for (var key in this){ if (this.hasOwnProperty(key) && !fn.call(bind, this[key], key)) return false; } return true; }, some: function(fn, bind){ for (var key in this){ if (this.hasOwnProperty(key) && fn.call(bind, this[key], key)) return true; } return false; }, getKeys: function(){ var keys = []; Hash.each(this, function(value, key){ keys.push(key); }); return keys; }, getValues: function(){ var values = []; Hash.each(this, function(value){ values.push(value); }); return values; }, toQueryString: function(base){ var queryString = []; Hash.each(this, function(value, key){ if (base) key = base + '[' + key + ']'; var result; switch ($type(value)){ case 'object': result = Hash.toQueryString(value, key); break; case 'array': var qs = {}; value.each(function(val, i){ qs[i] = val; }); result = Hash.toQueryString(qs, key); break; default: result = key + '=' + encodeURIComponent(value); } if (value != undefined) queryString.push(result); }); return queryString.join('&'); } }); Hash.alias({keyOf: 'indexOf', hasValue: 'contains'}); /* --- name: Class description: Contains the Class Function for easily creating, extending, and implementing reusable Classes. license: MIT-style license. requires: [$util, Native, Array, String, Function, Number, Hash] provides: Class ... */ function Class(params){ if (params instanceof Function) params = {initialize: params}; var newClass = function(){ Object.reset(this); if (newClass._prototyping) return this; this._current = $empty; var value = (this.initialize) ? this.initialize.apply(this, arguments) : this; delete this._current; delete this.caller; return value; }.extend(this); newClass.implement(params); newClass.constructor = Class; newClass.prototype.constructor = newClass; return newClass; }; Function.prototype.protect = function(){ this._protected = true; return this; }; Object.reset = function(object, key){ if (key == null){ for (var p in object) Object.reset(object, p); return object; } delete object[key]; switch ($type(object[key])){ case 'object': var F = function(){}; F.prototype = object[key]; var i = new F; object[key] = Object.reset(i); break; case 'array': object[key] = $unlink(object[key]); break; } return object; }; new Native({name: 'Class', initialize: Class}).extend({ instantiate: function(F){ F._prototyping = true; var proto = new F; delete F._prototyping; return proto; }, wrap: function(self, key, method){ if (method._origin) method = method._origin; return function(){ if (method._protected && this._current == null) throw new Error('The method "' + key + '" cannot be called.'); var caller = this.caller, current = this._current; this.caller = current; this._current = arguments.callee; var result = method.apply(this, arguments); this._current = current; this.caller = caller; return result; }.extend({_owner: self, _origin: method, _name: key}); } }); Class.implement({ implement: function(key, value){ if ($type(key) == 'object'){ for (var p in key) this.implement(p, key[p]); return this; } var mutator = Class.Mutators[key]; if (mutator){ value = mutator.call(this, value); if (value == null) return this; } var proto = this.prototype; switch ($type(value)){ case 'function': if (value._hidden) return this; proto[key] = Class.wrap(this, key, value); break; case 'object': var previous = proto[key]; if ($type(previous) == 'object') $mixin(previous, value); else proto[key] = $unlink(value); break; case 'array': proto[key] = $unlink(value); break; default: proto[key] = value; } return this; } }); Class.Mutators = { Extends: function(parent){ this.parent = parent; this.prototype = Class.instantiate(parent); this.implement('parent', function(){ var name = this.caller._name, previous = this.caller._owner.parent.prototype[name]; if (!previous) throw new Error('The method "' + name + '" has no parent.'); return previous.apply(this, arguments); }.protect()); }, Implements: function(items){ $splat(items).each(function(item){ if (item instanceof Function) item = Class.instantiate(item); this.implement(item); }, this); } }; /* --- name: Class.Extras description: Contains Utility Classes that can be implemented into your own Classes to ease the execution of many common tasks. license: MIT-style license. requires: Class provides: [Chain, Events, Options, Class.Extras] ... */ var Chain = new Class({ $chain: [], chain: function(){ this.$chain.extend(Array.flatten(arguments)); return this; }, callChain: function(){ return (this.$chain.length) ? this.$chain.shift().apply(this, arguments) : false; }, clearChain: function(){ this.$chain.empty(); return this; } }); var Events = new Class({ $events: {}, addEvent: function(type, fn, internal){ type = Events.removeOn(type); if (fn != $empty){ this.$events[type] = this.$events[type] || []; this.$events[type].include(fn); if (internal) fn.internal = true; } return this; }, addEvents: function(events){ for (var type in events) this.addEvent(type, events[type]); return this; }, fireEvent: function(type, args, delay){ type = Events.removeOn(type); if (!this.$events || !this.$events[type]) return this; this.$events[type].each(function(fn){ fn.create({'bind': this, 'delay': delay, 'arguments': args})(); }, this); return this; }, removeEvent: function(type, fn){ type = Events.removeOn(type); if (!this.$events[type]) return this; if (!fn.internal) this.$events[type].erase(fn); return this; }, removeEvents: function(events){ var type; if ($type(events) == 'object'){ for (type in events) this.removeEvent(type, events[type]); return this; } if (events) events = Events.removeOn(events); for (type in this.$events){ if (events && events != type) continue; var fns = this.$events[type]; for (var i = fns.length; i--; i) this.removeEvent(type, fns[i]); } return this; } }); Events.removeOn = function(string){ return string.replace(/^on([A-Z])/, function(full, first){ return first.toLowerCase(); }); }; var Options = new Class({ setOptions: function(){ this.options = $merge.run([this.options].extend(arguments)); if (!this.addEvent) return this; for (var option in this.options){ if ($type(this.options[option]) != 'function' || !(/^on[A-Z]/).test(option)) continue; this.addEvent(option, this.options[option]); delete this.options[option]; } return this; } }); /* --- name: Browser description: The Browser Core. Contains Browser initialization, Window and Document, and the Browser Hash. license: MIT-style license. requires: [Native, $util] provides: [Browser, Window, Document, $exec] ... */ var Browser = $merge({ Engine: {name: 'unknown', version: 0}, Platform: {name: (window.orientation != undefined) ? 'ipod' : (navigator.platform.match(/mac|win|linux/i) || ['other'])[0].toLowerCase()}, Features: {xpath: !!(document.evaluate), air: !!(window.runtime), query: !!(document.querySelector)}, Plugins: {}, Engines: { presto: function(){ return (!window.opera) ? false : ((arguments.callee.caller) ? 960 : ((document.getElementsByClassName) ? 950 : 925)); }, trident: function(){ return (!window.ActiveXObject) ? false : ((window.XMLHttpRequest) ? ((document.querySelectorAll) ? 6 : 5) : 4); }, webkit: function(){ return (navigator.taintEnabled) ? false : ((Browser.Features.xpath) ? ((Browser.Features.query) ? 525 : 420) : 419); }, gecko: function(){ return (!document.getBoxObjectFor && window.mozInnerScreenX == null) ? false : ((document.getElementsByClassName) ? 19 : 18); } } }, Browser || {}); Browser.Platform[Browser.Platform.name] = true; Browser.detect = function(){ for (var engine in this.Engines){ var version = this.Engines[engine](); if (version){ this.Engine = {name: engine, version: version}; this.Engine[engine] = this.Engine[engine + version] = true; break; } } return {name: engine, version: version}; }; Browser.detect(); Browser.Request = function(){ return $try(function(){ return new XMLHttpRequest(); }, function(){ return new ActiveXObject('MSXML2.XMLHTTP'); }, function(){ return new ActiveXObject('Microsoft.XMLHTTP'); }); }; Browser.Features.xhr = !!(Browser.Request()); Browser.Plugins.Flash = (function(){ var version = ($try(function(){ return navigator.plugins['Shockwave Flash'].description; }, function(){ return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version'); }) || '0 r0').match(/\d+/g); return {version: parseInt(version[0] || 0 + '.' + version[1], 10) || 0, build: parseInt(version[2], 10) || 0}; })(); function $exec(text){ if (!text) return text; if (window.execScript){ window.execScript(text); } else { var script = document.createElement('script'); script.setAttribute('type', 'text/javascript'); script[(Browser.Engine.webkit && Browser.Engine.version < 420) ? 'innerText' : 'text'] = text; document.head.appendChild(script); document.head.removeChild(script); } return text; }; Native.UID = 1; var $uid = (Browser.Engine.trident) ? function(item){ return (item.uid || (item.uid = [Native.UID++]))[0]; } : function(item){ return item.uid || (item.uid = Native.UID++); }; var Window = new Native({ name: 'Window', legacy: (Browser.Engine.trident) ? null: window.Window, initialize: function(win){ $uid(win); if (!win.Element){ win.Element = $empty; if (Browser.Engine.webkit) win.document.createElement("iframe"); //fixes safari 2 win.Element.prototype = (Browser.Engine.webkit) ? window["[[DOMElement.prototype]]"] : {}; } win.document.window = win; return $extend(win, Window.Prototype); }, afterImplement: function(property, value){ window[property] = Window.Prototype[property] = value; } }); Window.Prototype = {$family: {name: 'window'}}; new Window(window); var Document = new Native({ name: 'Document', legacy: (Browser.Engine.trident) ? null: window.Document, initialize: function(doc){ $uid(doc); doc.head = doc.getElementsByTagName('head')[0]; doc.html = doc.getElementsByTagName('html')[0]; if (Browser.Engine.trident && Browser.Engine.version <= 4) $try(function(){ doc.execCommand("BackgroundImageCache", false, true); }); if (Browser.Engine.trident) doc.window.attachEvent('onunload', function(){ doc.window.detachEvent('onunload', arguments.callee); doc.head = doc.html = doc.window = null; }); return $extend(doc, Document.Prototype); }, afterImplement: function(property, value){ document[property] = Document.Prototype[property] = value; } }); Document.Prototype = {$family: {name: 'document'}}; new Document(document); /* --- name: Element description: One of the most important items in MooTools. Contains the dollar function, the dollars function, and an handful of cross-browser, time-saver methods to let you easily work with HTML Elements. license: MIT-style license. requires: [Window, Document, Array, String, Function, Number, Hash] provides: [Element, Elements, $, $$, Iframe] ... */ var Element = new Native({ name: 'Element', legacy: window.Element, initialize: function(tag, props){ var konstructor = Element.Constructors.get(tag); if (konstructor) return konstructor(props); if (typeof tag == 'string') return document.newElement(tag, props); return document.id(tag).set(props); }, afterImplement: function(key, value){ Element.Prototype[key] = value; if (Array[key]) return; Elements.implement(key, function(){ var items = [], elements = true; for (var i = 0, j = this.length; i < j; i++){ var returns = this[i][key].apply(this[i], arguments); items.push(returns); if (elements) elements = ($type(returns) == 'element'); } return (elements) ? new Elements(items) : items; }); } }); Element.Prototype = {$family: {name: 'element'}}; Element.Constructors = new Hash; var IFrame = new Native({ name: 'IFrame', generics: false, initialize: function(){ var params = Array.link(arguments, {properties: Object.type, iframe: $defined}); var props = params.properties || {}; var iframe = document.id(params.iframe); var onload = props.onload || $empty; delete props.onload; props.id = props.name = $pick(props.id, props.name, iframe ? (iframe.id || iframe.name) : 'IFrame_' + $time()); iframe = new Element(iframe || 'iframe', props); var onFrameLoad = function(){ var host = $try(function(){ return iframe.contentWindow.location.host; }); if (!host || host == window.location.host){ var win = new Window(iframe.contentWindow); new Document(iframe.contentWindow.document); $extend(win.Element.prototype, Element.Prototype); } onload.call(iframe.contentWindow, iframe.contentWindow.document); }; var contentWindow = $try(function(){ return iframe.contentWindow; }); ((contentWindow && contentWindow.document.body) || window.frames[props.id]) ? onFrameLoad() : iframe.addListener('load', onFrameLoad); return iframe; } }); var Elements = new Native({ initialize: function(elements, options){ options = $extend({ddup: true, cash: true}, options); elements = elements || []; if (options.ddup || options.cash){ var uniques = {}, returned = []; for (var i = 0, l = elements.length; i < l; i++){ var el = document.id(elements[i], !options.cash); if (options.ddup){ if (uniques[el.uid]) continue; uniques[el.uid] = true; } if (el) returned.push(el); } elements = returned; } return (options.cash) ? $extend(elements, this) : elements; } }); Elements.implement({ filter: function(filter, bind){ if (!filter) return this; return new Elements(Array.filter(this, (typeof filter == 'string') ? function(item){ return item.match(filter); } : filter, bind)); } }); (function(){ /**/ var createElementAcceptsHTML; try { var x = document.createElement(''); createElementAcceptsHTML = (x.name == 'x'); } catch(e){} var escapeQuotes = function(html){ return ('' + html).replace(/&/g,'&').replace(/"/g,'"'); }; /**/ Document.implement({ newElement: function(tag, props){ if (props && props.checked != null) props.defaultChecked = props.checked; /**/// Fix for readonly name and type properties in IE < 8 if (createElementAcceptsHTML && props){ tag = '<' + tag; if (props.name) tag += ' name="' + escapeQuotes(props.name) + '"'; if (props.type) tag += ' type="' + escapeQuotes(props.type) + '"'; tag += '>'; delete props.name; delete props.type; } /**/ return this.id(this.createElement(tag)).set(props); }, newTextNode: function(text){ return this.createTextNode(text); }, getDocument: function(){ return this; }, getWindow: function(){ return this.window; }, id: (function(){ var types = { string: function(id, nocash, doc){ id = doc.getElementById(id); return (id) ? types.element(id, nocash) : null; }, element: function(el, nocash){ $uid(el); if (!nocash && !el.$family && !(/^object|embed$/i).test(el.tagName)){ var proto = Element.Prototype; for (var p in proto) el[p] = proto[p]; }; return el; }, object: function(obj, nocash, doc){ if (obj.toElement) return types.element(obj.toElement(doc), nocash); return null; } }; types.textnode = types.whitespace = types.window = types.document = $arguments(0); return function(el, nocash, doc){ if (el && el.$family && el.uid) return el; var type = $type(el); return (types[type]) ? types[type](el, nocash, doc || document) : null; }; })() }); })(); if (window.$ == null) Window.implement({ $: function(el, nc){ return document.id(el, nc, this.document); } }); Window.implement({ $$: function(selector){ if (arguments.length == 1 && typeof selector == 'string') return this.document.getElements(selector); var elements = []; var args = Array.flatten(arguments); for (var i = 0, l = args.length; i < l; i++){ var item = args[i]; switch ($type(item)){ case 'element': elements.push(item); break; case 'string': elements.extend(this.document.getElements(item, true)); } } return new Elements(elements); }, getDocument: function(){ return this.document; }, getWindow: function(){ return this; } }); Native.implement([Element, Document], { getElement: function(selector, nocash){ return document.id(this.getElements(selector, true)[0] || null, nocash); }, getElements: function(tags, nocash){ tags = tags.split(','); var elements = []; var ddup = (tags.length > 1); tags.each(function(tag){ var partial = this.getElementsByTagName(tag.trim()); (ddup) ? elements.extend(partial) : elements = partial; }, this); return new Elements(elements, {ddup: ddup, cash: !nocash}); } }); (function(){ var collected = {}, storage = {}; var props = {input: 'checked', option: 'selected', textarea: (Browser.Engine.webkit && Browser.Engine.version < 420) ? 'innerHTML' : 'value'}; var get = function(uid){ return (storage[uid] || (storage[uid] = {})); }; var clean = function(item, retain){ if (!item) return; var uid = item.uid; if (retain !== true) retain = false; if (Browser.Engine.trident){ if (item.clearAttributes){ var clone = retain && item.cloneNode(false); item.clearAttributes(); if (clone) item.mergeAttributes(clone); } else if (item.removeEvents){ item.removeEvents(); } if ((/object/i).test(item.tagName)){ for (var p in item){ if (typeof item[p] == 'function') item[p] = $empty; } Element.dispose(item); } } if (!uid) return; collected[uid] = storage[uid] = null; }; var purge = function(){ Hash.each(collected, clean); if (Browser.Engine.trident) $A(document.getElementsByTagName('object')).each(clean); if (window.CollectGarbage) CollectGarbage(); collected = storage = null; }; var walk = function(element, walk, start, match, all, nocash){ var el = element[start || walk]; var elements = []; while (el){ if (el.nodeType == 1 && (!match || Element.match(el, match))){ if (!all) return document.id(el, nocash); elements.push(el); } el = el[walk]; } return (all) ? new Elements(elements, {ddup: false, cash: !nocash}) : null; }; var attributes = { 'html': 'innerHTML', 'class': 'className', 'for': 'htmlFor', 'defaultValue': 'defaultValue', 'text': (Browser.Engine.trident || (Browser.Engine.webkit && Browser.Engine.version < 420)) ? 'innerText' : 'textContent' }; var bools = ['compact', 'nowrap', 'ismap', 'declare', 'noshade', 'checked', 'disabled', 'readonly', 'multiple', 'selected', 'noresize', 'defer']; var camels = ['value', 'type', 'defaultValue', 'accessKey', 'cellPadding', 'cellSpacing', 'colSpan', 'frameBorder', 'maxLength', 'readOnly', 'rowSpan', 'tabIndex', 'useMap']; bools = bools.associate(bools); Hash.extend(attributes, bools); Hash.extend(attributes, camels.associate(camels.map(String.toLowerCase))); var inserters = { before: function(context, element){ if (element.parentNode) element.parentNode.insertBefore(context, element); }, after: function(context, element){ if (!element.parentNode) return; var next = element.nextSibling; (next) ? element.parentNode.insertBefore(context, next) : element.parentNode.appendChild(context); }, bottom: function(context, element){ element.appendChild(context); }, top: function(context, element){ var first = element.firstChild; (first) ? element.insertBefore(context, first) : element.appendChild(context); } }; inserters.inside = inserters.bottom; Hash.each(inserters, function(inserter, where){ where = where.capitalize(); Element.implement('inject' + where, function(el){ inserter(this, document.id(el, true)); return this; }); Element.implement('grab' + where, function(el){ inserter(document.id(el, true), this); return this; }); }); Element.implement({ set: function(prop, value){ switch ($type(prop)){ case 'object': for (var p in prop) this.set(p, prop[p]); break; case 'string': var property = Element.Properties.get(prop); (property && property.set) ? property.set.apply(this, Array.slice(arguments, 1)) : this.setProperty(prop, value); } return this; }, get: function(prop){ var property = Element.Properties.get(prop); return (property && property.get) ? property.get.apply(this, Array.slice(arguments, 1)) : this.getProperty(prop); }, erase: function(prop){ var property = Element.Properties.get(prop); (property && property.erase) ? property.erase.apply(this) : this.removeProperty(prop); return this; }, setProperty: function(attribute, value){ var key = attributes[attribute]; if (value == undefined) return this.removeProperty(attribute); if (key && bools[attribute]) value = !!value; (key) ? this[key] = value : this.setAttribute(attribute, '' + value); return this; }, setProperties: function(attributes){ for (var attribute in attributes) this.setProperty(attribute, attributes[attribute]); return this; }, getProperty: function(attribute){ var key = attributes[attribute]; var value = (key) ? this[key] : this.getAttribute(attribute, 2); return (bools[attribute]) ? !!value : (key) ? value : value || null; }, getProperties: function(){ var args = $A(arguments); return args.map(this.getProperty, this).associate(args); }, removeProperty: function(attribute){ var key = attributes[attribute]; (key) ? this[key] = (key && bools[attribute]) ? false : '' : this.removeAttribute(attribute); return this; }, removeProperties: function(){ Array.each(arguments, this.removeProperty, this); return this; }, hasClass: function(className){ return this.className.contains(className, ' '); }, addClass: function(className){ if (!this.hasClass(className)) this.className = (this.className + ' ' + className).clean(); return this; }, removeClass: function(className){ this.className = this.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)'), '$1'); return this; }, toggleClass: function(className){ return this.hasClass(className) ? this.removeClass(className) : this.addClass(className); }, adopt: function(){ Array.flatten(arguments).each(function(element){ element = document.id(element, true); if (element) this.appendChild(element); }, this); return this; }, appendText: function(text, where){ return this.grab(this.getDocument().newTextNode(text), where); }, grab: function(el, where){ inserters[where || 'bottom'](document.id(el, true), this); return this; }, inject: function(el, where){ inserters[where || 'bottom'](this, document.id(el, true)); return this; }, replaces: function(el){ el = document.id(el, true); el.parentNode.replaceChild(this, el); return this; }, wraps: function(el, where){ el = document.id(el, true); return this.replaces(el).grab(el, where); }, getPrevious: function(match, nocash){ return walk(this, 'previousSibling', null, match, false, nocash); }, getAllPrevious: function(match, nocash){ return walk(this, 'previousSibling', null, match, true, nocash); }, getNext: function(match, nocash){ return walk(this, 'nextSibling', null, match, false, nocash); }, getAllNext: function(match, nocash){ return walk(this, 'nextSibling', null, match, true, nocash); }, getFirst: function(match, nocash){ return walk(this, 'nextSibling', 'firstChild', match, false, nocash); }, getLast: function(match, nocash){ return walk(this, 'previousSibling', 'lastChild', match, false, nocash); }, getParent: function(match, nocash){ return walk(this, 'parentNode', null, match, false, nocash); }, getParents: function(match, nocash){ return walk(this, 'parentNode', null, match, true, nocash); }, getSiblings: function(match, nocash){ return this.getParent().getChildren(match, nocash).erase(this); }, getChildren: function(match, nocash){ return walk(this, 'nextSibling', 'firstChild', match, true, nocash); }, getWindow: function(){ return this.ownerDocument.window; }, getDocument: function(){ return this.ownerDocument; }, getElementById: function(id, nocash){ var el = this.ownerDocument.getElementById(id); if (!el) return null; for (var parent = el.parentNode; parent != this; parent = parent.parentNode){ if (!parent) return null; } return document.id(el, nocash); }, getSelected: function(){ return new Elements($A(this.options).filter(function(option){ return option.selected; })); }, getComputedStyle: function(property){ if (this.currentStyle) return this.currentStyle[property.camelCase()]; var computed = this.getDocument().defaultView.getComputedStyle(this, null); return (computed) ? computed.getPropertyValue([property.hyphenate()]) : null; }, toQueryString: function(){ var queryString = []; this.getElements('input, select, textarea', true).each(function(el){ if (!el.name || el.disabled || el.type == 'submit' || el.type == 'reset' || el.type == 'file') return; var value = (el.tagName.toLowerCase() == 'select') ? Element.getSelected(el).map(function(opt){ return opt.value; }) : ((el.type == 'radio' || el.type == 'checkbox') && !el.checked) ? null : el.value; $splat(value).each(function(val){ if (typeof val != 'undefined') queryString.push(el.name + '=' + encodeURIComponent(val)); }); }); return queryString.join('&'); }, clone: function(contents, keepid){ contents = contents !== false; var clone = this.cloneNode(contents); var clean = function(node, element){ if (!keepid) node.removeAttribute('id'); if (Browser.Engine.trident){ node.clearAttributes(); node.mergeAttributes(element); node.removeAttribute('uid'); if (node.options){ var no = node.options, eo = element.options; for (var j = no.length; j--;) no[j].selected = eo[j].selected; } } var prop = props[element.tagName.toLowerCase()]; if (prop && element[prop]) node[prop] = element[prop]; }; if (contents){ var ce = clone.getElementsByTagName('*'), te = this.getElementsByTagName('*'); for (var i = ce.length; i--;) clean(ce[i], te[i]); } clean(clone, this); return document.id(clone); }, destroy: function(){ Element.empty(this); Element.dispose(this); clean(this, true); return null; }, empty: function(){ $A(this.childNodes).each(function(node){ Element.destroy(node); }); return this; }, dispose: function(){ return (this.parentNode) ? this.parentNode.removeChild(this) : this; }, hasChild: function(el){ el = document.id(el, true); if (!el) return false; if (Browser.Engine.webkit && Browser.Engine.version < 420) return $A(this.getElementsByTagName(el.tagName)).contains(el); return (this.contains) ? (this != el && this.contains(el)) : !!(this.compareDocumentPosition(el) & 16); }, match: function(tag){ return (!tag || (tag == this) || (Element.get(this, 'tag') == tag)); } }); Native.implement([Element, Window, Document], { addListener: function(type, fn){ if (type == 'unload'){ var old = fn, self = this; fn = function(){ self.removeListener('unload', fn); old(); }; } else { collected[this.uid] = this; } if (this.addEventListener) this.addEventListener(type, fn, false); else this.attachEvent('on' + type, fn); return this; }, removeListener: function(type, fn){ if (this.removeEventListener) this.removeEventListener(type, fn, false); else this.detachEvent('on' + type, fn); return this; }, retrieve: function(property, dflt){ var storage = get(this.uid), prop = storage[property]; if (dflt != undefined && prop == undefined) prop = storage[property] = dflt; return $pick(prop); }, store: function(property, value){ var storage = get(this.uid); storage[property] = value; return this; }, eliminate: function(property){ var storage = get(this.uid); delete storage[property]; return this; } }); window.addListener('unload', purge); })(); Element.Properties = new Hash; Element.Properties.style = { set: function(style){ this.style.cssText = style; }, get: function(){ return this.style.cssText; }, erase: function(){ this.style.cssText = ''; } }; Element.Properties.tag = { get: function(){ return this.tagName.toLowerCase(); } }; Element.Properties.html = (function(){ var wrapper = document.createElement('div'); var translations = { table: [1, '', '
'], select: [1, ''], tbody: [2, '', '
'], tr: [3, '', '
'] }; translations.thead = translations.tfoot = translations.tbody; var html = { set: function(){ var html = Array.flatten(arguments).join(''); var wrap = Browser.Engine.trident && translations[this.get('tag')]; if (wrap){ var first = wrapper; first.innerHTML = wrap[1] + html + wrap[2]; for (var i = wrap[0]; i--;) first = first.firstChild; this.empty().adopt(first.childNodes); } else { this.innerHTML = html; } } }; html.erase = html.set; return html; })(); if (Browser.Engine.webkit && Browser.Engine.version < 420) Element.Properties.text = { get: function(){ if (this.innerText) return this.innerText; var temp = this.ownerDocument.newElement('div', {html: this.innerHTML}).inject(this.ownerDocument.body); var text = temp.innerText; temp.destroy(); return text; } }; /* --- name: Element.Dimensions description: Contains methods to work with size, scroll, or positioning of Elements and the window object. license: MIT-style license. credits: - Element positioning based on the [qooxdoo](http://qooxdoo.org/) code and smart browser fixes, [LGPL License](http://www.gnu.org/licenses/lgpl.html). - Viewport dimensions based on [YUI](http://developer.yahoo.com/yui/) code, [BSD License](http://developer.yahoo.com/yui/license.html). requires: Element provides: Element.Dimensions ... */ (function(){ Element.implement({ scrollTo: function(x, y){ if (isBody(this)){ this.getWindow().scrollTo(x, y); } else { this.scrollLeft = x; this.scrollTop = y; } return this; }, getSize: function(){ if (isBody(this)) return this.getWindow().getSize(); return {x: this.offsetWidth, y: this.offsetHeight}; }, getScrollSize: function(){ if (isBody(this)) return this.getWindow().getScrollSize(); return {x: this.scrollWidth, y: this.scrollHeight}; }, getScroll: function(){ if (isBody(this)) return this.getWindow().getScroll(); return {x: this.scrollLeft, y: this.scrollTop}; }, getScrolls: function(){ var element = this, position = {x: 0, y: 0}; while (element && !isBody(element)){ position.x += element.scrollLeft; position.y += element.scrollTop; element = element.parentNode; } return position; }, getOffsetParent: function(){ var element = this; if (isBody(element)) return null; if (!Browser.Engine.trident) return element.offsetParent; while ((element = element.parentNode) && !isBody(element)){ if (styleString(element, 'position') != 'static') return element; } return null; }, getOffsets: function(){ if (this.getBoundingClientRect){ var bound = this.getBoundingClientRect(), html = document.id(this.getDocument().documentElement), htmlScroll = html.getScroll(), elemScrolls = this.getScrolls(), elemScroll = this.getScroll(), isFixed = (styleString(this, 'position') == 'fixed'); return { x: bound.left.toInt() + elemScrolls.x - elemScroll.x + ((isFixed) ? 0 : htmlScroll.x) - html.clientLeft, y: bound.top.toInt() + elemScrolls.y - elemScroll.y + ((isFixed) ? 0 : htmlScroll.y) - html.clientTop }; } var element = this, position = {x: 0, y: 0}; if (isBody(this)) return position; while (element && !isBody(element)){ position.x += element.offsetLeft; position.y += element.offsetTop; if (Browser.Engine.gecko){ if (!borderBox(element)){ position.x += leftBorder(element); position.y += topBorder(element); } var parent = element.parentNode; if (parent && styleString(parent, 'overflow') != 'visible'){ position.x += leftBorder(parent); position.y += topBorder(parent); } } else if (element != this && Browser.Engine.webkit){ position.x += leftBorder(element); position.y += topBorder(element); } element = element.offsetParent; } if (Browser.Engine.gecko && !borderBox(this)){ position.x -= leftBorder(this); position.y -= topBorder(this); } return position; }, getPosition: function(relative){ if (isBody(this)) return {x: 0, y: 0}; var offset = this.getOffsets(), scroll = this.getScrolls(); var position = { x: offset.x - scroll.x, y: offset.y - scroll.y }; var relativePosition = (relative && (relative = document.id(relative))) ? relative.getPosition() : {x: 0, y: 0}; return {x: position.x - relativePosition.x, y: position.y - relativePosition.y}; }, getCoordinates: function(element){ if (isBody(this)) return this.getWindow().getCoordinates(); var position = this.getPosition(element), size = this.getSize(); var obj = { left: position.x, top: position.y, width: size.x, height: size.y }; obj.right = obj.left + obj.width; obj.bottom = obj.top + obj.height; return obj; }, computePosition: function(obj){ return { left: obj.x - styleNumber(this, 'margin-left'), top: obj.y - styleNumber(this, 'margin-top') }; }, setPosition: function(obj){ return this.setStyles(this.computePosition(obj)); } }); Native.implement([Document, Window], { getSize: function(){ if (Browser.Engine.presto || Browser.Engine.webkit){ var win = this.getWindow(); return {x: win.innerWidth, y: win.innerHeight}; } var doc = getCompatElement(this); return {x: doc.clientWidth, y: doc.clientHeight}; }, getScroll: function(){ var win = this.getWindow(), doc = getCompatElement(this); return {x: win.pageXOffset || doc.scrollLeft, y: win.pageYOffset || doc.scrollTop}; }, getScrollSize: function(){ var doc = getCompatElement(this), min = this.getSize(); return {x: Math.max(doc.scrollWidth, min.x), y: Math.max(doc.scrollHeight, min.y)}; }, getPosition: function(){ return {x: 0, y: 0}; }, getCoordinates: function(){ var size = this.getSize(); return {top: 0, left: 0, bottom: size.y, right: size.x, height: size.y, width: size.x}; } }); // private methods var styleString = Element.getComputedStyle; function styleNumber(element, style){ return styleString(element, style).toInt() || 0; }; function borderBox(element){ return styleString(element, '-moz-box-sizing') == 'border-box'; }; function topBorder(element){ return styleNumber(element, 'border-top-width'); }; function leftBorder(element){ return styleNumber(element, 'border-left-width'); }; function isBody(element){ return (/^(?:body|html)$/i).test(element.tagName); }; function getCompatElement(element){ var doc = element.getDocument(); return (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body; }; })(); //aliases Element.alias('setPosition', 'position'); //compatability Native.implement([Window, Document, Element], { getHeight: function(){ return this.getSize().y; }, getWidth: function(){ return this.getSize().x; }, getScrollTop: function(){ return this.getScroll().y; }, getScrollLeft: function(){ return this.getScroll().x; }, getScrollHeight: function(){ return this.getScrollSize().y; }, getScrollWidth: function(){ return this.getScrollSize().x; }, getTop: function(){ return this.getPosition().y; }, getLeft: function(){ return this.getPosition().x; } }); /* --- name: Event description: Contains the Event Class, to make the event object cross-browser. license: MIT-style license. requires: [Window, Document, Hash, Array, Function, String] provides: Event ... */ var Event = new Native({ name: 'Event', initialize: function(event, win){ win = win || window; var doc = win.document; event = event || win.event; if (event.$extended) return event; this.$extended = true; var type = event.type; var target = event.target || event.srcElement; while (target && target.nodeType == 3) target = target.parentNode; if (type.test(/key/)){ var code = event.which || event.keyCode; var key = Event.Keys.keyOf(code); if (type == 'keydown'){ var fKey = code - 111; if (fKey > 0 && fKey < 13) key = 'f' + fKey; } key = key || String.fromCharCode(code).toLowerCase(); } else if (type.match(/(click|mouse|menu)/i)){ doc = (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body; var page = { x: event.pageX || event.clientX + doc.scrollLeft, y: event.pageY || event.clientY + doc.scrollTop }; var client = { x: (event.pageX) ? event.pageX - win.pageXOffset : event.clientX, y: (event.pageY) ? event.pageY - win.pageYOffset : event.clientY }; if (type.match(/DOMMouseScroll|mousewheel/)){ var wheel = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0) / 3; } var rightClick = (event.which == 3) || (event.button == 2); var related = null; if (type.match(/over|out/)){ switch (type){ case 'mouseover': related = event.relatedTarget || event.fromElement; break; case 'mouseout': related = event.relatedTarget || event.toElement; } if (!(function(){ while (related && related.nodeType == 3) related = related.parentNode; return true; }).create({attempt: Browser.Engine.gecko})()) related = false; } } return $extend(this, { event: event, type: type, page: page, client: client, rightClick: rightClick, wheel: wheel, relatedTarget: related, target: target, code: code, key: key, shift: event.shiftKey, control: event.ctrlKey, alt: event.altKey, meta: event.metaKey }); } }); Event.Keys = new Hash({ 'enter': 13, 'up': 38, 'down': 40, 'left': 37, 'right': 39, 'esc': 27, 'space': 32, 'backspace': 8, 'tab': 9, 'delete': 46 }); Event.implement({ stop: function(){ return this.stopPropagation().preventDefault(); }, stopPropagation: function(){ if (this.event.stopPropagation) this.event.stopPropagation(); else this.event.cancelBubble = true; return this; }, preventDefault: function(){ if (this.event.preventDefault) this.event.preventDefault(); else this.event.returnValue = false; return this; } }); /* --- name: Element.Event description: Contains Element methods for dealing with events. This file also includes mouseenter and mouseleave custom Element Events. license: MIT-style license. requires: [Element, Event] provides: Element.Event ... */ Element.Properties.events = {set: function(events){ this.addEvents(events); }}; Native.implement([Element, Window, Document], { addEvent: function(type, fn){ var events = this.retrieve('events', {}); events[type] = events[type] || {'keys': [], 'values': []}; if (events[type].keys.contains(fn)) return this; events[type].keys.push(fn); var realType = type, custom = Element.Events.get(type), condition = fn, self = this; if (custom){ if (custom.onAdd) custom.onAdd.call(this, fn); if (custom.condition){ condition = function(event){ if (custom.condition.call(this, event)) return fn.call(this, event); return true; }; } realType = custom.base || realType; } var defn = function(){ return fn.call(self); }; var nativeEvent = Element.NativeEvents[realType]; if (nativeEvent){ if (nativeEvent == 2){ defn = function(event){ event = new Event(event, self.getWindow()); if (condition.call(self, event) === false) event.stop(); }; } this.addListener(realType, defn); } events[type].values.push(defn); return this; }, removeEvent: function(type, fn){ var events = this.retrieve('events'); if (!events || !events[type]) return this; var pos = events[type].keys.indexOf(fn); if (pos == -1) return this; events[type].keys.splice(pos, 1); var value = events[type].values.splice(pos, 1)[0]; var custom = Element.Events.get(type); if (custom){ if (custom.onRemove) custom.onRemove.call(this, fn); type = custom.base || type; } return (Element.NativeEvents[type]) ? this.removeListener(type, value) : this; }, addEvents: function(events){ for (var event in events) this.addEvent(event, events[event]); return this; }, removeEvents: function(events){ var type; if ($type(events) == 'object'){ for (type in events) this.removeEvent(type, events[type]); return this; } var attached = this.retrieve('events'); if (!attached) return this; if (!events){ for (type in attached) this.removeEvents(type); this.eliminate('events'); } else if (attached[events]){ while (attached[events].keys[0]) this.removeEvent(events, attached[events].keys[0]); attached[events] = null; } return this; }, fireEvent: function(type, args, delay){ var events = this.retrieve('events'); if (!events || !events[type]) return this; events[type].keys.each(function(fn){ fn.create({'bind': this, 'delay': delay, 'arguments': args})(); }, this); return this; }, cloneEvents: function(from, type){ from = document.id(from); var fevents = from.retrieve('events'); if (!fevents) return this; if (!type){ for (var evType in fevents) this.cloneEvents(from, evType); } else if (fevents[type]){ fevents[type].keys.each(function(fn){ this.addEvent(type, fn); }, this); } return this; } }); // IE9 try { if (typeof HTMLElement != 'undefined') HTMLElement.prototype.fireEvent = Element.prototype.fireEvent; } catch(e){} Element.NativeEvents = { click: 2, dblclick: 2, mouseup: 2, mousedown: 2, contextmenu: 2, //mouse buttons mousewheel: 2, DOMMouseScroll: 2, //mouse wheel mouseover: 2, mouseout: 2, mousemove: 2, selectstart: 2, selectend: 2, //mouse movement keydown: 2, keypress: 2, keyup: 2, //keyboard focus: 2, blur: 2, change: 2, reset: 2, select: 2, submit: 2, //form elements load: 1, unload: 1, beforeunload: 2, resize: 1, move: 1, DOMContentLoaded: 1, readystatechange: 1, //window error: 1, abort: 1, scroll: 1 //misc }; (function(){ var $check = function(event){ var related = event.relatedTarget; if (related == undefined) return true; if (related === false) return false; return ($type(this) != 'document' && related != this && related.prefix != 'xul' && !this.hasChild(related)); }; Element.Events = new Hash({ mouseenter: { base: 'mouseover', condition: $check }, mouseleave: { base: 'mouseout', condition: $check }, mousewheel: { base: (Browser.Engine.gecko) ? 'DOMMouseScroll' : 'mousewheel' } }); })(); /* --- name: Element.Style description: Contains methods for interacting with the styles of Elements in a fashionable way. license: MIT-style license. requires: Element provides: Element.Style ... */ Element.Properties.styles = {set: function(styles){ this.setStyles(styles); }}; Element.Properties.opacity = { set: function(opacity, novisibility){ if (!novisibility){ if (opacity == 0){ if (this.style.visibility != 'hidden') this.style.visibility = 'hidden'; } else { if (this.style.visibility != 'visible') this.style.visibility = 'visible'; } } if (!this.currentStyle || !this.currentStyle.hasLayout) this.style.zoom = 1; if (Browser.Engine.trident) this.style.filter = (opacity == 1) ? '' : 'alpha(opacity=' + opacity * 100 + ')'; this.style.opacity = opacity; this.store('opacity', opacity); }, get: function(){ return this.retrieve('opacity', 1); } }; Element.implement({ setOpacity: function(value){ return this.set('opacity', value, true); }, getOpacity: function(){ return this.get('opacity'); }, setStyle: function(property, value){ switch (property){ case 'opacity': return this.set('opacity', parseFloat(value)); case 'float': property = (Browser.Engine.trident) ? 'styleFloat' : 'cssFloat'; } property = property.camelCase(); if ($type(value) != 'string'){ var map = (Element.Styles.get(property) || '@').split(' '); value = $splat(value).map(function(val, i){ if (!map[i]) return ''; return ($type(val) == 'number') ? map[i].replace('@', Math.round(val)) : val; }).join(' '); } else if (value == String(Number(value))){ value = Math.round(value); } this.style[property] = value; return this; }, getStyle: function(property){ switch (property){ case 'opacity': return this.get('opacity'); case 'float': property = (Browser.Engine.trident) ? 'styleFloat' : 'cssFloat'; } property = property.camelCase(); var result = this.style[property]; if (!$chk(result)){ result = []; for (var style in Element.ShortStyles){ if (property != style) continue; for (var s in Element.ShortStyles[style]) result.push(this.getStyle(s)); return result.join(' '); } result = this.getComputedStyle(property); } if (result){ result = String(result); var color = result.match(/rgba?\([\d\s,]+\)/); if (color) result = result.replace(color[0], color[0].rgbToHex()); } if (Browser.Engine.presto || (Browser.Engine.trident && !$chk(parseInt(result, 10)))){ if (property.test(/^(height|width)$/)){ var values = (property == 'width') ? ['left', 'right'] : ['top', 'bottom'], size = 0; values.each(function(value){ size += this.getStyle('border-' + value + '-width').toInt() + this.getStyle('padding-' + value).toInt(); }, this); return this['offset' + property.capitalize()] - size + 'px'; } if ((Browser.Engine.presto) && String(result).test('px')) return result; if (property.test(/(border(.+)Width|margin|padding)/)) return '0px'; } return result; }, setStyles: function(styles){ for (var style in styles) this.setStyle(style, styles[style]); return this; }, getStyles: function(){ var result = {}; Array.flatten(arguments).each(function(key){ result[key] = this.getStyle(key); }, this); return result; } }); Element.Styles = new Hash({ left: '@px', top: '@px', bottom: '@px', right: '@px', width: '@px', height: '@px', maxWidth: '@px', maxHeight: '@px', minWidth: '@px', minHeight: '@px', backgroundColor: 'rgb(@, @, @)', backgroundPosition: '@px @px', color: 'rgb(@, @, @)', fontSize: '@px', letterSpacing: '@px', lineHeight: '@px', clip: 'rect(@px @px @px @px)', margin: '@px @px @px @px', padding: '@px @px @px @px', border: '@px @ rgb(@, @, @) @px @ rgb(@, @, @) @px @ rgb(@, @, @)', borderWidth: '@px @px @px @px', borderStyle: '@ @ @ @', borderColor: 'rgb(@, @, @) rgb(@, @, @) rgb(@, @, @) rgb(@, @, @)', zIndex: '@', 'zoom': '@', fontWeight: '@', textIndent: '@px', opacity: '@' }); Element.ShortStyles = {margin: {}, padding: {}, border: {}, borderWidth: {}, borderStyle: {}, borderColor: {}}; ['Top', 'Right', 'Bottom', 'Left'].each(function(direction){ var Short = Element.ShortStyles; var All = Element.Styles; ['margin', 'padding'].each(function(style){ var sd = style + direction; Short[style][sd] = All[sd] = '@px'; }); var bd = 'border' + direction; Short.border[bd] = All[bd] = '@px @ rgb(@, @, @)'; var bdw = bd + 'Width', bds = bd + 'Style', bdc = bd + 'Color'; Short[bd] = {}; Short.borderWidth[bdw] = Short[bd][bdw] = All[bdw] = '@px'; Short.borderStyle[bds] = Short[bd][bds] = All[bds] = '@'; Short.borderColor[bdc] = Short[bd][bdc] = All[bdc] = 'rgb(@, @, @)'; }); /* --- name: Fx description: Contains the basic animation logic to be extended by all other Fx Classes. license: MIT-style license. requires: [Chain, Events, Options] provides: Fx ... */ var Fx = new Class({ Implements: [Chain, Events, Options], options: { /* onStart: $empty, onCancel: $empty, onComplete: $empty, */ fps: 50, unit: false, duration: 500, link: 'ignore' }, initialize: function(options){ this.subject = this.subject || this; this.setOptions(options); this.options.duration = Fx.Durations[this.options.duration] || this.options.duration.toInt(); var wait = this.options.wait; if (wait === false) this.options.link = 'cancel'; }, getTransition: function(){ return function(p){ return -(Math.cos(Math.PI * p) - 1) / 2; }; }, step: function(){ var time = $time(); if (time < this.time + this.options.duration){ var delta = this.transition((time - this.time) / this.options.duration); this.set(this.compute(this.from, this.to, delta)); } else { this.set(this.compute(this.from, this.to, 1)); this.complete(); } }, set: function(now){ return now; }, compute: function(from, to, delta){ return Fx.compute(from, to, delta); }, check: function(){ if (!this.timer) return true; switch (this.options.link){ case 'cancel': this.cancel(); return true; case 'chain': this.chain(this.caller.bind(this, arguments)); return false; } return false; }, start: function(from, to){ if (!this.check(from, to)) return this; this.from = from; this.to = to; this.time = 0; this.transition = this.getTransition(); this.startTimer(); this.onStart(); return this; }, complete: function(){ if (this.stopTimer()) this.onComplete(); return this; }, cancel: function(){ if (this.stopTimer()) this.onCancel(); return this; }, onStart: function(){ this.fireEvent('start', this.subject); }, onComplete: function(){ this.fireEvent('complete', this.subject); if (!this.callChain()) this.fireEvent('chainComplete', this.subject); }, onCancel: function(){ this.fireEvent('cancel', this.subject).clearChain(); }, pause: function(){ this.stopTimer(); return this; }, resume: function(){ this.startTimer(); return this; }, stopTimer: function(){ if (!this.timer) return false; this.time = $time() - this.time; this.timer = $clear(this.timer); return true; }, startTimer: function(){ if (this.timer) return false; this.time = $time() - this.time; this.timer = this.step.periodical(Math.round(1000 / this.options.fps), this); return true; } }); Fx.compute = function(from, to, delta){ return (to - from) * delta + from; }; Fx.Durations = {'short': 250, 'normal': 500, 'long': 1000}; /* --- name: Fx.CSS description: Contains the CSS animation logic. Used by Fx.Tween, Fx.Morph, Fx.Elements. license: MIT-style license. requires: [Fx, Element.Style] provides: Fx.CSS ... */ Fx.CSS = new Class({ Extends: Fx, //prepares the base from/to object prepare: function(element, property, values){ values = $splat(values); var values1 = values[1]; if (!$chk(values1)){ values[1] = values[0]; values[0] = element.getStyle(property); } var parsed = values.map(this.parse); return {from: parsed[0], to: parsed[1]}; }, //parses a value into an array parse: function(value){ value = $lambda(value)(); value = (typeof value == 'string') ? value.split(' ') : $splat(value); return value.map(function(val){ val = String(val); var found = false; Fx.CSS.Parsers.each(function(parser, key){ if (found) return; var parsed = parser.parse(val); if ($chk(parsed)) found = {value: parsed, parser: parser}; }); found = found || {value: val, parser: Fx.CSS.Parsers.String}; return found; }); }, //computes by a from and to prepared objects, using their parsers. compute: function(from, to, delta){ var computed = []; (Math.min(from.length, to.length)).times(function(i){ computed.push({value: from[i].parser.compute(from[i].value, to[i].value, delta), parser: from[i].parser}); }); computed.$family = {name: 'fx:css:value'}; return computed; }, //serves the value as settable serve: function(value, unit){ if ($type(value) != 'fx:css:value') value = this.parse(value); var returned = []; value.each(function(bit){ returned = returned.concat(bit.parser.serve(bit.value, unit)); }); return returned; }, //renders the change to an element render: function(element, property, value, unit){ element.setStyle(property, this.serve(value, unit)); }, //searches inside the page css to find the values for a selector search: function(selector){ if (Fx.CSS.Cache[selector]) return Fx.CSS.Cache[selector]; var to = {}; Array.each(document.styleSheets, function(sheet, j){ var href = sheet.href; if (href && href.contains('://') && !href.contains(document.domain)) return; var rules = sheet.rules || sheet.cssRules; Array.each(rules, function(rule, i){ if (!rule.style) return; var selectorText = (rule.selectorText) ? rule.selectorText.replace(/^\w+/, function(m){ return m.toLowerCase(); }) : null; if (!selectorText || !selectorText.test('^' + selector + '$')) return; Element.Styles.each(function(value, style){ if (!rule.style[style] || Element.ShortStyles[style]) return; value = String(rule.style[style]); to[style] = (value.test(/^rgb/)) ? value.rgbToHex() : value; }); }); }); return Fx.CSS.Cache[selector] = to; } }); Fx.CSS.Cache = {}; Fx.CSS.Parsers = new Hash({ Color: { parse: function(value){ if (value.match(/^#[0-9a-f]{3,6}$/i)) return value.hexToRgb(true); return ((value = value.match(/(\d+),\s*(\d+),\s*(\d+)/))) ? [value[1], value[2], value[3]] : false; }, compute: function(from, to, delta){ return from.map(function(value, i){ return Math.round(Fx.compute(from[i], to[i], delta)); }); }, serve: function(value){ return value.map(Number); } }, Number: { parse: parseFloat, compute: Fx.compute, serve: function(value, unit){ return (unit) ? value + unit : value; } }, String: { parse: $lambda(false), compute: $arguments(1), serve: $arguments(0) } }); /* --- name: Fx.Morph description: Formerly Fx.Styles, effect to transition any number of CSS properties for an element using an object of rules, or CSS based selector rules. license: MIT-style license. requires: Fx.CSS provides: Fx.Morph ... */ Fx.Morph = new Class({ Extends: Fx.CSS, initialize: function(element, options){ this.element = this.subject = document.id(element); this.parent(options); }, set: function(now){ if (typeof now == 'string') now = this.search(now); for (var p in now) this.render(this.element, p, now[p], this.options.unit); return this; }, compute: function(from, to, delta){ var now = {}; for (var p in from) now[p] = this.parent(from[p], to[p], delta); return now; }, start: function(properties){ if (!this.check(properties)) return this; if (typeof properties == 'string') properties = this.search(properties); var from = {}, to = {}; for (var p in properties){ var parsed = this.prepare(this.element, p, properties[p]); from[p] = parsed.from; to[p] = parsed.to; } return this.parent(from, to); } }); Element.Properties.morph = { set: function(options){ var morph = this.retrieve('morph'); if (morph) morph.cancel(); return this.eliminate('morph').store('morph:options', $extend({link: 'cancel'}, options)); }, get: function(options){ if (options || !this.retrieve('morph')){ if (options || !this.retrieve('morph:options')) this.set('morph', options); this.store('morph', new Fx.Morph(this, this.retrieve('morph:options'))); } return this.retrieve('morph'); } }; Element.implement({ morph: function(props){ this.get('morph').start(props); return this; } }); /* --- name: Fx.Transitions description: Contains a set of advanced transitions to be used with any of the Fx Classes. license: MIT-style license. credits: Easing Equations by Robert Penner, , modified and optimized to be used with MooTools. requires: Fx provides: Fx.Transitions ... */ Fx.implement({ getTransition: function(){ var trans = this.options.transition || Fx.Transitions.Sine.easeInOut; if (typeof trans == 'string'){ var data = trans.split(':'); trans = Fx.Transitions; trans = trans[data[0]] || trans[data[0].capitalize()]; if (data[1]) trans = trans['ease' + data[1].capitalize() + (data[2] ? data[2].capitalize() : '')]; } return trans; } }); Fx.Transition = function(transition, params){ params = $splat(params); return $extend(transition, { easeIn: function(pos){ return transition(pos, params); }, easeOut: function(pos){ return 1 - transition(1 - pos, params); }, easeInOut: function(pos){ return (pos <= 0.5) ? transition(2 * pos, params) / 2 : (2 - transition(2 * (1 - pos), params)) / 2; } }); }; Fx.Transitions = new Hash({ linear: $arguments(0) }); Fx.Transitions.extend = function(transitions){ for (var transition in transitions) Fx.Transitions[transition] = new Fx.Transition(transitions[transition]); }; Fx.Transitions.extend({ Pow: function(p, x){ return Math.pow(p, x[0] || 6); }, Expo: function(p){ return Math.pow(2, 8 * (p - 1)); }, Circ: function(p){ return 1 - Math.sin(Math.acos(p)); }, Sine: function(p){ return 1 - Math.sin((1 - p) * Math.PI / 2); }, Back: function(p, x){ x = x[0] || 1.618; return Math.pow(p, 2) * ((x + 1) * p - x); }, Bounce: function(p){ var value; for (var a = 0, b = 1; 1; a += b, b /= 2){ if (p >= (7 - 4 * a) / 11){ value = b * b - Math.pow((11 - 6 * a - 11 * p) / 4, 2); break; } } return value; }, Elastic: function(p, x){ return Math.pow(2, 10 * --p) * Math.cos(20 * p * Math.PI * (x[0] || 1) / 3); } }); ['Quad', 'Cubic', 'Quart', 'Quint'].each(function(transition, i){ Fx.Transitions[transition] = new Fx.Transition(function(p){ return Math.pow(p, [i + 2]); }); }); /* --- name: Fx.Tween description: Formerly Fx.Style, effect to transition any CSS property for an element. license: MIT-style license. requires: Fx.CSS provides: [Fx.Tween, Element.fade, Element.highlight] ... */ Fx.Tween = new Class({ Extends: Fx.CSS, initialize: function(element, options){ this.element = this.subject = document.id(element); this.parent(options); }, set: function(property, now){ if (arguments.length == 1){ now = property; property = this.property || this.options.property; } this.render(this.element, property, now, this.options.unit); return this; }, start: function(property, from, to){ if (!this.check(property, from, to)) return this; var args = Array.flatten(arguments); this.property = this.options.property || args.shift(); var parsed = this.prepare(this.element, this.property, args); return this.parent(parsed.from, parsed.to); } }); Element.Properties.tween = { set: function(options){ var tween = this.retrieve('tween'); if (tween) tween.cancel(); return this.eliminate('tween').store('tween:options', $extend({link: 'cancel'}, options)); }, get: function(options){ if (options || !this.retrieve('tween')){ if (options || !this.retrieve('tween:options')) this.set('tween', options); this.store('tween', new Fx.Tween(this, this.retrieve('tween:options'))); } return this.retrieve('tween'); } }; Element.implement({ tween: function(property, from, to){ this.get('tween').start(arguments); return this; }, fade: function(how){ var fade = this.get('tween'), o = 'opacity', toggle; how = $pick(how, 'toggle'); switch (how){ case 'in': fade.start(o, 1); break; case 'out': fade.start(o, 0); break; case 'show': fade.set(o, 1); break; case 'hide': fade.set(o, 0); break; case 'toggle': var flag = this.retrieve('fade:flag', this.get('opacity') == 1); fade.start(o, (flag) ? 0 : 1); this.store('fade:flag', !flag); toggle = true; break; default: fade.start(o, arguments); } if (!toggle) this.eliminate('fade:flag'); return this; }, highlight: function(start, end){ if (!end){ end = this.retrieve('highlight:original', this.getStyle('background-color')); end = (end == 'transparent') ? '#fff' : end; } var tween = this.get('tween'); tween.start('background-color', start || '#ffff88', end).chain(function(){ this.setStyle('background-color', this.retrieve('highlight:original')); tween.callChain(); }.bind(this)); return this; } }); /* --- name: Request description: Powerful all purpose Request Class. Uses XMLHTTPRequest. license: MIT-style license. requires: [Element, Chain, Events, Options, Browser] provides: Request ... */ var Request = new Class({ Implements: [Chain, Events, Options], options: {/* onRequest: $empty, onComplete: $empty, onCancel: $empty, onSuccess: $empty, onFailure: $empty, onException: $empty,*/ url: '', data: '', headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*' }, async: true, format: false, method: 'post', link: 'ignore', isSuccess: null, emulation: true, urlEncoded: true, encoding: 'utf-8', evalScripts: false, evalResponse: false, noCache: false }, initialize: function(options){ this.xhr = new Browser.Request(); this.setOptions(options); this.options.isSuccess = this.options.isSuccess || this.isSuccess; this.headers = new Hash(this.options.headers); }, onStateChange: function(){ if (this.xhr.readyState != 4 || !this.running) return; this.running = false; this.status = 0; $try(function(){ this.status = this.xhr.status; }.bind(this)); this.xhr.onreadystatechange = $empty; if (this.options.isSuccess.call(this, this.status)){ this.response = {text: this.xhr.responseText, xml: this.xhr.responseXML}; this.success(this.response.text, this.response.xml); } else { this.response = {text: null, xml: null}; this.failure(); } }, isSuccess: function(){ return ((this.status >= 200) && (this.status < 300)); }, processScripts: function(text){ if (this.options.evalResponse || (/(ecma|java)script/).test(this.getHeader('Content-type'))) return $exec(text); return text.stripScripts(this.options.evalScripts); }, success: function(text, xml){ this.onSuccess(this.processScripts(text), xml); }, onSuccess: function(){ this.fireEvent('complete', arguments).fireEvent('success', arguments).callChain(); }, failure: function(){ this.onFailure(); }, onFailure: function(){ this.fireEvent('complete').fireEvent('failure', this.xhr); }, setHeader: function(name, value){ this.headers.set(name, value); return this; }, getHeader: function(name){ return $try(function(){ return this.xhr.getResponseHeader(name); }.bind(this)); }, check: function(){ if (!this.running) return true; switch (this.options.link){ case 'cancel': this.cancel(); return true; case 'chain': this.chain(this.caller.bind(this, arguments)); return false; } return false; }, send: function(options){ if (!this.check(options)) return this; this.running = true; var type = $type(options); if (type == 'string' || type == 'element') options = {data: options}; var old = this.options; options = $extend({data: old.data, url: old.url, method: old.method}, options); var data = options.data, url = String(options.url), method = options.method.toLowerCase(); switch ($type(data)){ case 'element': data = document.id(data).toQueryString(); break; case 'object': case 'hash': data = Hash.toQueryString(data); } if (this.options.format){ var format = 'format=' + this.options.format; data = (data) ? format + '&' + data : format; } if (this.options.emulation && !['get', 'post'].contains(method)){ var _method = '_method=' + method; data = (data) ? _method + '&' + data : _method; method = 'post'; } if (this.options.urlEncoded && method == 'post'){ var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : ''; this.headers.set('Content-type', 'application/x-www-form-urlencoded' + encoding); } if (this.options.noCache){ var noCache = 'noCache=' + new Date().getTime(); data = (data) ? noCache + '&' + data : noCache; } var trimPosition = url.lastIndexOf('/'); if (trimPosition > -1 && (trimPosition = url.indexOf('#')) > -1) url = url.substr(0, trimPosition); if (data && method == 'get'){ url = url + (url.contains('?') ? '&' : '?') + data; data = null; } this.xhr.open(method.toUpperCase(), url, this.options.async); this.xhr.onreadystatechange = this.onStateChange.bind(this); this.headers.each(function(value, key){ try { this.xhr.setRequestHeader(key, value); } catch (e){ this.fireEvent('exception', [key, value]); } }, this); this.fireEvent('request'); this.xhr.send(data); if (!this.options.async) this.onStateChange(); return this; }, cancel: function(){ if (!this.running) return this; this.running = false; this.xhr.abort(); this.xhr.onreadystatechange = $empty; this.xhr = new Browser.Request(); this.fireEvent('cancel'); return this; } }); (function(){ var methods = {}; ['get', 'post', 'put', 'delete', 'GET', 'POST', 'PUT', 'DELETE'].each(function(method){ methods[method] = function(){ var params = Array.link(arguments, {url: String.type, data: $defined}); return this.send($extend(params, {method: method})); }; }); Request.implement(methods); })(); Element.Properties.send = { set: function(options){ var send = this.retrieve('send'); if (send) send.cancel(); return this.eliminate('send').store('send:options', $extend({ data: this, link: 'cancel', method: this.get('method') || 'post', url: this.get('action') }, options)); }, get: function(options){ if (options || !this.retrieve('send')){ if (options || !this.retrieve('send:options')) this.set('send', options); this.store('send', new Request(this.retrieve('send:options'))); } return this.retrieve('send'); } }; Element.implement({ send: function(url){ var sender = this.get('send'); sender.send({data: this, url: url || sender.options.url}); return this; } }); /* --- name: Request.HTML description: Extends the basic Request Class with additional methods for interacting with HTML responses. license: MIT-style license. requires: [Request, Element] provides: Request.HTML ... */ Request.HTML = new Class({ Extends: Request, options: { update: false, append: false, evalScripts: true, filter: false }, processHTML: function(text){ var match = text.match(/]*>([\s\S]*?)<\/body>/i); text = (match) ? match[1] : text; var container = new Element('div'); return $try(function(){ var root = '' + text + '', doc; if (Browser.Engine.trident){ doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = false; doc.loadXML(root); } else { doc = new DOMParser().parseFromString(root, 'text/xml'); } root = doc.getElementsByTagName('root')[0]; if (!root) return null; for (var i = 0, k = root.childNodes.length; i < k; i++){ var child = Element.clone(root.childNodes[i], true, true); if (child) container.grab(child); } return container; }) || container.set('html', text); }, success: function(text){ var options = this.options, response = this.response; response.html = text.stripScripts(function(script){ response.javascript = script; }); var temp = this.processHTML(response.html); response.tree = temp.childNodes; response.elements = temp.getElements('*'); if (options.filter) response.tree = response.elements.filter(options.filter); if (options.update) document.id(options.update).empty().set('html', response.html); else if (options.append) document.id(options.append).adopt(temp.getChildren()); if (options.evalScripts) $exec(response.javascript); this.onSuccess(response.tree, response.elements, response.html, response.javascript); } }); Element.Properties.load = { set: function(options){ var load = this.retrieve('load'); if (load) load.cancel(); return this.eliminate('load').store('load:options', $extend({data: this, link: 'cancel', update: this, method: 'get'}, options)); }, get: function(options){ if (options || ! this.retrieve('load')){ if (options || !this.retrieve('load:options')) this.set('load', options); this.store('load', new Request.HTML(this.retrieve('load:options'))); } return this.retrieve('load'); } }; Element.implement({ load: function(){ this.get('load').send(Array.link(arguments, {data: Object.type, url: String.type})); return this; } }); /* --- name: JSON description: JSON encoder and decoder. license: MIT-style license. see: requires: [Array, String, Number, Function, Hash] provides: JSON ... */ var JSON = new Hash(this.JSON && { stringify: JSON.stringify, parse: JSON.parse }).extend({ $specialChars: {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\'}, $replaceChars: function(chr){ return JSON.$specialChars[chr] || '\\u00' + Math.floor(chr.charCodeAt() / 16).toString(16) + (chr.charCodeAt() % 16).toString(16); }, encode: function(obj){ switch ($type(obj)){ case 'string': return '"' + obj.replace(/[\x00-\x1f\\"]/g, JSON.$replaceChars) + '"'; case 'array': return '[' + String(obj.map(JSON.encode).clean()) + ']'; case 'object': case 'hash': var string = []; Hash.each(obj, function(value, key){ var json = JSON.encode(value); if (json) string.push(JSON.encode(key) + ':' + json); }); return '{' + string + '}'; case 'number': case 'boolean': return String(obj); case false: return 'null'; } return null; }, decode: function(string, secure){ if ($type(string) != 'string' || !string.length) return null; if (secure && !(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(string.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''))) return null; return eval('(' + string + ')'); } }); /* --- name: Request.JSON description: Extends the basic Request Class with additional methods for sending and receiving JSON data. license: MIT-style license. requires: [Request, JSON] provides: [Request.JSON] ... */ Request.JSON = new Class({ Extends: Request, options: { secure: true }, initialize: function(options){ this.parent(options); this.headers.extend({'Accept': 'application/json', 'X-Request': 'JSON'}); }, success: function(text){ this.response.json = JSON.decode(text, this.options.secure); this.onSuccess(this.response.json, text); } }); /* --- name: Cookie description: Class for creating, reading, and deleting browser Cookies. license: MIT-style license. credits: Based on the functions by Peter-Paul Koch (http://quirksmode.org). requires: Options provides: Cookie ... */ var Cookie = new Class({ Implements: Options, options: { path: false, domain: false, duration: false, secure: false, document: document }, initialize: function(key, options){ this.key = key; this.setOptions(options); }, write: function(value){ value = encodeURIComponent(value); if (this.options.domain) value += '; domain=' + this.options.domain; if (this.options.path) value += '; path=' + this.options.path; if (this.options.duration){ var date = new Date(); date.setTime(date.getTime() + this.options.duration * 24 * 60 * 60 * 1000); value += '; expires=' + date.toGMTString(); } if (this.options.secure) value += '; secure'; this.options.document.cookie = this.key + '=' + value; return this; }, read: function(){ var value = this.options.document.cookie.match('(?:^|;)\\s*' + this.key.escapeRegExp() + '=([^;]*)'); return (value) ? decodeURIComponent(value[1]) : null; }, dispose: function(){ new Cookie(this.key, $merge(this.options, {duration: -1})).write(''); return this; } }); Cookie.write = function(key, value, options){ return new Cookie(key, options).write(value); }; Cookie.read = function(key){ return new Cookie(key).read(); }; Cookie.dispose = function(key, options){ return new Cookie(key, options).dispose(); }; /* --- name: DomReady description: Contains the custom event domready. license: MIT-style license. requires: Element.Event provides: DomReady ... */ Element.Events.domready = { onAdd: function(fn){ if (Browser.loaded) fn.call(this); } }; (function(){ var domready = function(){ if (Browser.loaded) return; Browser.loaded = true; window.fireEvent('domready'); document.fireEvent('domready'); }; window.addEvent('load', domready); if (Browser.Engine.trident){ var temp = document.createElement('div'); (function(){ ($try(function(){ temp.doScroll(); // Technique by Diego Perini return document.id(temp).inject(document.body).set('html', 'temp').dispose(); })) ? domready() : arguments.callee.delay(50); })(); } else if (Browser.Engine.webkit && Browser.Engine.version < 525){ (function(){ (['loaded', 'complete'].contains(document.readyState)) ? domready() : arguments.callee.delay(50); })(); } else { document.addEvent('DOMContentLoaded', domready); } })(); /* --- name: Selectors description: Adds advanced CSS-style querying capabilities for targeting HTML Elements. Includes pseudo selectors. license: MIT-style license. requires: Element provides: Selectors ... */ Native.implement([Document, Element], { getElements: function(expression, nocash){ expression = expression.split(','); var items, local = {}; for (var i = 0, l = expression.length; i < l; i++){ var selector = expression[i], elements = Selectors.Utils.search(this, selector, local); if (i != 0 && elements.item) elements = $A(elements); items = (i == 0) ? elements : (items.item) ? $A(items).concat(elements) : items.concat(elements); } return new Elements(items, {ddup: (expression.length > 1), cash: !nocash}); } }); Element.implement({ match: function(selector){ if (!selector || (selector == this)) return true; var tagid = Selectors.Utils.parseTagAndID(selector); var tag = tagid[0], id = tagid[1]; if (!Selectors.Filters.byID(this, id) || !Selectors.Filters.byTag(this, tag)) return false; var parsed = Selectors.Utils.parseSelector(selector); return (parsed) ? Selectors.Utils.filter(this, parsed, {}) : true; } }); var Selectors = {Cache: {nth: {}, parsed: {}}}; Selectors.RegExps = { id: (/#([\w-]+)/), tag: (/^(\w+|\*)/), quick: (/^(\w+|\*)$/), splitter: (/\s*([+>~\s])\s*([a-zA-Z#.*:\[])/g), combined: (/\.([\w-]+)|\[(\w+)(?:([!*^$~|]?=)(["']?)([^\4]*?)\4)?\]|:([\w-]+)(?:\(["']?(.*?)?["']?\)|$)/g) }; Selectors.Utils = { chk: function(item, uniques){ if (!uniques) return true; var uid = $uid(item); if (!uniques[uid]) return uniques[uid] = true; return false; }, parseNthArgument: function(argument){ if (Selectors.Cache.nth[argument]) return Selectors.Cache.nth[argument]; var parsed = argument.match(/^([+-]?\d*)?([a-z]+)?([+-]?\d*)?$/); if (!parsed) return false; var inta = parseInt(parsed[1], 10); var a = (inta || inta === 0) ? inta : 1; var special = parsed[2] || false; var b = parseInt(parsed[3], 10) || 0; if (a != 0){ b--; while (b < 1) b += a; while (b >= a) b -= a; } else { a = b; special = 'index'; } switch (special){ case 'n': parsed = {a: a, b: b, special: 'n'}; break; case 'odd': parsed = {a: 2, b: 0, special: 'n'}; break; case 'even': parsed = {a: 2, b: 1, special: 'n'}; break; case 'first': parsed = {a: 0, special: 'index'}; break; case 'last': parsed = {special: 'last-child'}; break; case 'only': parsed = {special: 'only-child'}; break; default: parsed = {a: (a - 1), special: 'index'}; } return Selectors.Cache.nth[argument] = parsed; }, parseSelector: function(selector){ if (Selectors.Cache.parsed[selector]) return Selectors.Cache.parsed[selector]; var m, parsed = {classes: [], pseudos: [], attributes: []}; while ((m = Selectors.RegExps.combined.exec(selector))){ var cn = m[1], an = m[2], ao = m[3], av = m[5], pn = m[6], pa = m[7]; if (cn){ parsed.classes.push(cn); } else if (pn){ var parser = Selectors.Pseudo.get(pn); if (parser) parsed.pseudos.push({parser: parser, argument: pa}); else parsed.attributes.push({name: pn, operator: '=', value: pa}); } else if (an){ parsed.attributes.push({name: an, operator: ao, value: av}); } } if (!parsed.classes.length) delete parsed.classes; if (!parsed.attributes.length) delete parsed.attributes; if (!parsed.pseudos.length) delete parsed.pseudos; if (!parsed.classes && !parsed.attributes && !parsed.pseudos) parsed = null; return Selectors.Cache.parsed[selector] = parsed; }, parseTagAndID: function(selector){ var tag = selector.match(Selectors.RegExps.tag); var id = selector.match(Selectors.RegExps.id); return [(tag) ? tag[1] : '*', (id) ? id[1] : false]; }, filter: function(item, parsed, local){ var i; if (parsed.classes){ for (i = parsed.classes.length; i--; i){ var cn = parsed.classes[i]; if (!Selectors.Filters.byClass(item, cn)) return false; } } if (parsed.attributes){ for (i = parsed.attributes.length; i--; i){ var att = parsed.attributes[i]; if (!Selectors.Filters.byAttribute(item, att.name, att.operator, att.value)) return false; } } if (parsed.pseudos){ for (i = parsed.pseudos.length; i--; i){ var psd = parsed.pseudos[i]; if (!Selectors.Filters.byPseudo(item, psd.parser, psd.argument, local)) return false; } } return true; }, getByTagAndID: function(ctx, tag, id){ if (id){ var item = (ctx.getElementById) ? ctx.getElementById(id, true) : Element.getElementById(ctx, id, true); return (item && Selectors.Filters.byTag(item, tag)) ? [item] : []; } else { return ctx.getElementsByTagName(tag); } }, search: function(self, expression, local){ var splitters = []; var selectors = expression.trim().replace(Selectors.RegExps.splitter, function(m0, m1, m2){ splitters.push(m1); return ':)' + m2; }).split(':)'); var items, filtered, item; for (var i = 0, l = selectors.length; i < l; i++){ var selector = selectors[i]; if (i == 0 && Selectors.RegExps.quick.test(selector)){ items = self.getElementsByTagName(selector); continue; } var splitter = splitters[i - 1]; var tagid = Selectors.Utils.parseTagAndID(selector); var tag = tagid[0], id = tagid[1]; if (i == 0){ items = Selectors.Utils.getByTagAndID(self, tag, id); } else { var uniques = {}, found = []; for (var j = 0, k = items.length; j < k; j++) found = Selectors.Getters[splitter](found, items[j], tag, id, uniques); items = found; } var parsed = Selectors.Utils.parseSelector(selector); if (parsed){ filtered = []; for (var m = 0, n = items.length; m < n; m++){ item = items[m]; if (Selectors.Utils.filter(item, parsed, local)) filtered.push(item); } items = filtered; } } return items; } }; Selectors.Getters = { ' ': function(found, self, tag, id, uniques){ var items = Selectors.Utils.getByTagAndID(self, tag, id); for (var i = 0, l = items.length; i < l; i++){ var item = items[i]; if (Selectors.Utils.chk(item, uniques)) found.push(item); } return found; }, '>': function(found, self, tag, id, uniques){ var children = Selectors.Utils.getByTagAndID(self, tag, id); for (var i = 0, l = children.length; i < l; i++){ var child = children[i]; if (child.parentNode == self && Selectors.Utils.chk(child, uniques)) found.push(child); } return found; }, '+': function(found, self, tag, id, uniques){ while ((self = self.nextSibling)){ if (self.nodeType == 1){ if (Selectors.Utils.chk(self, uniques) && Selectors.Filters.byTag(self, tag) && Selectors.Filters.byID(self, id)) found.push(self); break; } } return found; }, '~': function(found, self, tag, id, uniques){ while ((self = self.nextSibling)){ if (self.nodeType == 1){ if (!Selectors.Utils.chk(self, uniques)) break; if (Selectors.Filters.byTag(self, tag) && Selectors.Filters.byID(self, id)) found.push(self); } } return found; } }; Selectors.Filters = { byTag: function(self, tag){ return (tag == '*' || (self.tagName && self.tagName.toLowerCase() == tag)); }, byID: function(self, id){ return (!id || (self.id && self.id == id)); }, byClass: function(self, klass){ return (self.className && self.className.contains && self.className.contains(klass, ' ')); }, byPseudo: function(self, parser, argument, local){ return parser.call(self, argument, local); }, byAttribute: function(self, name, operator, value){ var result = Element.prototype.getProperty.call(self, name); if (!result) return (operator == '!='); if (!operator || value == undefined) return true; switch (operator){ case '=': return (result == value); case '*=': return (result.contains(value)); case '^=': return (result.substr(0, value.length) == value); case '$=': return (result.substr(result.length - value.length) == value); case '!=': return (result != value); case '~=': return result.contains(value, ' '); case '|=': return result.contains(value, '-'); } return false; } }; Selectors.Pseudo = new Hash({ // w3c pseudo selectors checked: function(){ return this.checked; }, empty: function(){ return !(this.innerText || this.textContent || '').length; }, not: function(selector){ return !Element.match(this, selector); }, contains: function(text){ return (this.innerText || this.textContent || '').contains(text); }, 'first-child': function(){ return Selectors.Pseudo.index.call(this, 0); }, 'last-child': function(){ var element = this; while ((element = element.nextSibling)){ if (element.nodeType == 1) return false; } return true; }, 'only-child': function(){ var prev = this; while ((prev = prev.previousSibling)){ if (prev.nodeType == 1) return false; } var next = this; while ((next = next.nextSibling)){ if (next.nodeType == 1) return false; } return true; }, 'nth-child': function(argument, local){ argument = (argument == undefined) ? 'n' : argument; var parsed = Selectors.Utils.parseNthArgument(argument); if (parsed.special != 'n') return Selectors.Pseudo[parsed.special].call(this, parsed.a, local); var count = 0; local.positions = local.positions || {}; var uid = $uid(this); if (!local.positions[uid]){ var self = this; while ((self = self.previousSibling)){ if (self.nodeType != 1) continue; count ++; var position = local.positions[$uid(self)]; if (position != undefined){ count = position + count; break; } } local.positions[uid] = count; } return (local.positions[uid] % parsed.a == parsed.b); }, // custom pseudo selectors index: function(index){ var element = this, count = 0; while ((element = element.previousSibling)){ if (element.nodeType == 1 && ++count > index) return false; } return (count == index); }, even: function(argument, local){ return Selectors.Pseudo['nth-child'].call(this, '2n+1', local); }, odd: function(argument, local){ return Selectors.Pseudo['nth-child'].call(this, '2n', local); }, selected: function(){ return this.selected; }, enabled: function(){ return (this.disabled === false); } }); /* --- name: Swiff description: Wrapper for embedding SWF movies. Supports External Interface Communication. license: MIT-style license. credits: Flash detection & Internet Explorer + Flash Player 9 fix inspired by SWFObject. requires: [Options, $util] provides: Swiff ... */ var Swiff = new Class({ Implements: [Options], options: { id: null, height: 1, width: 1, container: null, properties: {}, params: { quality: 'high', allowScriptAccess: 'always', wMode: 'transparent', swLiveConnect: true }, callBacks: {}, vars: {} }, toElement: function(){ return this.object; }, initialize: function(path, options){ this.instance = 'Swiff_' + $time(); this.setOptions(options); options = this.options; var id = this.id = options.id || this.instance; var container = document.id(options.container); Swiff.CallBacks[this.instance] = {}; var params = options.params, vars = options.vars, callBacks = options.callBacks; var properties = $extend({height: options.height, width: options.width}, options.properties); var self = this; for (var callBack in callBacks){ Swiff.CallBacks[this.instance][callBack] = (function(option){ return function(){ return option.apply(self.object, arguments); }; })(callBacks[callBack]); vars[callBack] = 'Swiff.CallBacks.' + this.instance + '.' + callBack; } params.flashVars = Hash.toQueryString(vars); if (Browser.Engine.trident){ properties.classid = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'; params.movie = path; } else { properties.type = 'application/x-shockwave-flash'; properties.data = path; } var build = ''; } build += ''; this.object = ((container) ? container.empty() : new Element('div')).set('html', build).firstChild; }, replaces: function(element){ element = document.id(element, true); element.parentNode.replaceChild(this.toElement(), element); return this; }, inject: function(element){ document.id(element, true).appendChild(this.toElement()); return this; }, remote: function(){ return Swiff.remote.apply(Swiff, [this.toElement()].extend(arguments)); } }); Swiff.CallBacks = {}; Swiff.remote = function(obj, fn){ var rs = obj.CallFunction('' + __flash__argumentsToXML(arguments, 2) + ''); return eval(rs); }; /** -- M O O T O O L S C O R E -- **/ function format_text(a){a=a.split(" ").join("");a=a.split("\n").join("");a=a.split(".").join(".\n\n");a=a.split("\n ").join("\n");return a}; /** -- M O O T O O L S M O R E -- **/ //MooTools More, . Copyright (c) 2006-2009 Aaron Newton , Valerio Proietti & the MooTools team , MIT Style License. /* --- script: More.js name: More description: MooTools More license: MIT-style license requires: - Core/MooTools provides: [MooTools.More] ... */ MooTools.More = { 'version': '1.2.5.1', 'build': '254884f2b83651bf95260eed5c6cceb838e22d8e' }; /* --- script: Fx.Elements.js name: Fx.Elements description: Effect to change any number of CSS properties of any number of Elements. license: MIT-style license authors: - Valerio Proietti requires: - Core/Fx.CSS - /MooTools.More provides: [Fx.Elements] ... */ Fx.Elements = new Class({ Extends: Fx.CSS, initialize: function(elements, options){ this.elements = this.subject = $$(elements); this.parent(options); }, compute: function(from, to, delta){ var now = {}; for (var i in from){ var iFrom = from[i], iTo = to[i], iNow = now[i] = {}; for (var p in iFrom) iNow[p] = this.parent(iFrom[p], iTo[p], delta); } return now; }, set: function(now){ for (var i in now){ if (!this.elements[i]) continue; var iNow = now[i]; for (var p in iNow) this.render(this.elements[i], p, iNow[p], this.options.unit); } return this; }, start: function(obj){ if (!this.check(obj)) return this; var from = {}, to = {}; for (var i in obj){ if (!this.elements[i]) continue; var iProps = obj[i], iFrom = from[i] = {}, iTo = to[i] = {}; for (var p in iProps){ var parsed = this.prepare(this.elements[i], p, iProps[p]); iFrom[p] = parsed.from; iTo[p] = parsed.to; } } return this.parent(from, to); } }); /* --- script: Fx.Accordion.js name: Fx.Accordion description: An Fx.Elements extension which allows you to easily create accordion type controls. license: MIT-style license authors: - Valerio Proietti requires: - Core/Element.Event - /Fx.Elements provides: [Fx.Accordion] ... */ Fx.Accordion = new Class({ Extends: Fx.Elements, options: {/* onActive: $empty(toggler, section), onBackground: $empty(toggler, section), */ fixedHeight: false, fixedWidth: false, display: 0, show: false, height: true, width: false, opacity: true, alwaysHide: false, trigger: 'click', initialDisplayFx: true, returnHeightToAuto: true }, initialize: function(){ var params = Array.link(arguments, { 'container': Element.type, //deprecated 'options': Object.type, 'togglers': $defined, 'elements': $defined }); this.parent(params.elements, params.options); this.togglers = $$(params.togglers); this.previous = -1; this.internalChain = new Chain(); if (this.options.alwaysHide) this.options.wait = true; if ($chk(this.options.show)){ this.options.display = false; this.previous = this.options.show; } if (this.options.start){ this.options.display = false; this.options.show = false; } this.effects = {}; if (this.options.opacity) this.effects.opacity = 'fullOpacity'; if (this.options.width) this.effects.width = this.options.fixedWidth ? 'fullWidth' : 'offsetWidth'; if (this.options.height) this.effects.height = this.options.fixedHeight ? 'fullHeight' : 'scrollHeight'; for (var i = 0, l = this.togglers.length; i < l; i++) this.addSection(this.togglers[i], this.elements[i]); this.elements.each(function(el, i){ if (this.options.show === i){ this.fireEvent('active', [this.togglers[i], el]); } else { for (var fx in this.effects) el.setStyle(fx, 0); } }, this); if ($chk(this.options.display) || this.options.initialDisplayFx === false) this.display(this.options.display, this.options.initialDisplayFx); if (this.options.fixedHeight !== false) this.options.returnHeightToAuto = false; this.addEvent('complete', this.internalChain.callChain.bind(this.internalChain)); }, addSection: function(toggler, element){ toggler = document.id(toggler); element = document.id(element); var test = this.togglers.contains(toggler); this.togglers.include(toggler); this.elements.include(element); var idx = this.togglers.indexOf(toggler); var displayer = this.display.bind(this, idx); toggler.store('accordion:display', displayer); toggler.addEvent(this.options.trigger, displayer); if (this.options.height) element.setStyles({'padding-top': 0, 'border-top': 'none', 'padding-bottom': 0, 'border-bottom': 'none'}); if (this.options.width) element.setStyles({'padding-left': 0, 'border-left': 'none', 'padding-right': 0, 'border-right': 'none'}); element.fullOpacity = 1; if (this.options.fixedWidth) element.fullWidth = this.options.fixedWidth; if (this.options.fixedHeight) element.fullHeight = this.options.fixedHeight; element.setStyle('overflow', 'hidden'); if (!test){ for (var fx in this.effects) element.setStyle(fx, 0); } return this; }, removeSection: function(toggler, displayIndex) { var idx = this.togglers.indexOf(toggler); var element = this.elements[idx]; var remover = function(){ this.togglers.erase(toggler); this.elements.erase(element); this.detach(toggler); }.bind(this); if (this.now == idx || displayIndex != undefined) this.display($pick(displayIndex, idx - 1 >= 0 ? idx - 1 : 0)).chain(remover); else remover(); return this; }, detach: function(toggler){ var remove = function(toggler) { toggler.removeEvent(this.options.trigger, toggler.retrieve('accordion:display')); }.bind(this); if (!toggler) this.togglers.each(remove); else remove(toggler); return this; }, display: function(index, useFx){ if (!this.check(index, useFx)) return this; useFx = $pick(useFx, true); index = ($type(index) == 'element') ? this.elements.indexOf(index) : index; if (index == this.previous && !this.options.alwaysHide) return this; if (this.options.returnHeightToAuto){ var prev = this.elements[this.previous]; if (prev && !this.selfHidden){ for (var fx in this.effects){ prev.setStyle(fx, prev[this.effects[fx]]); } } } if ((this.timer && this.options.wait) || (index === this.previous && !this.options.alwaysHide)) return this; this.previous = index; var obj = {}; this.elements.each(function(el, i){ obj[i] = {}; var hide; if (i != index){ hide = true; } else if (this.options.alwaysHide && ((el.offsetHeight > 0 && this.options.height) || el.offsetWidth > 0 && this.options.width)){ hide = true; this.selfHidden = true; } this.fireEvent(hide ? 'background' : 'active', [this.togglers[i], el]); for (var fx in this.effects) obj[i][fx] = hide ? 0 : el[this.effects[fx]]; }, this); this.internalChain.clearChain(); this.internalChain.chain(function(){ if (this.options.returnHeightToAuto && !this.selfHidden){ var el = this.elements[index]; if (el) el.setStyle('height', 'auto'); }; }.bind(this)); return useFx ? this.start(obj) : this.set(obj); } }); /* Compatibility with 1.2.0 */ var Accordion = new Class({ Extends: Fx.Accordion, initialize: function(){ this.parent.apply(this, arguments); var params = Array.link(arguments, {'container': Element.type}); this.container = params.container; }, addSection: function(toggler, element, pos){ toggler = document.id(toggler); element = document.id(element); var test = this.togglers.contains(toggler); var len = this.togglers.length; if (len && (!test || pos)){ pos = $pick(pos, len - 1); toggler.inject(this.togglers[pos], 'before'); element.inject(toggler, 'after'); } else if (this.container && !test){ toggler.inject(this.container); element.inject(this.container); } return this.parent.apply(this, arguments); } }); /* --- script: Fx.Scroll.js name: Fx.Scroll description: Effect to smoothly scroll any element, including the window. license: MIT-style license authors: - Valerio Proietti requires: - Core/Fx - Core/Element.Event - Core/Element.Dimensions - /MooTools.More provides: [Fx.Scroll] ... */ Fx.Scroll = new Class({ Extends: Fx, options: { offset: {x: 0, y: 0}, wheelStops: true }, initialize: function(element, options){ this.element = this.subject = document.id(element); this.parent(options); var cancel = this.cancel.bind(this, false); if ($type(this.element) != 'element') this.element = document.id(this.element.getDocument().body); var stopper = this.element; if (this.options.wheelStops){ this.addEvent('start', function(){ stopper.addEvent('mousewheel', cancel); }, true); this.addEvent('complete', function(){ stopper.removeEvent('mousewheel', cancel); }, true); } }, set: function(){ var now = Array.flatten(arguments); if (Browser.Engine.gecko) now = [Math.round(now[0]), Math.round(now[1])]; this.element.scrollTo(now[0] + this.options.offset.x, now[1] + this.options.offset.y); }, compute: function(from, to, delta){ return [0, 1].map(function(i){ return Fx.compute(from[i], to[i], delta); }); }, start: function(x, y){ if (!this.check(x, y)) return this; var scrollSize = this.element.getScrollSize(), scroll = this.element.getScroll(), values = {x: x, y: y}; for (var z in values){ var max = scrollSize[z]; if ($chk(values[z])) values[z] = ($type(values[z]) == 'number') ? values[z] : max; else values[z] = scroll[z]; values[z] += this.options.offset[z]; } return this.parent([scroll.x, scroll.y], [values.x, values.y]); }, toTop: function(){ return this.start(false, 0); }, toLeft: function(){ return this.start(0, false); }, toRight: function(){ return this.start('right', false); }, toBottom: function(){ return this.start(false, 'bottom'); }, toElement: function(el){ var position = document.id(el).getPosition(this.element); return this.start(position.x, position.y); }, scrollIntoView: function(el, axes, offset){ axes = axes ? $splat(axes) : ['x','y']; var to = {}; el = document.id(el); var pos = el.getPosition(this.element); var size = el.getSize(); var scroll = this.element.getScroll(); var containerSize = this.element.getSize(); var edge = { x: pos.x + size.x, y: pos.y + size.y }; ['x','y'].each(function(axis) { if (axes.contains(axis)) { if (edge[axis] > scroll[axis] + containerSize[axis]) to[axis] = edge[axis] - containerSize[axis]; if (pos[axis] < scroll[axis]) to[axis] = pos[axis]; } if (to[axis] == null) to[axis] = scroll[axis]; if (offset && offset[axis]) to[axis] = to[axis] + offset[axis]; }, this); if (to.x != scroll.x || to.y != scroll.y) this.start(to.x, to.y); return this; }, scrollToCenter: function(el, axes, offset){ axes = axes ? $splat(axes) : ['x', 'y']; el = $(el); var to = {}, pos = el.getPosition(this.element), size = el.getSize(), scroll = this.element.getScroll(), containerSize = this.element.getSize(), edge = { x: pos.x + size.x, y: pos.y + size.y }; ['x','y'].each(function(axis){ if(axes.contains(axis)){ to[axis] = pos[axis] - (containerSize[axis] - size[axis])/2; } if(to[axis] == null) to[axis] = scroll[axis]; if(offset && offset[axis]) to[axis] = to[axis] + offset[axis]; }, this); if (to.x != scroll.x || to.y != scroll.y) this.start(to.x, to.y); return this; } }); /* --- script: Fx.Slide.js name: Fx.Slide description: Effect to slide an element in and out of view. license: MIT-style license authors: - Valerio Proietti requires: - Core/Fx - Core/Element.Style - /MooTools.More provides: [Fx.Slide] ... */ Fx.Slide = new Class({ Extends: Fx, options: { mode: 'vertical', wrapper: false, hideOverflow: true, resetHeight: false }, initialize: function(element, options){ this.addEvent('complete', function(){ this.open = (this.wrapper['offset' + this.layout.capitalize()] != 0); if (this.open && this.options.resetHeight) this.wrapper.setStyle('height', ''); if (this.open && Browser.Engine.webkit419) this.element.dispose().inject(this.wrapper); }, true); this.element = this.subject = document.id(element); this.parent(options); var wrapper = this.element.retrieve('wrapper'); var styles = this.element.getStyles('margin', 'position', 'overflow'); if (this.options.hideOverflow) styles = $extend(styles, {overflow: 'hidden'}); if (this.options.wrapper) wrapper = document.id(this.options.wrapper).setStyles(styles); this.wrapper = wrapper || new Element('div', { styles: styles }).wraps(this.element); this.element.store('wrapper', this.wrapper).setStyle('margin', 0); this.now = []; this.open = true; }, vertical: function(){ this.margin = 'margin-top'; this.layout = 'height'; this.offset = this.element.offsetHeight; }, horizontal: function(){ this.margin = 'margin-left'; this.layout = 'width'; this.offset = this.element.offsetWidth; }, set: function(now){ this.element.setStyle(this.margin, now[0]); this.wrapper.setStyle(this.layout, now[1]); return this; }, compute: function(from, to, delta){ return [0, 1].map(function(i){ return Fx.compute(from[i], to[i], delta); }); }, start: function(how, mode){ if (!this.check(how, mode)) return this; this[mode || this.options.mode](); var margin = this.element.getStyle(this.margin).toInt(); var layout = this.wrapper.getStyle(this.layout).toInt(); var caseIn = [[margin, layout], [0, this.offset]]; var caseOut = [[margin, layout], [-this.offset, 0]]; var start; switch (how){ case 'in': start = caseIn; break; case 'out': start = caseOut; break; case 'toggle': start = (layout == 0) ? caseIn : caseOut; } return this.parent(start[0], start[1]); }, slideIn: function(mode){ return this.start('in', mode); }, slideOut: function(mode){ return this.start('out', mode); }, hide: function(mode){ this[mode || this.options.mode](); this.open = false; return this.set([-this.offset, 0]); }, show: function(mode){ this[mode || this.options.mode](); this.open = true; return this.set([0, this.offset]); }, toggle: function(mode){ return this.start('toggle', mode); } }); Element.Properties.slide = { set: function(options){ var slide = this.retrieve('slide'); if (slide) slide.cancel(); return this.eliminate('slide').store('slide:options', $extend({link: 'cancel'}, options)); }, get: function(options){ if (options || !this.retrieve('slide')){ if (options || !this.retrieve('slide:options')) this.set('slide', options); this.store('slide', new Fx.Slide(this, this.retrieve('slide:options'))); } return this.retrieve('slide'); } }; Element.implement({ slide: function(how, mode){ how = how || 'toggle'; var slide = this.get('slide'), toggle; switch (how){ case 'hide': slide.hide(mode); break; case 'show': slide.show(mode); break; case 'toggle': var flag = this.retrieve('slide:flag', slide.open); slide[flag ? 'slideOut' : 'slideIn'](mode); this.store('slide:flag', !flag); toggle = true; break; default: slide.start(how, mode); } if (!toggle) this.eliminate('slide:flag'); return this; } }); /* --- script: Fx.SmoothScroll.js name: Fx.SmoothScroll description: Class for creating a smooth scrolling effect to all internal links on the page. license: MIT-style license authors: - Valerio Proietti requires: - Core/Selectors - /Fx.Scroll provides: [Fx.SmoothScroll] ... */ var SmoothScroll = Fx.SmoothScroll = new Class({ Extends: Fx.Scroll, initialize: function(options, context){ context = context || document; this.doc = context.getDocument(); var win = context.getWindow(); this.parent(this.doc, options); this.links = $$(this.options.links || this.doc.links); var location = win.location.href.match(/^[^#]*/)[0] + '#'; this.links.each(function(link){ if (link.href.indexOf(location) != 0) {return;} var anchor = link.href.substr(location.length); if (anchor) this.useLink(link, anchor); }, this); if (!Browser.Engine.webkit419) { this.addEvent('complete', function(){ win.location.hash = this.anchor; }, true); } }, useLink: function(link, anchor){ var el; link.addEvent('click', function(event){ if (el !== false && !el) el = document.id(anchor) || this.doc.getElement('a[name=' + anchor + ']'); if (el) { event.preventDefault(); this.anchor = anchor; this.toElement(el).chain(function(){ this.fireEvent('scrolledTo', [link, el]); }.bind(this)); link.blur(); } }.bind(this)); } }); /* --- script: Assets.js name: Assets description: Provides methods to dynamically load JavaScript, CSS, and Image files into the document. license: MIT-style license authors: - Valerio Proietti requires: - Core/Element.Event - /MooTools.More provides: [Assets] ... */ var Asset = { javascript: function(source, properties){ properties = $extend({ onload: $empty, document: document, check: $lambda(true) }, properties); if (properties.onLoad) { properties.onload = properties.onLoad; delete properties.onLoad; } var script = new Element('script', {src: source, type: 'text/javascript'}); var load = properties.onload.bind(script), check = properties.check, doc = properties.document; delete properties.onload; delete properties.check; delete properties.document; script.addEvents({ load: load, readystatechange: function(){ if (['loaded', 'complete'].contains(this.readyState)) load(); } }).set(properties); if (Browser.Engine.webkit419) var checker = (function(){ if (!$try(check)) return; $clear(checker); load(); }).periodical(50); return script.inject(doc.head); }, css: function(source, properties){ properties = properties || {}; var onload = properties.onload || properties.onLoad; if (onload) { properties.events = properties.events || {}; properties.events.load = onload; delete properties.onload; delete properties.onLoad; } return new Element('link', $merge({ rel: 'stylesheet', media: 'screen', type: 'text/css', href: source }, properties)).inject(document.head); }, image: function(source, properties){ properties = $merge({ onload: $empty, onabort: $empty, onerror: $empty }, properties); var image = new Image(); var element = document.id(image) || new Element('img'); ['load', 'abort', 'error'].each(function(name){ var type = 'on' + name; var cap = name.capitalize(); if (properties['on' + cap]) { properties[type] = properties['on' + cap]; delete properties['on' + cap]; } var event = properties[type]; delete properties[type]; image[type] = function(){ if (!image) return; if (!element.parentNode){ element.width = image.width; element.height = image.height; } image = image.onload = image.onabort = image.onerror = null; event.delay(1, element, element); element.fireEvent(name, element, 1); }; }); image.src = element.src = source; if (image && image.complete) image.onload.delay(1); return element.set(properties); }, images: function(sources, options){ options = $merge({ onComplete: $empty, onProgress: $empty, onError: $empty, properties: {} }, options); sources = $splat(sources); var images = []; var counter = 0; return new Elements(sources.map(function(source, index){ return Asset.image(source, $extend(options.properties, { onload: function(){ options.onProgress.call(this, counter, index); counter++; if (counter == sources.length) options.onComplete(); }, onerror: function(){ options.onError.call(this, counter, index); counter++; if (counter == sources.length) options.onComplete(); } })); })); } }; /** -- M O O T O O L S M O R E -- **/ /** -- M O O B U B B L E -- **/ // JavaScript Document var moobubble = new Class ({ Implements: [Options], options: { enabled:true, //Allows all functions of the bubble to be disabled. target: false, //The ID of the element to attach the bubble to. location:false, //Custom flag to define if the target is located in the site side or header container. bubble: false, //The ID of the element which contains the contents for the bubble. position:'corner', //Where the bubble should attach to the container {options: corner, center}. edge:false, //Specify what edge of the target the bubble should attach to. If false will be auto calculated. style:false, //A class added to the bubble to allow specific styling. force_show:false, //If set to true the bubble will be shown onscreen even when the calculated position would put it elsewhere. offset: { //Allow a manual offset to the x and y position of the created bubble. x:0, y:0 }, close_button: { icon:false, location: 'top', action:false } }, params: { alive:false, //Set to true when a bubble has been created. window_width: false, //Width of the viewport window. window_height: false, //Height of the viewport window. target_width: false, //Width of the target element. target_height:false, //Height of the target element. target_x:false, //X position of the target element {taken from top left}. target_y:false, //Y position of the target element {taken from top left}. target_relative_h:'left', //The horizontal relative position of the target in the viewport. target_relative_v:'bottom', //The vertical relative position of the target in the viewport. bubble_width:false, //The width of the created bubble. bubble_height:false, //The height of the created bubble. bubble_x:0, //X position of the bubble. bubble_y:0, //Y position of the bubble. events: { //Settings for events. enabled: false, //Prevents events from functioning while false. Set to enabled when the bubble is started. created_events: 0, //Used for unique event id's, value will never be reduced. total_events: 0, //Total number of events for the bubble. creation_events: 0, //Total events which could trigger the bubble to be created. timer_events: 0, //Total number of events which would trigger on a timer. fx_events: 0 //Total number of events using fx effects that require a modification to the bubble. }, bubble_ghost: false, bubble_template: false }, events: false, initialize: function(options) { /** R U N S W H E N I N S T A N C E I S C R E A T E D **/ //Updates the options with any passed parameters. this.setOptions(options); //Create an array to hold the stack of events this.eventsArray = new Array(); //Create an array to hold events to be applied when the bubble is created. this.delayedEventsArray = new Array(); //Create an array to store the timers the class uses. this.timerArray = new Array(); //Create an array to store the timer flags. this.timerFlagsArray = new Array(); //Create and array to store the fx chain handlers. this.fxArray = new Array(); //The bubble can be disabled. If enabled is false, the bubble will cease to function. if (this.options.enabled) { //Call Internal Function: Set Document Properties this.set_document_properties(); //Call Internal Function: Calculate target Position this.calculate_target_position(); } }, newEvent: function (options) { //Store the event details to an array to process later this.eventsArray[this.eventsArray.length] = options; //If construct is true, then add as a creation event if (options.construct) { this.params.events.creation_events ++; } //If the event uses certain fx, then a flag needs to be set so additional divs can be added when the bubble is created. if (options.fx.kind && (options.fx.kind.toLowerCase() == "slide" || options.fx.kind.toLowerCase() == "morph")) { this.params.events.fx_events ++; } //Add one to the total events, this is a list of current events. this.params.events.total_events ++; //This increments as an event is added, but does not change if an event is removed, thus keeping values unique. this.params.events.created_events ++; options.unique_event_id = this.params.events.created_events; return options.unique_event_id; }, createEvent: function(options) { //These events trigger when the bubble is created. if (options.type == 'runtime') { if (options.run_event_now == true) { this.run_effect(options); } else { options.run_event_now = true; this.delayedEventsArray[this.delayedEventsArray.length] = options; } } //These events trigger on a timer. else if (options.type == 'timer') { var new_timer_ref = 'timer_' + options.unique_event_id; //Number of times to repeat the timer. if (options.countdown) { //If using a countdown the bubble must already be created. if (options.construct && this.params.alive == false) { this.construct(); } this.timerFlagsArray[new_timer_ref] = new Array(); var number_of_milliseconds = Math.round(options.timeout/1000) * 1000; options.timeout = 1000; this.timerFlagsArray[new_timer_ref]['countdown'] = true; this.timerFlagsArray[new_timer_ref]['timeout'] = options.timeout; this.timerFlagsArray[new_timer_ref]['countdown_start'] = number_of_milliseconds / 1000; this.timerFlagsArray[new_timer_ref]['countdown_remaining'] = number_of_milliseconds / 1000; this.timerFlagsArray[new_timer_ref]['stored_options'] = options; var time_remaining = this.timerFlagsArray[new_timer_ref]['countdown_remaining']; var countdown_area_html = '' + options.countdown.message_before + ''; countdown_area_html += '' + time_remaining + ''; countdown_area_html += '' + options.countdown.message_after + ''; var countdown_area = new Element('div',{ 'class':'countdown_area', 'id':this.options.bubble + '_countdown', 'html': countdown_area_html }); if (options.countdown.position == 'before') { $(countdown_area).inject($(this.options.bubble + '_inner_content'),'top'); } else { $(countdown_area).inject($(this.options.bubble + '_inner_content'),'bottom'); } } this.timerArray[new_timer_ref] = this.timeout.periodical(options.timeout, this, [new_timer_ref, options]); //Return the reference to the timer return new_timer_ref; } //There events trigger on a user action. else if (options.type == 'action') { if ($(options.target)) { //If a handler is supplied, its assumed this action is related to a timer. if(options.handler) { $(options.target).addEvent(options.event.action, function(e){ if (this.timerArray["timer_" + options.handler]) { $clear(this.timerArray["timer_" + options.handler]); } }.bind(this)) if (options.event.resume) { var new_timer_ref = "timer_" + options.handler; options.timeout = 1000; $(options.target).addEvent(options.event.resume, function(e){ this.timerArray[new_timer_ref] = this.timeout.periodical(options.timeout, this, [new_timer_ref, options]); }.bind(this)) } } else { $(options.target).addEvent(options.event.action, function(e){ e.stop(); //When the event fires trigger the creation of the bubble if it does not already exist. if (options.construct && this.params.alive == false) { this.construct(); } this.run_effect(options); }.bind(this)); } } else //The target for the event does not yet exist, store the event to be applied when the bubble is created. { this.delayedEventsArray[this.delayedEventsArray.length] = options; } } }, start: function(options) { /** S T A R T T H E B U B B L E **/ //Set the bubble as enabled, but activating the events. this.params.events.enabled = true; //If no creation events, automatically construct the bubble. if (this.params.events.creation_events == 0) { this.construct(); } //Now run events this.eventsArray.each(function(item){ this.createEvent(item); }.bind(this)) }, restart: function() { //The bubble can be disabled. If enabled is false, the bubble will cease to function. /* if (this.options.enabled) { $(this.options.bubble).setStyle('display','none'); //Call Internal Function: Set Document Properties this.set_document_properties(); //Call Internal Function: Calculate target Position this.calculate_target_position(); this.set_bubble_position(); this.params.alive = true; }*/ }, stop: function() { /** E N D T H E B U B B L E **/ //this.destruct(); }, construct: function() { /** C R E A T E S T H E B U B B L E **/ //Call Internal Function: Create Bubble this.create_bubble(); //Call Internal Function: Set Bubble Styles this.set_bubble_styles(); //Call Internal Function: Postion Bubble this.set_bubble_position(); this.params.alive = true; //If any events have been marked as using fx where an additional container is required, then apply it now. if (this.params.events.fx_events > 0) { this.params.fx_container = this.options.bubble + "_fx"; var new_container = new Element('div', {'id' : this.params.fx_container }) var temp_contents = $(this.options.bubble).get('html'); $(new_container).set('html',temp_contents ); $(this.options.bubble).set('html',''); $(new_container).inject(this.options.bubble,'top' ); } //Now run any events that can only be applied after the bubble is created. this.delayedEventsArray.each(function(item){ this.createEvent(item); }.bind(this)); //Run the oncomplete function if (this.options.onComplete) { this.options.onComplete(); } }, destruct: function() { /** D E S T R O Y S T H E B U B B L E **/ //Remove the bubble and store as a ghost. if(this.params.alive) { var temp_contents = $(this.options.bubble).clone(true,true); this.params.bubble_ghost = temp_contents.dispose(); $(this.options.bubble).setStyle('display','none'); this.params.alive = false; } } , set_document_properties: function() { /** S E T D O C U M E N T P R O P E R T I E S **/ this.params.window_width = window.getSize().x; this.params.window_height = window.getSize().y; var target_coordinates = $(this.options.target).getCoordinates(); this.params.target_width = target_coordinates.width; this.params.target_height = target_coordinates.height; this.params.target_x = target_coordinates.left; this.params.target_y = target_coordinates.top; }, calculate_target_position: function() { /** C A L C U L A T E T A R G E T P O S I T I O N **/ if (this.params.target_x > (this.params.window_width /2)) { this.params.target_relative_h = 'right'; } else { this.params.target_relative_h = 'left'; } if (this.params.target_y > (this.params.window_height /2)) { this.params.target_relative_v = 'bottom'; } else { this.params.target_relative_v = 'top'; } }, create_bubble: function() { /** C R E A T E B U B B L E **/ //Get current bubble contents, store and empty original container. if(this.params.bubble_template == false) { var bubble_contents = $(this.options.bubble).get('html'); this.params.bubble_template = bubble_contents } else { var bubble_contents = this.params.bubble_template; } $(this.options.bubble).set('html',''); //Add style class to bubble if supplied. if (this.options.style) { if(!$(this.options.bubble).hasClass(this.options.style)) { $(this.options.bubble).addClass(this.options.style); } } //Add new containers to bubble, and shove the contents into the inner container. var bubble_top = new Element('div',{'class':'bubble_top'}); var bubble_content = new Element('div',{'class':'bubble_content'}); var bubble_inner_content = new Element('div',{'class':'bubble_inner_content', 'id':this.options.bubble + '_inner_content'}); var bubble_bottom = new Element('div',{'class':'bubble_bottom'}); //If true add an icon for the close button. if(this.options.close_button.icon) { var close_btn = new Element('div',{'class':'close_button', 'id':this.options.bubble + '_close'}); //If action not false, then apply an action to the button. Set to false for more advanced actions. if (this.options.close_button.action) { close_btn.addEvent(this.options.close_button.action,function(){ $(this.options.bubble).setStyle('display','none'); }.bind(this)); } if (this.options.close_button.location == 'top') { var close_button_location = 'bubble_top'; } else if (this.options.close_button.location == 'middle' || this.options.close_button.location == 'content') { var close_button_location = 'bubble_inner_content'; } else if (this.options.close_button.location == 'bottom') { var close_button_location = 'bubble_bottom'; } else { var close_button_location = 'bubble_top'; } close_btn.inject(bubble_top,'top'); } bubble_inner_content.set('html', bubble_contents); bubble_inner_content.inject(bubble_content,'top'); bubble_bottom.inject($(this.options.bubble),'top'); bubble_content.inject($(this.options.bubble),'top'); bubble_top.inject($(this.options.bubble),'top'); }, set_bubble_styles: function() { /** S E T B U B B L E S T Y L E S **/ $(this.options.bubble).setStyle('position', 'absolute'); $(this.options.bubble).setStyle('display', 'block'); $(this.options.bubble).setStyle('z-index', 10); //Vertical if (this.params.target_relative_v =="top") { $$("#" + this.options.bubble + " .bubble_bottom").each(function(item){ item.addClass('flat'); }) $$("#" + this.options.bubble + " .bubble_top").each(function(item){ item.addClass('arrow'); }) } else { $$("#" + this.options.bubble + " .bubble_bottom").each(function(item){ item.addClass('arrow'); }) $$("#" + this.options.bubble + " .bubble_top").each(function(item){ item.addClass('flat'); }) } //Horizontal if (this.params.target_relative_h =="left") { $$("#" + this.options.bubble + " .bubble_bottom").each(function(item){ item.addClass('left'); }) $$("#" + this.options.bubble + " .bubble_top").each(function(item){ item.addClass('left'); }) $$("#" + this.options.bubble + " .bubble_content").each(function(item){ item.addClass('left'); }) } else { $$("#" + this.options.bubble + " .bubble_bottom").each(function(item){ item.addClass('right'); }) $$("#" + this.options.bubble + " .bubble_top").each(function(item){ item.addClass('right'); }) $$("#" + this.options.bubble + " .bubble_content").each(function(item){ item.addClass('right'); }) } }, set_bubble_position: function() { //Get bubble dimensions var bubble_coordinates = $(this.options.bubble).getCoordinates(); this.params.bubble_width = bubble_coordinates.width; this.params.bubble_height = bubble_coordinates.height; this.params.bubble_x = bubble_coordinates.left; this.params.bubble_y = bubble_coordinates.top; if(this.options.edge == "vertical") { if(this.params.target_relative_h == "right" && this.params.target_relative_v == "top") { if (this.options.position == 'corner') { $(this.options.bubble).setStyle('left', (((this.params.target_x + (this.params.target_width /2)) - this.params.bubble_width) + this.options.offset.x)); $(this.options.bubble).setStyle('top', (this.params.target_y + this.params.target_height + this.options.offset.y)); } else { $(this.options.bubble).setStyle('left', ((this.params.target_x - this.params.bubble_width) + this.options.offset.x)); var top = (this.params.target_y + (this.params.target_height/2) - (this.params.bubble_height/2) + this.options.offset.y); if (top < 0) { top=0; } if ((top + this.params.bubble_height) > this.params.window_height) { top = (this.params.window_height - this.params.bubble_height); } $(this.options.bubble).setStyle('top',top ); } } if(this.params.target_relative_h == "left" && this.params.target_relative_v == "top") { if (this.options.position == 'corner') { $(this.options.bubble).setStyle('left', (this.params.target_x + this.params.target_width + this.options.offset.x)); $(this.options.bubble).setStyle('top', (this.params.target_y + this.params.target_height + this.options.offset.y)); } else { $(this.options.bubble).setStyle('left', (this.params.target_x + this.params.target_width + this.options.offset.x)); var top = (this.params.target_y + (this.params.target_height/2) - (this.params.bubble_height/2) + this.options.offset.y); if (top < 0) { top=0; } if ((top + this.params.bubble_height) > this.params.window_height) { top = (this.params.window_height - this.params.bubble_height); } $(this.options.bubble).setStyle('top',top ); } } if(this.params.target_relative_h == "right" && this.params.target_relative_v == "bottom") { if (this.options.position == 'corner') { $(this.options.bubble).setStyle('left', (((this.params.target_x + (this.params.target_width /2)) - this.params.bubble_width) + this.options.offset.x)); var top = (this.params.target_y - this.params.bubble_height ) + this.options.offset.y; if (this.options.force_show == true && top > this.params.window_height) { top = this.params.window_height - this.params.bubble_height; } $(this.options.bubble).setStyle('top', top); } else { $(this.options.bubble).setStyle('left', ((this.params.target_x - this.params.bubble_width) + this.options.offset.x)); var top = (this.params.target_y + (this.params.target_height/2) - (this.params.bubble_height/2) + this.options.offset.y); if (top < 0) { top=0; } if ((top + this.params.bubble_height) > this.params.window_height) { top = (this.params.window_height - this.params.bubble_height); } $(this.options.bubble).setStyle('top',top ); } } if(this.params.target_relative_h == "left" && this.params.target_relative_v == "bottom") { if (this.options.position == 'corner') { $(this.options.bubble).setStyle('left', (((this.params.target_x + (this.params.target_width /2))) + this.options.offset.x)); var top = (this.params.target_y - this.params.bubble_height ) + this.options.offset.y; if (this.options.force_show == true && top > this.params.window_height) { top = this.params.window_height - this.params.bubble_height; } $(this.options.bubble).setStyle('top', top); } else { $(this.options.bubble).setStyle('left', (this.params.target_x + this.params.target_width + this.options.offset.x)); var top = (this.params.target_y + (this.params.target_height/2) - (this.params.bubble_height/2) + this.options.offset.y); if (top < 0) { top=0; } if ((top + this.params.bubble_height) > this.params.window_height) { top = (this.params.window_height - this.params.bubble_height); } $(this.options.bubble).setStyle('top',top ); } } } else //Else will apply as horizonal, choosing top or bottom based on basket position. { if(this.params.target_relative_h == "right" && this.params.target_relative_v == "top") { if (this.options.position == 'corner') { $(this.options.bubble).setStyle('left', (((this.params.target_x + (this.params.target_width /2)) - this.params.bubble_width) + this.options.offset.x)); $(this.options.bubble).setStyle('top', (this.params.target_y + this.params.target_height + this.options.offset.y)); } else { $(this.options.bubble).setStyle('left', (((this.params.target_x + (this.params.target_width /2)) - (this.params.bubble_width/2)) + this.options.offset.x)); $(this.options.bubble).setStyle('top', (this.params.target_y + this.params.target_height + this.options.offset.y)); } } if(this.params.target_relative_h == "left" && this.params.target_relative_v == "top") { if (this.options.position == 'corner') { $(this.options.bubble).setStyle('left', (((this.params.target_x + (this.params.target_width /2))) + this.options.offset.x)); $(this.options.bubble).setStyle('top', (this.params.target_y + this.params.target_height + this.options.offset.y)); } else { $(this.options.bubble).setStyle('left', (((this.params.target_x + (this.params.target_width /2)) - (this.params.bubble_width/2)) + this.options.offset.x)); $(this.options.bubble).setStyle('top', (this.params.target_y + this.params.target_height + this.options.offset.y)); } } if(this.params.target_relative_h == "right" && this.params.target_relative_v == "bottom") { if (this.options.position == 'corner') { $(this.options.bubble).setStyle('left', (((this.params.target_x + (this.params.target_width /2)) - this.params.bubble_width) + this.options.offset.x)); var top = (this.params.target_y - this.params.bubble_height ) + this.options.offset.y; if (this.options.force_show == true && top > this.params.window_height) { top = this.params.window_height - this.params.bubble_height; } $(this.options.bubble).setStyle('top', top); } else { $(this.options.bubble).setStyle('left', (((this.params.target_x + (this.params.target_width /2)) - (this.params.bubble_width/2)) + this.options.offset.x)); var top = (this.params.target_y - this.params.bubble_height) + this.options.offset.y; if (this.options.force_show == true && top > this.params.window_height) { top = this.params.window_height - this.params.bubble_height; } $(this.options.bubble).setStyle('top', top); } } if(this.params.target_relative_h == "left" && this.params.target_relative_v == "bottom") { if (this.options.position == 'corner') { $(this.options.bubble).setStyle('left', (((this.params.target_x + (this.params.target_width /2))) + this.options.offset.x)); var top = (this.params.target_y - this.params.bubble_height ) + this.options.offset.y; if (this.options.force_show == true && top > this.params.window_height) { top = this.params.window_height - this.params.bubble_height; } $(this.options.bubble).setStyle('top', top); } else { $(this.options.bubble).setStyle('left', ((this.params.target_x + (this.params.target_width /2)) - (this.params.bubble_width/2) + this.options.offset.x)); var top = (this.params.target_y - this.params.bubble_height ) + this.options.offset.y; if (this.options.force_show == true && top > this.params.window_height) { top = this.params.window_height - this.params.bubble_height; } $(this.options.bubble).setStyle('top', top); } } } }, timeout: function(timer_ref, options) { //Treat as a repeating timer until the timeout expires if (this.timerFlagsArray[timer_ref]['countdown'] == true) { this.timerFlagsArray[timer_ref]['countdown_remaining'] --; if (this.timerFlagsArray[timer_ref]['countdown_remaining'] < 1) { $clear(this.timerArray[timer_ref]); this.run_effect(this.timerFlagsArray[timer_ref]['stored_options']); } else { $(this.options.bubble + "_countdown_value").set('html', this.timerFlagsArray[timer_ref]['countdown_remaining']); } } else //Otherwise run once then expire. { $clear(this.timerArray[timer_ref]); this.run_effect(options); } }, run_effect: function(options) { if (options.fx) //Only produce fx if passed. { if (options.fx.chain) { var entry_id = options.fx.chain; } else { var entry_id = options.unique_event_id; } if(options.fx.kind == 'clear') //Clear effects and effect delays { //If delay is passed, then clear the delay. if (options.fx.delay) { if (options.fx.delay[0]) { $each(options.fx.delay, function(value, text){ $clear(this.timerArray[value]); }.bind(this)); } else { $clear(this.timerArray[options.fx.delay]); } } if (options.fx.chain) { this.fxArray[options.fx.chain].cancel(); } } else if(options.fx.kind == 'fade') //Choose type of effect. { if (!options.fx.settings) { options.fx.settings = 'out'; } $(this.options.bubble).fade(options.fx.settings); } else if (options.fx.kind == 'slide') { //Quick params for bubble width and height var height = this.params.bubble_height; var width = this.params.bubble_width; //Add a wrapper div to replicate the slide wrapper. var parent = $(this.params.fx_container).getParent(); if($(parent).get('class') != "wrapper") { var temp_html = $(parent).get("html"); $(parent).set("html",""); var wrapper = new Element('div',{'class':'wrapper', 'styles': { 'width':width,'height':height, 'overflow':'hidden'}}) wrapper.set('html', temp_html); wrapper.inject(parent, 'top'); } //Use a custom morth to replicate a slide. if (!options.fx.chain) //If not chained create a new effect { this.fxArray[entry_id] = new Fx.Morph($(this.params.fx_container),options.fx.settings); this.fxArray[entry_id].wrapper = wrapper; } /* else { $each(options.fx.settings, function(value, text){ this.fxArray[entry_id].set(text,value); }.bind(this)); } */ if (options.fx.method) { if (options.fx.method == "in") { var fx_function = function(options) { //Custom rule to adjust slide when in side_container. if (this.options.location == 'side_container') { if (this.params.target_relative_h == "left") { $(this.options.bubble).setStyle('width', width); this.fxArray[entry_id].wrapper.setStyle('width', width); this.fxArray[entry_id].start({ 'margin-left': [0] }); } else { $(this.options.bubble).setStyle('width', width); this.fxArray[entry_id].wrapper.setStyle('width', width); this.fxArray[entry_id].start({ 'margin-left': [0] }); } } else { $(this.options.bubble).setStyle('width', width); this.fxArray[entry_id].wrapper.setStyle('width', width); this.fxArray[entry_id].start({ 'margin-top': [0] }); } }.bind(this) } else if (options.fx.method == "out") { var fx_function = function(options) { //Custom rule to adjust slide when in side_container. if (this.options.location == 'side_container') { if (this.params.target_relative_h == "left") { this.fxArray[entry_id].start({ 'margin-left': [(width*-1)] }).chain(function(){ this.fxArray[entry_id].wrapper.setStyle('width', 0); $(this.options.bubble).setStyle('width', 0); }.bind(this)); } else { this.fxArray[entry_id].start({ 'margin-left': [(width)] }).chain(function(){ this.fxArray[entry_id].wrapper.setStyle('width', 0); $(this.options.bubble).setStyle('width', 0); }.bind(this)); } } else { this.fxArray[entry_id].start({ 'margin-top': [(height*-1)] }).chain(function(){ this.fxArray[entry_id].wrapper.setStyle('width', 0); $(this.options.bubble).setStyle('width', 0); }.bind(this)); } }.bind(this) } else if (options.fx.method == "toggle") { //Add function when needed. } else if (options.fx.method == "hide") { var fx_function = function(options) { if (this.options.location == 'side_container') { if (this.params.target_relative_h == "left") { $(this.params.fx_container).setStyle("margin-left", (width*-1)); } else { $(this.params.fx_container).setStyle("margin-left", (width)); } } else { $(this.params.fx_container).setStyle("margin-top", (height*-1)); } }.bind(this) } else if (options.fx.method == "show") { var fx_function = function(options) { if (this.options.location == 'side_container') { if (this.params.target_relative_h == "left") { $(this.params.fx_container).setStyle("margin-left", 0); } else { $(this.params.fx_container).setStyle("margin-left", 0); } } else { $(this.params.fx_container).setStyle("margin-top", 0); } }.bind(this) } if (options.fx.delay) { this.timerArray[options.unique_event_id] = fx_function.delay(options.fx.delay,this,options); } else { fx_function(); } } } } //If destruct is set to true, destroy the bubble after the effect has run. /* if (options.destruct) { this.destruct(); } */ } }); /** -- M O O B U B B L E -- **/ /** -- S C R O L L E R -- **/ /* This script and many more are available free online at The JavaScript Source!! http://javascript.internet.com Created by: Mr J | http://www.huntingground.net/ */ scrollStep=3; timerUp=""; timerDown=""; function toTop(id) { document.getElementById(id).scrollTop=0; } function scrollDivDown(id) { clearTimeout(timerDown); document.getElementById(id).scrollTop+=scrollStep; timerDown=setTimeout("scrollDivDown('"+id+"')",10); } function scrollDivUp(id) { clearTimeout(timerUp); document.getElementById(id).scrollTop-=scrollStep; timerUp=setTimeout("scrollDivUp('"+id+"')",10); } function toBottom(id) { document.getElementById(id).scrollTop=document.getElementById(id).scrollWidth; } function stopMe() { clearTimeout(timerDown); clearTimeout(timerUp); } /** // S C R O L L E R // **/ /** -- B A S K E T A T T R I B U T E S -- **/ // JavaScript Document function auto_slide_elements(activator, target) { if(typeof window.basket_attributes_link_show !="undefined") { var link_label = window.basket_attributes_link_show; } else { var link_label = 'Show Details'; } $$("." + target).each(function(item){ var slider = new Fx.Slide(item); slider.hide(); var head_id = item.get("id"); var head_id_parts = head_id.split("_"); var record_id = head_id_parts[2]; var link_content = '(' + link_label + ')'; $("show_hide_" + record_id).set("html",link_content); $('show_hide_link_' + record_id).addEvent('click', function(e){ e.stop(); slider.toggle(); update_link(record_id,slider.open); }); }) } function update_link(record_id, state) { if(!state) { if(typeof window.basket_attributes_link_hide !="undefined") { var link_content = window.basket_attributes_link_hide; } else { var link_content = 'Hide Details'; } $("show_hide_link_" + record_id).set("html",link_content); } else { if(typeof window.basket_attributes_link_show !="undefined") { var link_content = window.basket_attributes_link_show; } else { var link_content = 'Show Details'; } $("show_hide_link_" + record_id).set("html",link_content); } } /** -- B A S K E T A T T R I B U T E S -- **/ /** -- M I S C I L A N E O U S -- **/ // JavaScript Document var form='form'; function SetChecked(val,chkName) { dml=document.forms[form]; len = dml.elements.length; var i=0; for( i=0 ; i 0) { var previous_dropdown = dropdown_name + previous_dropdown_number; if( $(previous_dropdown) ) { new_cat_choosen = $(previous_dropdown).options[$(previous_dropdown).selectedIndex].value; } } } if(typeof(window.product_drop_down) != "undefined" && window.product_drop_down == true) { if($("selected_product")) { $("selected_product").value = ""; } var ajax = new ajax_file(); ajax.initialize(); ajax.asynchronous = true; var choose = document.createElement("option"); choose.setAttribute("value", "choose"); choose.innerHTML = "...Loading..."; var product_drop_down_name = next_dropdown_id.match("[a-z_-]*") + "product"; $(product_drop_down_name).innerHTML = ""; $(product_drop_down_name).appendChild(choose); $(product_drop_down_name).disabled = true; response = ajax.get_content(absolute_address_server + "elements/category/subcategory_details.html", "category=" + category_id + "&get_products", "update_category_box(my_response, '" + product_drop_down_name + "', '" + window.product_drop_down_label + "'); "); } // RESET INPUT "cat[]"; for set it with the new category selected //$("drop_downs_list").removeChild( $("selected_category") ); // creating selected_category div // var div_selected_category = document.createElement("div"); // div_selected_category.setAttribute("id", "selected_category"); // $("drop_downs_list").appendChild(div_selected_category); // var selected_category_input = document.createElement("input"); // selected_category_input.setAttribute("type","hidden"); // selected_category_input.setAttribute("name","cat[]"); // selected_category_input.setAttribute("value",new_cat_choosen); //$("selected_category").appendChild(selected_category_input); if( $("selected_category") ) { $("selected_category").value = new_cat_choosen; } if( $("selected_category_module") ) { $("selected_category_module").value = new_cat_choosen; } } function populate_dropdown(category_list, dropdown_id, dropdowns_label) { html = ''; $(dropdown_id).innerHTML = ""; if(!dropdowns_label || dropdowns_label == 'undefined') { dropdowns_label = "- Choose -"; } var choose = document.createElement("option"); choose.setAttribute("value", "choose"); choose.innerHTML = dropdowns_label; $(dropdown_id).appendChild(choose); for(var counter=0; counter < category_list.length; counter++) { var option = document.createElement("option"); option.setAttribute("value", category_list[counter][0]); option.setAttribute("class", category_list[counter][0]); option.innerHTML = category_list[counter][1]; $(dropdown_id).appendChild(option); } $(dropdown_id).disabled = false; } function clear_dropdowns(dropdown_id, dropdowns_label) { var drop_down_number = dropdown_id.match("[0-9]+") * 1; var drop_down_name = dropdown_id.match("[a-z_-]*"); if(typeof(dropdowns_label) == "undefined") { var dropdowns_label = ""; } if(drop_down_number) { for(var counter = drop_down_number; counter <= number_of_drop_downs; counter++) { if($(drop_down_name + counter)) { $(drop_down_name + counter).innerHTML = ''; $(drop_down_name + counter).disabled = true; } } } else { $(dropdown_id).innerHTML = ''; $(dropdown_id).disabled = true; } } //END: NEW DROP DOWNS CATEGORIES SYSTEM //END: NEW DROP DOWNS CATEGORIES SYSTEM //END: NEW DROP DOWNS CATEGORIES SYSTEM /* function decode_des(text) { //alert(text); text = text.replace("©", "©"); text = text.replace(">", ">"); text = text.replace("<", "<"); text = text.replace("ª", "¬"); text = text.replace("&", "&"); text = text.replace(" ", " "); text = text.replace(""", """); text = text.replace("£", "£"); //alert(text); return text; } function addOnChange(obj, drop_down_number) { obj.onchange = function() { update_drop_down(drop_down_number, this.value); }; } function update_drop_down(drop_down_to_update, ref_value) { // REMOVE OPTIONS; in those drop downs that follows the drop down to be updated var drop_down_number = drop_down_to_update; for(drop_down_number; drop_down_number <= number_of_drop_downs; drop_down_number++) { document.getElementById("drop_down_"+drop_down_number).options.length = 1; } // FINDING SUBTREE; going trough category_tree_array finding the subtree position var temp_array = category_tree_array; var cat_path; ref_value_arr = ref_value.split("-"); //alert(ref_value); //alert(ref_value_arr); for(var key = 0; key < ref_value_arr.length; key++) { cat_path = ref_value_arr[key]; temp_array = temp_array[cat_path]; } // RESET INPUT "cat[]"; for set it with the new category selected document.getElementById("drop_downs_list").removeChild( document.getElementById("selected_category") ); // creating selected_category div div_selected_category = document.createElement("div"); div_selected_category.setAttribute("id", "selected_category"); document.getElementById("drop_downs_list").appendChild(div_selected_category); var selected_category_input = document.createElement("input"); selected_category_input.setAttribute("type","hidden"); selected_category_input.setAttribute("name","cat[]"); selected_category_input.setAttribute("value",temp_array[0][0]); document.getElementById("selected_category").appendChild(selected_category_input); temp_array = temp_array[1]; //FILLING DROP DOWN var my_drop_down = document.getElementById("drop_down_"+drop_down_to_update); for(var key = 1; key < temp_array.length; key++) { if(typeof(temp_array[key][0]) != 'undefined') { drop_down_option = document.createElement('option'); drop_down_option.text = temp_array[key][0][1]; drop_down_option.value = ref_value+"-1-"+key; try { my_drop_down.add(drop_down_option, null); // standards compliant; doesn't work in IE } catch(ex) { my_drop_down.add(drop_down_option); // IE only } } } } // creating drop downs, from number_of_drop_downs global variable function create_drop_downs(text_string, drop_downs_div_id, drop_down_box_style, text_box_style, input_box_style, select_box_style) { //alert(category_tree_array[10][1][0][1]); //creating the first drop down var number = 1; var drop_down_to_update; // creating drop_down div var div_drop_down = document.createElement("div"); div_drop_down.className = drop_down_box_style; // creating text div var div_text = document.createElement("div"); div_text.className = text_box_style; div_text.innerHTML = text_string; div_drop_down.appendChild(div_text); // creating input_box div var div_input_box = document.createElement("div"); div_input_box.className = input_box_style; div_drop_down.appendChild(div_input_box); first_drop_down = document.createElement('select'); first_drop_down.id = "drop_down_" + number; first_drop_down.className = select_box_style; drop_down_to_update = number + 1; addOnChange(first_drop_down, drop_down_to_update); drop_down_option = document.createElement('option'); drop_down_option.text = "- Select -"; try { first_drop_down.add(drop_down_option, null); // standards compliant; doesn't work in IE } catch(ex) { first_drop_down.add(drop_down_option); // IE only } // filling the first drop down with the main categories; taken from category_tree_array for(var key = 1; key < category_tree_array.length; key++) //for(key in category_tree_array) { drop_down_option = document.createElement('option'); if(typeof(category_tree_array[key][0]) != 'undefined') { drop_down_option.text = category_tree_array[key][0][1]; drop_down_option.value = key; try { first_drop_down.add(drop_down_option, null); // standards compliant; doesn't work in IE } catch(ex) { first_drop_down.add(drop_down_option); // IE only } } } div_input_box.appendChild(first_drop_down); document.getElementById(drop_downs_div_id).appendChild(div_drop_down); number++; // creating the drop downs left (empty drop downs) for(drop_down_number = number; drop_down_number <= number_of_drop_downs; drop_down_number++) { // creating drop_down div div_drop_down = document.createElement("div"); div_drop_down.className = drop_down_box_style; // creating text div div_text = document.createElement("div"); div_text.className = text_box_style; div_text.innerHTML = text_string; div_drop_down.appendChild(div_text); // creating input_box div div_input_box = document.createElement("div"); div_input_box.className = input_box_style; div_drop_down.appendChild(div_input_box); new_drop_down = document.createElement('select'); new_drop_down.id = "drop_down_" + drop_down_number; new_drop_down.className = select_box_style; drop_down_to_update = drop_down_number + 1; //new_drop_down.setAttribute("onchange","update_drop_down("+drop_down_to_update+", this.value)"); addOnChange(new_drop_down, drop_down_to_update); drop_down_option = document.createElement('option'); drop_down_option.text = "- Select -"; try { new_drop_down.add(drop_down_option, null); // standards compliant; doesn't work in IE } catch(ex) { new_drop_down.add(drop_down_option); // IE only } div_input_box.appendChild(new_drop_down); document.getElementById(drop_downs_div_id).appendChild(div_drop_down); } } */ /** -- C A T E G O R Y D R O P D O W N S -- **/ /** -- F A U X O V E R I D E -- **/ // JavaScript Document function faux_override(target, content, content_js) { $$(target).each(function(item){ item.getElements(content).each(function(item) { item.removeClass(content.substr(1)); item.addClass(content_js.substr(1)); }); item.addEvent('click', function(){ this.getElements(content_js).each(function(item) { item.removeClass(content_js.substr(1)); item.addClass(content.substr(1)); item.addEvent('mouseleave', function(){ item.removeClass(content.substr(1)); item.addClass(content_js.substr(1)); }); }); }) item.addEvent('mouseleave', function(){ this.getElements(target).each(function(item) { item.removeClass(content.substr(1)); item.addClass(content_js.substr(1)); }); }) }) } /** -- F A U X O V E R I D E -- **/ /** -- R E A L T I M E S E A R C H -- **/ function product_search(search_term, target) { var ajax = new ajax_file(); ajax.initialize(); ajax.asynchronous = true; response = ajax.get_content(absolute_address_server + "elements/product/product_search.html", "search=" + search_term, "populate_product_search(my_response, '" + target + "'); "); } function populate_product_search(search_result, target) { if(typeof(populate_product_search_overide) == "function") { populate_product_search_overide(search_result, target); } else { if(search_result) { search_result = eval(search_result); var html = "
"; if(typeof(search_result[1][0][0]) != "undefined") { for(var counter=0; counter < search_result[1].length; counter++) { html += "" + ""; } } html += '
'; $(target).innerHTML = html; } } } /** -- R E A L T I M E S E A R C H -- **/ /** -- A J A X F I L E -- **/ // Javascript var ajax_file = new Class( { asynchronous: false, connection : null, initialize : function() { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari this.connection = new XMLHttpRequest(); } else if (window.ActiveXObject) { // code for IE6, IE5 this.connection = new ActiveXObject("Microsoft.XMLHTTP"); } else { alert("Your browser does not support XMLHTTP!"); } }, get_content : function(url, params, command) { if (this.connection) { if(this.asynchronous) { var my_connection = this.connection; this.connection.onreadystatechange=function() { if(my_connection.readyState==4) { my_response = my_connection.responseText; eval(command); } } this.connection.open("GET", url + "?" + params,true); return this.connection.send(null); } else { this.connection.open("GET", url + "?" + params, false); this.connection.send(null); return this.connection.responseText; } } else { return false; } }, post_content : function(url, params, command) { if (this.connection) { if(this.asynchronous) { var my_connection = this.connection; this.connection.onreadystatechange=function() { if(my_connection.readyState==4) { my_response = my_connection.responseText; eval(command); } } this.connection.open("POST", url, true); this.connection.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); this.connection.setRequestHeader("Content-length", params.length); this.connection.setRequestHeader("Connection", "close"); return this.connection.send(params); } else { this.connection.open("POST", url, false); this.connection.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); this.connection.setRequestHeader("Content-length", params.length); this.connection.setRequestHeader("Connection", "close"); this.connection.send(params); return this.connection.responseText; } } else { return false; } } }); /** -- A J A X F I L E -- **/ var absolute_address_server = 'https://m.cameraexchangestore.co.uk/'; function clear_search(){ $('result_area').setStyle('display','none'); $('close_button').setStyle('display','none'); $('search').set('value',''); } function show_close(){ $('result_area').setStyle('display','block'); $('close_button').setStyle('display','block'); } window.addEvent('domready', function() { var site_menu = new Fx.Slide('site_menu'); site_menu.hide(); $('site_menu').removeClass("start_hidden"); $('menu_link').addEvent('click', function(event){ event.stop(); site_menu.toggle(); return false; }); }); /** -- S P R Y T E X T -- **/ // SpryValidationTextField.js - version 0.37 - Spry Pre-Release 1.6.1 // // Copyright (c) 2006. Adobe Systems Incorporated. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Adobe Systems Incorporated nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. var Spry; if (!Spry) Spry = {}; if (!Spry.Widget) Spry.Widget = {}; Spry.CustomValidation = {}; Spry.OriginalError = {}; Spry.Widget.BrowserSniff = function() { var b = navigator.appName.toString(); var up = navigator.platform.toString(); var ua = navigator.userAgent.toString(); this.mozilla = this.ie = this.opera = this.safari = false; var re_opera = /Opera.([0-9\.]*)/i; var re_msie = /MSIE.([0-9\.]*)/i; var re_gecko = /gecko/i; var re_safari = /(applewebkit|safari)\/([\d\.]*)/i; var r = false; if ( (r = ua.match(re_opera))) { this.opera = true; this.version = parseFloat(r[1]); } else if ( (r = ua.match(re_msie))) { this.ie = true; this.version = parseFloat(r[1]); } else if ( (r = ua.match(re_safari))) { this.safari = true; this.version = parseFloat(r[2]); } else if (ua.match(re_gecko)) { var re_gecko_version = /rv:\s*([0-9\.]+)/i; r = ua.match(re_gecko_version); this.mozilla = true; this.version = parseFloat(r[1]); } this.windows = this.mac = this.linux = false; this.Platform = ua.match(/windows/i) ? "windows" : (ua.match(/linux/i) ? "linux" : (ua.match(/mac/i) ? "mac" : ua.match(/unix/i)? "unix" : "unknown")); this[this.Platform] = true; this.v = this.version; if (this.safari && this.mac && this.mozilla) { this.mozilla = false; } }; Spry.is = new Spry.Widget.BrowserSniff(); Spry.Widget.ValidationTextField = function(element, type, options, custom_validation) { type = Spry.Widget.Utils.firstValid(type, "none"); if (typeof type != 'string') { this.showError('The second parameter in the constructor should be the validation type, the options are the third parameter.'); return; } if (typeof Spry.Widget.ValidationTextField.ValidationDescriptors[type] == 'undefined') { this.showError('Unknown validation type received as the second parameter.'); return; } options = Spry.Widget.Utils.firstValid(options, {}); this.type = type; if (!this.isBrowserSupported()) { //disable character masking and pattern behaviors for low level browsers options.useCharacterMasking = false; } this.init(element, options); Spry.CustomValidation[element] = custom_validation; //make sure we validate at least on submit var validateOn = ['submit'].concat(Spry.Widget.Utils.firstValid(this.options.validateOn, [])); validateOn = validateOn.join(","); this.validateOn = 0; this.validateOn = this.validateOn | (validateOn.indexOf('submit') != -1 ? Spry.Widget.ValidationTextField.ONSUBMIT : 0); this.validateOn = this.validateOn | (validateOn.indexOf('blur') != -1 ? Spry.Widget.ValidationTextField.ONBLUR : 0); this.validateOn = this.validateOn | (validateOn.indexOf('change') != -1 ? Spry.Widget.ValidationTextField.ONCHANGE : 0); if (Spry.Widget.ValidationTextField.onloadDidFire) this.attachBehaviors(); else Spry.Widget.ValidationTextField.loadQueue.push(this); }; Spry.Widget.ValidationTextField.ONCHANGE = 1; Spry.Widget.ValidationTextField.ONBLUR = 2; Spry.Widget.ValidationTextField.ONSUBMIT = 4; Spry.Widget.ValidationTextField.ERROR_REQUIRED = 1; Spry.Widget.ValidationTextField.ERROR_FORMAT = 2; Spry.Widget.ValidationTextField.ERROR_RANGE_MIN = 4; Spry.Widget.ValidationTextField.ERROR_RANGE_MAX = 8; Spry.Widget.ValidationTextField.ERROR_CHARS_MIN = 16; Spry.Widget.ValidationTextField.ERROR_CHARS_MAX = 32; /* validation parameters: * - characterMasking : prevent typing of characters not matching an regular expression * - regExpFilter : additional regular expression to disalow typing of characters * (like the "-" sign in the middle of the value); use for partial matching of the currently typed value; * the typed value must match regExpFilter at any moment * - pattern : enforce character on each position inside a pattern (AX0?) * - validation : function performing logic validation; return false if failed and the typedValue value on success * - minValue, maxValue : range validation; check if typedValue inside the specified range * - minChars, maxChars : value length validation; at least/at most number of characters * */ Spry.Widget.ValidationTextField.ValidationDescriptors = { 'none': { }, 'custom': { }, 'integer': { characterMasking: /[\-\+\d]/, regExpFilter: /^[\-\+]?\d*$/, validation: function(value, options) { if (value == '' || value == '-' || value == '+') { return false; } var regExp = /^[\-\+]?\d*$/; if (!regExp.test(value)) { return false; } options = options || {allowNegative:false}; var ret = parseInt(value, 10); if (!isNaN(ret)) { var allowNegative = true; if (typeof options.allowNegative != 'undefined' && options.allowNegative == false) { allowNegative = false; } if (!allowNegative && value < 0) { ret = false; } } else { ret = false; } return ret; } }, 'real': { characterMasking: /[\d\.,\-\+e]/i, regExpFilter: /^[\-\+]?\d(?:|\.,\d{0,2})|(?:|e{0,1}[\-\+]?\d{0,})$/i, validation: function (value, options) { var regExp = /^[\+\-]?[0-9]+([\.,][0-9]+)?([eE]{0,1}[\-\+]?[0-9]+)?$/; if (!regExp.test(value)) { return false; } var ret = parseFloat(value); if (isNaN(ret)) { ret = false; } return ret; } }, 'currency': { formats: { 'dot_comma': { characterMasking: /[\d\.\,\-\+\$]/, regExpFilter: /^[\-\+]?(?:[\d\.]*)+(|\,\d{0,2})$/, validation: function(value, options) { var ret = false; //2 or no digits after the comma if (/^(\-|\+)?\d{1,3}(?:\.\d{3})*(?:\,\d{2}|)$/.test(value) || /^(\-|\+)?\d+(?:\,\d{2}|)$/.test(value)) { value = value.toString().replace(/\./gi, '').replace(/\,/, '.'); ret = parseFloat(value); } return ret; } }, 'comma_dot': { characterMasking: /[\d\.\,\-\+\$]/, regExpFilter: /^[\-\+]?(?:[\d\,]*)+(|\.\d{0,2})$/, validation: function(value, options) { var ret = false; //2 or no digits after the comma if (/^(\-|\+)?\d{1,3}(?:\,\d{3})*(?:\.\d{2}|)$/.test(value) || /^(\-|\+)?\d+(?:\.\d{2}|)$/.test(value)) { value = value.toString().replace(/\,/gi, ''); ret = parseFloat(value); } return ret; } } } }, 'email': { characterMasking: /[^\s]/, validation: function(value, options) { var rx = /^[\w\.-]+@[\w\.-]+\.\w+$/i; return rx.test(value); } }, 'date': { validation: function(value, options) { var formatRegExp = /^([mdy]+)[\.\-\/\\\s]+([mdy]+)[\.\-\/\\\s]+([mdy]+)$/i; var valueRegExp = this.dateValidationPattern; var formatGroups = options.format.match(formatRegExp); var valueGroups = value.match(valueRegExp); if (formatGroups !== null && valueGroups !== null) { var dayIndex = -1; var monthIndex = -1; var yearIndex = -1; for (var i=1; i 12) { return false; } // Calculate the maxDay according to the current month switch (theMonth) { case 1: // January case 3: // March case 5: // May case 7: // July case 8: // August case 10: // October case 12: // December maxDay = 31; break; case 4: // April case 6: // June case 9: // September case 11: // November maxDay = 30; break; case 2: // February if ((parseInt(theYear/4, 10) * 4 == theYear) && (theYear % 100 != 0 || theYear % 400 == 0)) { maxDay = 29; } else { maxDay = 28; } break; } // Check day value to be between 1..maxDay if (theDay < 1 || theDay > maxDay) { return false; } // If successfull we'll return the date object return (new Date(theYear, theMonth - 1, theDay)); //JavaScript requires a month between 0 and 11 } } else { return false; } } }, 'time': { validation: function(value, options) { // HH:MM:SS T var formatRegExp = /([hmst]+)/gi; var valueRegExp = /(\d+|AM?|PM?)/gi; var formatGroups = options.format.match(formatRegExp); var valueGroups = value.match(valueRegExp); //mast match and have same length if (formatGroups !== null && valueGroups !== null) { if (formatGroups.length != valueGroups.length) { return false; } var hourIndex = -1; var minuteIndex = -1; var secondIndex = -1; //T is AM or PM var tIndex = -1; var theHour = 0, theMinute = 0, theSecond = 0, theT = 'AM'; for (var i=0; i (formatGroups[hourIndex] == 'HH' ? 23 : 12 )) { return false; } } if (minuteIndex != -1) { var theMinute = parseInt(valueGroups[minuteIndex], 10); if (isNaN(theMinute) || theMinute > 59) { return false; } } if (secondIndex != -1) { var theSecond = parseInt(valueGroups[secondIndex], 10); if (isNaN(theSecond) || theSecond > 59) { return false; } } if (tIndex != -1) { var theT = valueGroups[tIndex].toUpperCase(); if ( formatGroups[tIndex].toUpperCase() == 'TT' && !/^a|pm$/i.test(theT) || formatGroups[tIndex].toUpperCase() == 'T' && !/^a|p$/i.test(theT) ) { return false; } } var date = new Date(2000, 0, 1, theHour + (theT.charAt(0) == 'P'?12:0), theMinute, theSecond); return date; } else { return false; } } }, 'credit_card': { characterMasking: /\d/, validation: function(value, options) { var regExp = null; options.format = options.format || 'ALL'; switch (options.format.toUpperCase()) { case 'ALL': regExp = /^[3-6]{1}[0-9]{12,18}$/; break; case 'VISA': regExp = /^4(?:[0-9]{12}|[0-9]{15})$/; break; case 'MASTERCARD': regExp = /^5[1-5]{1}[0-9]{14}$/; break; case 'AMEX': regExp = /^3(4|7){1}[0-9]{13}$/; break; case 'DISCOVER': regExp = /^6011[0-9]{12}$/; break; case 'DINERSCLUB': regExp = /^3(?:(0[0-5]{1}[0-9]{11})|(6[0-9]{12})|(8[0-9]{12}))$/; break; } if (!regExp.test(value)) { return false; } var digits = []; var j = 1, digit = ''; for (var i = value.length - 1; i >= 0; i--) { if ((j%2) == 0) { digit = parseInt(value.charAt(i), 10) * 2; digits[digits.length] = digit.toString().charAt(0); if (digit.toString().length == 2) { digits[digits.length] = digit.toString().charAt(1); } } else { digit = value.charAt(i); digits[digits.length] = digit; } j++; } var sum = 0; for(i=0; i < digits.length; i++ ) { sum += parseInt(digits[i], 10); } if ((sum%10) == 0) { return true; } return false; } }, 'zip_code': { formats: { 'zip_us9': { pattern:'00000-0000' }, 'zip_us5': { pattern:'00000' }, 'zip_uk': { characterMasking: /[\dA-Z\s]/, validation: function(value, options) { //check one of the following masks // AN NAA, ANA NAA, ANN NAA, AAN NAA, AANA NAA, AANN NAA return /^[A-Z]{1,2}\d[\dA-Z]?\s?\d[A-Z]{2}$/.test(value); } }, 'zip_canada': { characterMasking: /[\dA-Z\s]/, pattern: 'A0A 0A0' }, 'zip_custom': {} } }, 'phone_number': { formats: { //US phone number; 10 digits 'phone_us': { pattern:'(000) 000-0000' }, 'phone_custom': {} } }, 'social_security_number': { pattern:'000-00-0000' }, 'ip': { characterMaskingFormats: { 'ipv4': /[\d\.]/i, 'ipv6_ipv4': /[\d\.\:A-F\/]/i, 'ipv6': /[\d\.\:A-F\/]/i }, validation: function (value, options) { return Spry.Widget.ValidationTextField.validateIP(value, options.format); } }, 'url': { characterMasking: /[^\s]/, validation: function(value, options) { //fix for ?ID=223429 and ?ID=223387 /* the following regexp matches components of an URI as specified in http://tools.ietf.org/html/rfc3986#page-51 page 51, Appendix B. scheme = $2 authority = $4 path = $5 query = $7 fragment = $9 */ var URI_spliter = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/; var parts = value.match(URI_spliter); if (parts && parts[4]) { //encode each component of the domain name using Punycode encoding scheme: http://tools.ietf.org/html/rfc3492 var host = parts[4].split("."); var punyencoded = ''; for (var i=0; i 1080::8:800:200C:417A FF01:0:0:0:0:0:0:101 --> FF01::101 0:0:0:0:0:0:0:1 --> ::1 0:0:0:0:0:0:0:0 --> :: 2.5.4 IPv6 Addresses with Embedded IPv4 Addresses IPv4-compatible IPv6 address (tunnel IPv6 packets over IPv4 routing infrastructures) ::0:129.144.52.38 IPv4-mapped IPv6 address (represent the addresses of IPv4-only nodes as IPv6 addresses) ::ffff:129.144.52.38 The text representation of IPv6 addresses and prefixes in Augmented BNF (Backus-Naur Form) [ABNF] for reference purposes. [ABNF http://tools.ietf.org/html/rfc2234] IPv6address = hexpart [ ":" IPv4address ] IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT IPv6prefix = hexpart "/" 1*2DIGIT hexpart = hexseq | hexseq "::" [ hexseq ] | "::" [ hexseq ] hexseq = hex4 *( ":" hex4) hex4 = 1*4HEXDIG */ Spry.Widget.ValidationTextField.validateIP = function (value, format) { var validIPv6Addresses = [ //preferred /^(?:[a-f0-9]{1,4}:){7}[a-f0-9]{1,4}(?:\/\d{1,3})?$/i, //various compressed /^[a-f0-9]{0,4}::(?:\/\d{1,3})?$/i, /^:(?::[a-f0-9]{1,4}){1,6}(?:\/\d{1,3})?$/i, /^(?:[a-f0-9]{1,4}:){1,6}:(?:\/\d{1,3})?$/i, /^(?:[a-f0-9]{1,4}:)(?::[a-f0-9]{1,4}){1,6}(?:\/\d{1,3})?$/i, /^(?:[a-f0-9]{1,4}:){2}(?::[a-f0-9]{1,4}){1,5}(?:\/\d{1,3})?$/i, /^(?:[a-f0-9]{1,4}:){3}(?::[a-f0-9]{1,4}){1,4}(?:\/\d{1,3})?$/i, /^(?:[a-f0-9]{1,4}:){4}(?::[a-f0-9]{1,4}){1,3}(?:\/\d{1,3})?$/i, /^(?:[a-f0-9]{1,4}:){5}(?::[a-f0-9]{1,4}){1,2}(?:\/\d{1,3})?$/i, /^(?:[a-f0-9]{1,4}:){6}(?::[a-f0-9]{1,4})(?:\/\d{1,3})?$/i, //IPv6 mixes with IPv4 /^(?:[a-f0-9]{1,4}:){6}(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,3})?$/i, /^:(?::[a-f0-9]{1,4}){0,4}:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,3})?$/i, /^(?:[a-f0-9]{1,4}:){1,5}:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,3})?$/i, /^(?:[a-f0-9]{1,4}:)(?::[a-f0-9]{1,4}){1,4}:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,3})?$/i, /^(?:[a-f0-9]{1,4}:){2}(?::[a-f0-9]{1,4}){1,3}:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,3})?$/i, /^(?:[a-f0-9]{1,4}:){3}(?::[a-f0-9]{1,4}){1,2}:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,3})?$/i, /^(?:[a-f0-9]{1,4}:){4}(?::[a-f0-9]{1,4}):(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,3})?$/i ]; var validIPv4Addresses = [ //IPv4 /^(\d{1,3}\.){3}\d{1,3}$/i ]; var validAddresses = []; if (format == 'ipv6' || format == 'ipv6_ipv4') { validAddresses = validAddresses.concat(validIPv6Addresses); } if (format == 'ipv4' || format == 'ipv6_ipv4') { validAddresses = validAddresses.concat(validIPv4Addresses); } var ret = false; for (var i=0; i 255 || !regExp.test(pieces[i]) || pieces[i].length>3 || /^0{2,3}$/.test(pieces[i])) { return false; } } } if (ret && value.indexOf("/") != -1) { // if prefix-length is specified must be in [1-128] var prefLen = value.match(/\/\d{1,3}$/); if (!prefLen) return false; var prefLenVal = parseInt(prefLen[0].replace(/^\//,''), 10); if (isNaN(prefLenVal) || prefLenVal > 128 || prefLenVal < 1) { return false; } } return ret; }; Spry.Widget.ValidationTextField.onloadDidFire = false; Spry.Widget.ValidationTextField.loadQueue = []; Spry.Widget.ValidationTextField.prototype.isBrowserSupported = function() { return Spry.is.ie && Spry.is.v >= 5 && Spry.is.windows || Spry.is.mozilla && Spry.is.v >= 1.4 || Spry.is.safari || Spry.is.opera && Spry.is.v >= 9; }; Spry.Widget.ValidationTextField.prototype.init = function(element, options) { this.element = this.getElement(element); this.errors = 0; this.flags = {locked: false, restoreSelection: true}; this.options = {}; this.event_handlers = []; this.validClass = "textfieldValidState"; this.focusClass = "textfieldFocusState"; this.requiredClass = "textfieldRequiredState"; this.hintClass = "textfieldHintState"; this.invalidFormatClass = "textfieldInvalidFormatState"; this.invalidRangeMinClass = "textfieldMinValueState"; this.invalidRangeMaxClass = "textfieldMaxValueState"; this.invalidCharsMinClass = "textfieldMinCharsState"; this.invalidCharsMaxClass = "textfieldMaxCharsState"; this.textfieldFlashTextClass = "textfieldFlashText"; if (Spry.is.safari) { this.flags.lastKeyPressedTimeStamp = 0; } switch (this.type) { case 'phone_number':options.format = Spry.Widget.Utils.firstValid(options.format, 'phone_us');break; case 'currency':options.format = Spry.Widget.Utils.firstValid(options.format, 'comma_dot');break; case 'zip_code':options.format = Spry.Widget.Utils.firstValid(options.format, 'zip_us5');break; case 'date': options.format = Spry.Widget.Utils.firstValid(options.format, 'mm/dd/yy'); break; case 'time': options.format = Spry.Widget.Utils.firstValid(options.format, 'HH:mm'); options.pattern = options.format.replace(/[hms]/gi, "0").replace(/TT/gi, 'AM').replace(/T/gi, 'A'); break; case 'ip': options.format = Spry.Widget.Utils.firstValid(options.format, 'ipv4'); options.characterMasking = Spry.Widget.ValidationTextField.ValidationDescriptors[this.type].characterMaskingFormats[options.format]; break; } //retrieve the validation type descriptor to be used with this instance (base on type and format) //widgets may have different validations depending on format (like zip_code with formats) var validationDescriptor = {}; if (options.format && Spry.Widget.ValidationTextField.ValidationDescriptors[this.type].formats) { if (Spry.Widget.ValidationTextField.ValidationDescriptors[this.type].formats[options.format]) { Spry.Widget.Utils.setOptions(validationDescriptor, Spry.Widget.ValidationTextField.ValidationDescriptors[this.type].formats[options.format]); } } else { Spry.Widget.Utils.setOptions(validationDescriptor, Spry.Widget.ValidationTextField.ValidationDescriptors[this.type]); } //set default values for some parameters which were not aspecified options.useCharacterMasking = Spry.Widget.Utils.firstValid(options.useCharacterMasking, false); options.hint = Spry.Widget.Utils.firstValid(options.hint, ''); options.isRequired = Spry.Widget.Utils.firstValid(options.isRequired, true); options.additionalError = Spry.Widget.Utils.firstValid(options.additionalError, false); if (options.additionalError) options.additionalError = this.getElement(options.additionalError); //set widget validation parameters //get values from validation type descriptor //use the user specified values, if defined options.characterMasking = Spry.Widget.Utils.firstValid(options.characterMasking, validationDescriptor.characterMasking); options.regExpFilter = Spry.Widget.Utils.firstValid(options.regExpFilter, validationDescriptor.regExpFilter); options.pattern = Spry.Widget.Utils.firstValid(options.pattern, validationDescriptor.pattern); options.validation = Spry.Widget.Utils.firstValid(options.validation, validationDescriptor.validation); if (typeof options.validation == 'string') { options.validation = eval(options.validation); } options.minValue = Spry.Widget.Utils.firstValid(options.minValue, validationDescriptor.minValue); options.maxValue = Spry.Widget.Utils.firstValid(options.maxValue, validationDescriptor.maxValue); options.minChars = Spry.Widget.Utils.firstValid(options.minChars, validationDescriptor.minChars); options.maxChars = Spry.Widget.Utils.firstValid(options.maxChars, validationDescriptor.maxChars); Spry.Widget.Utils.setOptions(this, options); Spry.Widget.Utils.setOptions(this.options, options); }; Spry.Widget.ValidationTextField.prototype.destroy = function() { if (this.event_handlers) for (var i=0; i this.maxChars) { errors = errors | Spry.Widget.ValidationTextField.ERROR_CHARS_MAX; continueValidations = false; } } //validation - testValue passes widget validation function if (!mustRevert && this.validation && continueValidations) { var value = this.validation(fixedValue, this.options); if (false === value) { errors = errors | Spry.Widget.ValidationTextField.ERROR_FORMAT; continueValidations = false; } else { this.typedValue = value; } } if(!mustRevert && this.validation && this.minValue !== null && continueValidations) { var minValue = this.validation(this.minValue.toString(), this.options); if (minValue !== false) { if (this.typedValue < minValue) { errors = errors | Spry.Widget.ValidationTextField.ERROR_RANGE_MIN; continueValidations = false; } } } if(!mustRevert && this.validation && this.maxValue !== null && continueValidations) { var maxValue = this.validation(this.maxValue.toString(), this.options); if (maxValue !== false) { if( this.typedValue > maxValue) { errors = errors | Spry.Widget.ValidationTextField.ERROR_RANGE_MAX; continueValidations = false; } } } //an invalid value was tested; must make sure it does not get inside the input if (this.useCharacterMasking && mustRevert) { this.revertState(revertValue); } this.errors = errors; this.fixedValue = fixedValue; this.flags.locked = false; return mustRevert; }; Spry.Widget.ValidationTextField.prototype.onChange = function(e) { if (Spry.is.opera && this.flags.operaRevertOnKeyUp) { return true; } if (Spry.is.ie && e && e.propertyName != 'value') { return true; } if (this.flags.drop) { //delay this if it's a drop operation var self = this; setTimeout(function() { self.flags.drop = false; self.onChange(null); }, 0); return; } if (this.flags.hintOn) { return true; } if (this.keyCode == 8 || this.keyCode == 46 ) { var mustRevert = this.doValidations(this.input.value, this.input.value); this.oldValue = this.input.value; if ((mustRevert || this.errors) && this.validateOn & Spry.Widget.ValidationTextField.ONCHANGE) { var self = this; setTimeout(function() {self.validate();}, 0); return true; } } var mustRevert = this.doValidations(this.input.value, this.oldValue); if ((!mustRevert || this.errors) && this.validateOn & Spry.Widget.ValidationTextField.ONCHANGE) { var self = this; setTimeout(function() {self.validate();}, 0); } return true; }; Spry.Widget.ValidationTextField.prototype.onKeyUp = function(e) { if (this.flags.operaRevertOnKeyUp) { this.setValue(this.oldValue); Spry.Widget.Utils.stopEvent(e); this.selection.moveTo(this.selection.start, this.selection.start); this.flags.operaRevertOnKeyUp = false; return false; } if (this.flags.operaPasteOperation) { window.clearInterval(this.flags.operaPasteOperation); this.flags.operaPasteOperation = null; } }; Spry.Widget.ValidationTextField.prototype.operaPasteMonitor = function() { if (this.input.value != this.oldValue) { var mustRevert = this.doValidations(this.input.value, this.input.value); if (mustRevert) { this.setValue(this.oldValue); this.selection.moveTo(this.selection.start, this.selection.start); } else { this.onChange(); } } }; Spry.Widget.ValidationTextField.prototype.compileDatePattern = function () { var dateValidationPatternString = ""; var groupPatterns = []; var fullGroupPatterns = []; var autocompleteCharacters = []; var formatRegExp = /^([mdy]+)([\.\-\/\\\s]+)([mdy]+)([\.\-\/\\\s]+)([mdy]+)$/i; var formatGroups = this.options.format.match(formatRegExp); if (formatGroups !== null) { for (var i=1; i 0) { var all_messages = $$(' .textfieldRequiredMsg'); for(var counter=0; counter < all_messages.length; counter++) { if(all_messages[counter].parentNode.parentNode.id == this.element.id && all_messages[counter].parentNode.className == "alert alert_text") { if(!Spry.OriginalError[this.element.id]) { Spry.OriginalError[this.element.id] = all_messages[counter].innerHTML; } reset_flag = false; all_messages[counter].innerHTML = custom_validation_result[1]; } } } this.addClassName(this.element, this.requiredClass); this.addClassName(this.additionalError, this.requiredClass); false_flag = false; } } if(reset_flag || typeof(Spry.CustomValidation[this.element.id]) == "undefined") { if(Spry.OriginalError[this.element.id]) { var all_messages = $$(' .textfieldRequiredMsg'); for(var counter=0; counter < all_messages.length; counter++) { if(all_messages[counter].parentNode.parentNode.id == this.element.id && all_messages[counter].parentNode.className == "alert alert_text") { all_messages[counter].innerHTML = Spry.OriginalError[this.element.id]; } } } } //possible states: required, format, rangeMin, rangeMax, charsMin, charsMax if (this.validateOn & Spry.Widget.ValidationTextField.ONSUBMIT) { this.removeHint(); this.doValidations(this.input.value, this.input.value); if(!this.flags.active) { var self = this; setTimeout(function() {self.putHint();}, 10); } } if (false_flag && this.isRequired && this.errors & Spry.Widget.ValidationTextField.ERROR_REQUIRED) { this.addClassName(this.element, this.requiredClass); this.addClassName(this.additionalError, this.requiredClass); false_flag = false; //return false; } if (false_flag && this.errors & Spry.Widget.ValidationTextField.ERROR_FORMAT) { this.addClassName(this.element, this.invalidFormatClass); this.addClassName(this.additionalError, this.invalidFormatClass); false_flag = false; //return false; } if (false_flag && this.errors & Spry.Widget.ValidationTextField.ERROR_RANGE_MIN) { this.addClassName(this.element, this.invalidRangeMinClass); this.addClassName(this.additionalError, this.invalidRangeMinClass); false_flag = false; //return false; } if (false_flag && this.errors & Spry.Widget.ValidationTextField.ERROR_RANGE_MAX) { this.addClassName(this.element, this.invalidRangeMaxClass); this.addClassName(this.additionalError, this.invalidRangeMaxClass); false_flag = false; //return false; } if (false_flag && this.errors & Spry.Widget.ValidationTextField.ERROR_CHARS_MIN) { this.addClassName(this.element, this.invalidCharsMinClass); this.addClassName(this.additionalError, this.invalidCharsMinClass); false_flag = false; //return false; } if (false_flag && this.errors & Spry.Widget.ValidationTextField.ERROR_CHARS_MAX) { this.addClassName(this.element, this.invalidCharsMaxClass); this.addClassName(this.additionalError, this.invalidCharsMaxClass); false_flag = false; //return false; } /**************************************************** M O D I F I E D *************************************************/ if( typeof(spry_additional_error) != "undefined" ) { if(spry_additional_error) { page_validation(false_flag, VAL_ADDFIELD_TEXTFIELD, this); } } /**************************************************** M O D I F I E D *************************************************/ if(!false_flag) { return false; } this.addClassName(this.element, this.validClass); this.addClassName(this.additionalError, this.validClass); return true; }; Spry.Widget.ValidationTextField.prototype.addClassName = function(ele, className) { if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) != -1)) return; ele.className += (ele.className ? " " : "") + className; }; Spry.Widget.ValidationTextField.prototype.removeClassName = function(ele, className) { if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) == -1)) return; ele.className = ele.className.replace(new RegExp("\\s*\\b" + className + "\\b", "g"), ""); }; Spry.Widget.ValidationTextField.prototype.showError = function(msg) { alert('Spry.Widget.TextField ERR: ' + msg); }; /** * SelectionDescriptor is a wrapper for input type text selection methods and properties * as implemented by various browsers */ Spry.Widget.SelectionDescriptor = function (element) { this.element = element; this.update(); }; Spry.Widget.SelectionDescriptor.prototype.update = function() { if (Spry.is.ie && Spry.is.windows) { var sel = this.element.ownerDocument.selection; if (this.element.nodeName == "TEXTAREA") { if (sel.type != 'None') { try{var range = sel.createRange();}catch(err){return;} if (range.parentElement() == this.element){ var range_all = this.element.ownerDocument.body.createTextRange(); range_all.moveToElementText(this.element); for (var sel_start = 0; range_all.compareEndPoints('StartToStart', range) < 0; sel_start ++){ range_all.moveStart('character', 1); } this.start = sel_start; // create a selection of the whole this.element range_all = this.element.ownerDocument.body.createTextRange(); range_all.moveToElementText(this.element); for (var sel_end = 0; range_all.compareEndPoints('StartToEnd', range) < 0; sel_end++){ range_all.moveStart('character', 1); } this.end = sel_end; this.length = this.end - this.start; // get selected and surrounding text this.text = range.text; } } } else if (this.element.nodeName == "INPUT"){ try{this.range = sel.createRange();}catch(err){return;} this.length = this.range.text.length; var clone = this.range.duplicate(); this.start = -clone.moveStart("character", -10000); clone = this.range.duplicate(); clone.collapse(false); this.end = -clone.moveStart("character", -10000); this.text = this.range.text; } } else { var tmp = this.element; var selectionStart = 0; var selectionEnd = 0; try { selectionStart = tmp.selectionStart;} catch(err) {} try { selectionEnd = tmp.selectionEnd;} catch(err) {} if (Spry.is.safari) { if (selectionStart == 2147483647) { selectionStart = 0; } if (selectionEnd == 2147483647) { selectionEnd = 0; } } this.start = selectionStart; this.end = selectionEnd; this.length = selectionEnd - selectionStart; this.text = this.element.value.substring(selectionStart, selectionEnd); } }; Spry.Widget.SelectionDescriptor.prototype.destroy = function() { try { delete this.range} catch(err) {} try { delete this.element} catch(err) {} }; Spry.Widget.SelectionDescriptor.prototype.move = function(amount) { if (Spry.is.ie && Spry.is.windows) { this.range.move("character", amount); this.range.select(); } else { try { this.element.selectionStart++;}catch(err) {} } this.update(); }; Spry.Widget.SelectionDescriptor.prototype.moveTo = function(start, end) { if (Spry.is.ie && Spry.is.windows) { if (this.element.nodeName == "TEXTAREA") { var ta_range = this.element.createTextRange(); this.range = this.element.createTextRange(); this.range.move("character", start); this.range.moveEnd("character", end - start); var c1 = this.range.compareEndPoints("StartToStart", ta_range); if (c1 < 0) { this.range.setEndPoint("StartToStart", ta_range); } var c2 = this.range.compareEndPoints("EndToEnd", ta_range); if (c2 > 0) { this.range.setEndPoint("EndToEnd", ta_range); } } else if (this.element.nodeName == "INPUT"){ this.range = this.element.ownerDocument.selection.createRange(); this.range.move("character", -10000); this.start = this.range.moveStart("character", start); this.end = this.start + this.range.moveEnd("character", end - start); } this.range.select(); } else { this.start = start; try { this.element.selectionStart = start;} catch(err) {} this.end = end; try { this.element.selectionEnd = end;} catch(err) {} } this.ignore = true; this.update(); }; Spry.Widget.SelectionDescriptor.prototype.moveEnd = function(amount) { if (Spry.is.ie && Spry.is.windows) { this.range.moveEnd("character", amount); this.range.select(); } else { try { this.element.selectionEnd++;} catch(err) {} } this.update(); }; Spry.Widget.SelectionDescriptor.prototype.collapse = function(begin) { if (Spry.is.ie && Spry.is.windows) { this.range = this.element.ownerDocument.selection.createRange(); this.range.collapse(begin); this.range.select(); } else { if (begin) { try { this.element.selectionEnd = this.element.selectionStart;} catch(err) {} } else { try { this.element.selectionStart = this.element.selectionEnd;} catch(err) {} } } this.update(); }; ////////////////////////////////////////////////////////////////////// // // Spry.Widget.Form - common for all widgets // ////////////////////////////////////////////////////////////////////// if (!Spry.Widget.Form) Spry.Widget.Form = {}; if (!Spry.Widget.Form.onSubmitWidgetQueue) Spry.Widget.Form.onSubmitWidgetQueue = []; if (!Spry.Widget.Form.validate) { Spry.Widget.Form.validate = function(vform) { var isValid = true; var isElementValid = true; var q = Spry.Widget.Form.onSubmitWidgetQueue; var qlen = q.length; for (var i = 0; i < qlen; i++) { if (!q[i].isDisabled() && q[i].form == vform) { isElementValid = q[i].validate(); isValid = isElementValid && isValid; } } return isValid; } }; if(typeof(spry_popup_warning) == "undefined") { function spry_popup_warning() { if(typeof(document.getElementById("spry_popup_warning_message")) != "undefined" && document.getElementById("spry_popup_warning_message")) { document.getElementById("spry_popup_warning_message").style.display = "block"; if(typeof(spry_popup_warning_message_delay) != "undefined" && spry_popup_warning_message_delay) { setTimeout(function(){ reset_spry_popup_warning(); }, (spry_popup_warning_message_delay * 1000)); } else { setTimeout(function(){ reset_spry_popup_warning(); }, (3 * 1000)); } } } } if(typeof(reset_spry_popup_warning) == "undefined") { function reset_spry_popup_warning() { if(typeof(document.getElementById("spry_popup_warning_message")) != "undefined" && document.getElementById("spry_popup_warning_message")) { document.getElementById("spry_popup_warning_message").style.display = "none"; } } } if (!Spry.Widget.Form.onSubmit) { Spry.Widget.Form.onSubmit = function(e, form) { /**************************************************** M O D I F I E D *************************************************/ if(typeof(spry_validation_extension) == "function") { if(spry_validation_extension() == false) { spry_popup_warning(); return false; } } /**************************************************** M O D I F I E D *************************************************/ if (Spry.Widget.Form.validate(form) == false) { spry_popup_warning(); return false; } reset_spry_popup_warning(); return true; }; }; if (!Spry.Widget.Form.onReset) { Spry.Widget.Form.onReset = function(e, vform) { var q = Spry.Widget.Form.onSubmitWidgetQueue; var qlen = q.length; for (var i = 0; i < qlen; i++) { if (!q[i].isDisabled() && q[i].form == vform && typeof(q[i].reset) == 'function') { q[i].reset(); } } return true; }; }; if (!Spry.Widget.Form.destroy) { Spry.Widget.Form.destroy = function(form) { var q = Spry.Widget.Form.onSubmitWidgetQueue; for (var i = 0; i < Spry.Widget.Form.onSubmitWidgetQueue.length; i++) { if (q[i].form == form && typeof(q[i].destroy) == 'function') { q[i].destroy(); i--; } } } }; if (!Spry.Widget.Form.destroyAll) { Spry.Widget.Form.destroyAll = function() { var q = Spry.Widget.Form.onSubmitWidgetQueue; for (var i = 0; i < Spry.Widget.Form.onSubmitWidgetQueue.length; i++) { if (typeof(q[i].destroy) == 'function') { q[i].destroy(); i--; } } } }; ////////////////////////////////////////////////////////////////////// // // Spry.Widget.Utils // ////////////////////////////////////////////////////////////////////// if (!Spry.Widget.Utils) Spry.Widget.Utils = {}; Spry.Widget.Utils.punycode_constants = { base : 36, tmin : 1, tmax : 26, skew : 38, damp : 700, initial_bias : 72, initial_n : 0x80, delimiter : 0x2D, maxint : 2<<26-1 }; Spry.Widget.Utils.punycode_encode_digit = function (d) { return String.fromCharCode(d + 22 + 75 * (d < 26)); }; Spry.Widget.Utils.punycode_adapt = function (delta, numpoints, firsttime) { delta = firsttime ? delta / this.punycode_constants.damp : delta >> 1; delta += delta / numpoints; for (var k = 0; delta > ((this.punycode_constants.base - this.punycode_constants.tmin) * this.punycode_constants.tmax) / 2; k += this.punycode_constants.base) { delta /= this.punycode_constants.base - this.punycode_constants.tmin; } return k + (this.punycode_constants.base - this.punycode_constants.tmin + 1) * delta / (delta + this.punycode_constants.skew); }; /** * returns a Punicode representation of a UTF-8 string * adapted from http://tools.ietf.org/html/rfc3492 */ Spry.Widget.Utils.punycode_encode = function (input, max_out) { var inputc = input.split(""); input = []; for(var i=0; i 0) { output += String.fromCharCode(this.punycode_constants.delimiter); out++; } while (h < input_len) { for (m = this.punycode_constants.maxint, j = 0; j < input_len; j++) { if (input[j] >= n && input[j] < m) { m = input[j]; } } if (m - n > (this.punycode_constants.maxint - delta) / (h + 1)) { return false; } delta += (m - n) * (h + 1); n = m; for (j = 0; j < input_len; j++) { if (input[j] < n ) { if (++delta == 0) { return false; } } if (input[j] == n) { for (q = delta, k = this.punycode_constants.base; true; k += this.punycode_constants.base) { if (out >= max_out) { return false; } t = k <= bias ? this.punycode_constants.tmin : k >= bias + this.punycode_constants.tmax ? this.punycode_constants.tmax : k - bias; if (q < t) { break; } output += this.punycode_encode_digit(t + (q - t) % (this.punycode_constants.base - t)); out++; q = (q - t) / (this.punycode_constants.base - t); } output += this.punycode_encode_digit(q); out++; bias = this.punycode_adapt(delta, h + 1, h == b); delta = 0; h++; } } delta++, n++; } return output; }; Spry.Widget.Utils.setOptions = function(obj, optionsObj, ignoreUndefinedProps) { if (!optionsObj) return; for (var optionName in optionsObj) { if (ignoreUndefinedProps && optionsObj[optionName] == undefined) continue; obj[optionName] = optionsObj[optionName]; } }; Spry.Widget.Utils.firstValid = function() { var ret = null; for(var i=0; i 0) return; var handlers = this.event_handlers; if (this.input) { var self = this; this.input.setAttribute("AutoComplete", "off"); if (this.validateOn & Spry.Widget.ValidationConfirm.ONCHANGE) { var changeEvent = Spry.is.mozilla || Spry.is.opera || Spry.is.safari?"input": Spry.is.ie?"propertychange": "change"; handlers.push([this.input, changeEvent, function(e){if (self.isDisabled()) return true; return self.validate(e||event);}]); if (Spry.is.mozilla || Spry.is.safari) handlers.push([this.input, "dragdrop", function(e){if (self.isDisabled()) return true; return self.validate(e);}]); else if (Spry.is.ie) handlers.push([this.input, "drop", function(e){if (self.isDisabled()) return true; return self.validate(event);}]); } handlers.push([this.input, "blur", function(e) {if (self.isDisabled()) return true; return self.onBlur(e||event);}]); handlers.push([this.input, "focus", function(e) { if (self.isDisabled()) return true; return self.onFocus(e || event); }]); for (var i=0; i 0 && this.input.value != this.firstInput.value) { this.switchClassName(this.element, this.invalidClass); this.switchClassName(this.additionalError, this.invalidClass); return false; } this.switchClassName(this.element, this.validClass); this.switchClassName(this.additionalError, this.validClass); return true; }; Spry.Widget.ValidationConfirm.prototype.onBlur = function(e) { this.removeClassName(this.element, this.focusClass); this.removeClassName(this.additionalError, this.focusClass); if (this.validateOn & Spry.Widget.ValidationConfirm.ONBLUR) this.validate(e); }; Spry.Widget.ValidationConfirm.prototype.onFocus = function() { this.addClassName(this.element, this.focusClass); this.addClassName(this.additionalError, this.focusClass); }; Spry.Widget.ValidationConfirm.prototype.switchClassName = function(ele, className) { var classes = [this.validClass, this.requiredClass, this.invalidClass]; for (var i =0; i< classes.length; i++) this.removeClassName(ele, classes[i]); this.addClassName(ele, className); }; Spry.Widget.ValidationConfirm.prototype.addClassName = function(ele, className) { if (!ele || !className || (ele.className && ele.className.indexOf(className) != -1 && ele.className.search(new RegExp("\\b" + className + "\\b")) != -1)) return; ele.className += (ele.className ? " " : "") + className; }; Spry.Widget.ValidationConfirm.prototype.removeClassName = function(ele, className) { if (!ele || !className || (ele.className && ele.className.indexOf(className) != -1 && ele.className.search(new RegExp("\\b" + className + "\\b")) == -1)) return; ele.className = ele.className.replace(new RegExp("\\s*\\b" + className + "\\b", "g"), ""); }; Spry.Widget.ValidationConfirm.prototype.isBrowserSupported = function() { return Spry.is.ie && Spry.is.v >= 5 && Spry.is.windows || Spry.is.mozilla && Spry.is.v >= 1.4 || Spry.is.safari || Spry.is.opera && Spry.is.v >= 9; }; Spry.Widget.ValidationConfirm.prototype.isDisabled = function() { return this.input && (this.input.disabled || this.input.readOnly) || !this.input; }; Spry.Widget.ValidationConfirm.prototype.showError = function(msg) { alert('Spry.ValidationConfirm ERR: ' + msg); }; ////////////////////////////////////////////////////////////////////// // // Spry.Widget.Form - common for all widgets // ////////////////////////////////////////////////////////////////////// if (!Spry.Widget.Form) Spry.Widget.Form = {}; if (!Spry.Widget.Form.onSubmitWidgetQueue) Spry.Widget.Form.onSubmitWidgetQueue = []; if (!Spry.Widget.Form.validate) { Spry.Widget.Form.validate = function(vform) { var isValid = true; var isElementValid = true; var q = Spry.Widget.Form.onSubmitWidgetQueue; var qlen = q.length; for (var i = 0; i < qlen; i++) if (!q[i].isDisabled() && q[i].form == vform) { isElementValid = q[i].validate(); isValid = isElementValid && isValid; } return isValid; }; }; if(typeof(spry_popup_warning) == "undefined") { function spry_popup_warning() { if(typeof(document.getElementById("spry_popup_warning_message")) != "undefined" && document.getElementById("spry_popup_warning_message")) { document.getElementById("spry_popup_warning_message").style.display = "block"; if(typeof(spry_popup_warning_message_delay) != "undefined" && spry_popup_warning_message_delay) { setTimeout(function(){ reset_spry_popup_warning(); }, (spry_popup_warning_message_delay * 1000)); } else { setTimeout(function(){ reset_spry_popup_warning(); }, (3 * 1000)); } } } } if(typeof(reset_spry_popup_warning) == "undefined") { function reset_spry_popup_warning() { if(typeof(document.getElementById("spry_popup_warning_message")) != "undefined" && document.getElementById("spry_popup_warning_message")) { document.getElementById("spry_popup_warning_message").style.display = "none"; } } } if (!Spry.Widget.Form.onSubmit) { Spry.Widget.Form.onSubmit = function(e, form) { if (Spry.Widget.Form.validate(form) == false) { spry_popup_warning(); return false; } reset_spry_popup_warning(); return true; }; }; if (!Spry.Widget.Form.onReset) { Spry.Widget.Form.onReset = function(e, vform) { var q = Spry.Widget.Form.onSubmitWidgetQueue; var qlen = q.length; for (var i = 0; i < qlen; i++) if (!q[i].isDisabled() && q[i].form == vform && typeof(q[i].reset) == 'function') q[i].reset(); return true; }; }; if (!Spry.Widget.Form.destroy) { Spry.Widget.Form.destroy = function(form) { var q = Spry.Widget.Form.onSubmitWidgetQueue; for (var i = 0; i < Spry.Widget.Form.onSubmitWidgetQueue.length; i++) if (q[i].form == form && typeof(q[i].destroy) == 'function') { q[i].destroy(); i--; } } }; if (!Spry.Widget.Form.destroyAll) { Spry.Widget.Form.destroyAll = function() { var q = Spry.Widget.Form.onSubmitWidgetQueue; for (var i = 0; i < Spry.Widget.Form.onSubmitWidgetQueue.length; i++) if (typeof(q[i].destroy) == 'function') { q[i].destroy(); i--; } } }; ////////////////////////////////////////////////////////////////////// // // Spry.Widget.Utils // ////////////////////////////////////////////////////////////////////// if (!Spry.Widget.Utils) Spry.Widget.Utils = {}; Spry.Widget.Utils.setOptions = function(obj, optionsObj, ignoreUndefinedProps) { if (!optionsObj) return; for (var optionName in optionsObj) { if (ignoreUndefinedProps && optionsObj[optionName] == undefined) continue; obj[optionName] = optionsObj[optionName]; } }; Spry.Widget.Utils.firstValid = function() { var ret = null; for(var i=0; i= 5 && Spry.is.windows || Spry.is.mozilla && Spry.is.v >= 1.4 || Spry.is.safari || Spry.is.opera && Spry.is.v >= 9; }; /* * register our input to different event notifiers * */ Spry.Widget.ValidationTextarea.prototype.attachBehaviors = function() { if (this.element){ if (this.element.nodeName == "TEXTAREA") { this.input = this.element; } else { this.input = Spry.Widget.Utils.getFirstChildWithNodeNameAtAnyLevel(this.element, "TEXTAREA"); } } if (this.options && this.options.counterType && (this.options.counterType == 'chars_count' || this.options.counterType == 'chars_remaining')){ this.counterEl = document.getElementById(this.options.counterId); this.counterChar(); } if (this.input) { this.input.setAttribute("AutoComplete", "off"); this.putHint(); this.cursorPosition = new Spry.Widget.SelectionDescriptor(this.input); var self = this; this.event_handlers = []; //attach the pattern related event handlers (to stop invalid keys) if (this.useCharacterMasking) { if (Spry.is.ie){ this.event_handlers.push([this.input, "propertychange", function(e) { return self.onKeyEvent(e || event); }]); this.event_handlers.push([this.input, "drop", function(e) { return self.onDrop (e || event); }]); this.event_handlers.push([this.input, "keypress", function(e) { return self.onKeyPress(e || event); }]); } else{ this.event_handlers.push([this.input, "keydown", function(e) { return self.onKeyDown(e); }]); this.event_handlers.push([this.input, "keypress", function(e) { return self.safariKeyPress(e); }]); this.event_handlers.push([this.input, "keyup", function(e) { return self.safariValidate(e); }]); if (Spry.is.safari){ this.event_handlers.push([this.input, "mouseup", function(e) { return self.safariMouseUp(e); }]); this.event_handlers.push([this.input, "mousedown", function(e) { return self.safariMouseDown(e); }]); } else { //Firefox bug: 355219 //this.event_handlers.push([this.input, "input", function(e) { self.onKeyEvent(e); return true;}]); this.event_handlers.push([this.input, "dragdrop", function(e) { return self.onKeyEvent(e); }]); this.event_handlers.push([this.input, "dragenter", function(e) { self.removeHint(); return self.onKeyDown(e); }]); this.event_handlers.push([this.input, "dragexit", function(e) { return self.putHint(); }]); } } // we need to save an initial state in case of invalid input this.event_handlers.push([this.input, "keydown", function(e) {return self.onKeyDown(e || event); }]); } this.event_handlers.push([this.input, "focus", function(e) { return self.onFocus(e || event); }]); this.event_handlers.push([this.input, "mousedown", function(e) { return self.onMouseDown(e || event); }]); this.event_handlers.push([this.input, "blur", function(e) { return self.onBlur(e || event); }]); if (this.validateOn & Spry.Widget.ValidationTextarea.ONCHANGE){ if (Spry.is.ie){ this.event_handlers.push([this.input, "propertychange", function(e) { return self.onChange(e || event); }]); this.event_handlers.push([this.input, "drop", function(e) { return self.onChange(e || event); }]); } else{ this.event_handlers.push([this.input, "keydown", function(e) { return self.onKeyDown(e); }]); this.event_handlers.push([this.input, "keypress", function(e) { return self.safariChangeKeyPress(e); }]); this.event_handlers.push([this.input, "keyup", function(e) { return self.safariChangeValidate(e); }]); if (Spry.is.safari){ this.event_handlers.push([this.input, "mouseup", function(e) { return self.safariChangeMouseUp(e); }]); this.event_handlers.push([this.input, "mousedown", function(e) { return self.safariMouseDown(e); }]); } else { // Firefox bug: 355219 //this.event_handlers.push([this.input, "input", function(e) { return self.onChange(e); }]); this.event_handlers.push([this.input, "dragdrop", function(e) {return self.onChange(e); }]); this.event_handlers.push([this.input, "dragenter", function(e) { self.removeHint(); return self.onKeyDown(e); }]); this.event_handlers.push([this.input, "dragexit", function(e) { return self.putHint(); }]); } } } // The counter should be called directly when no enforcement or change restrictions exists if (! (this.validateOn & Spry.Widget.ValidationTextarea.ONCHANGE) && !this.useCharacterMasking){ if (Spry.is.ie){ this.event_handlers.push([this.input, "propertychange", function(e) { return self.counterChar(); }]); this.event_handlers.push([this.input, "drop", function(e) { return self.counterChar(); }]); } else{ this.event_handlers.push([this.input, "keypress", function(e) { return self.counterChar(); }]); this.event_handlers.push([this.input, "keyup", function(e) { return self.counterChar(); }]); if (Spry.is.safari){ this.event_handlers.push([this.input, "mouseup", function(e) { return self.counterChar(); }]); } else { // Firefox bug: 355219 //this.event_handlers.push([this.input, "input", function(e) { return self.onChange(e); }]); this.event_handlers.push([this.input, "dragdrop", function(e) {return self.counterChar(); }]); } } } for (var i=0; i 0 && ret){ if ( val.length > this.options.maxChars && ((!Spry.Widget.Utils.isSpecialKey(e) && this.cursorPosition.start == this.cursorPosition.end) || (Spry.Widget.Utils.isSpecialKey(e) && val != this.initialValue) || this.cursorPosition.start != this.cursorPosition.end) ){ // cut the extra chars and display error this.flags.locked = true; var initial = this.initialValue; var start = this.initialCursor.start; var end = this.initialCursor.end; if (initial.length && this.initialCursor.end < initial.length) { // we try to behave more like maxlength textfield var tmp = end - start + this.options.maxChars - initial.length; var newValue = initial.substring(0, start) + val.substring(start, start+tmp) + initial.substring(end, initial.length < this.options.maxChars ? initial.length:this.options.maxChars); end = start + tmp; }else{ var newValue = val.substring(0, this.options.maxChars); end = start = this.options.maxChars; } if (Spry.is.ie) { this.input.innerText = newValue; } else { this.input.value = newValue; } this.redTextFlash(); this.cursorPosition.moveTo(end, end); this.flags.locked = false; ret = false; } else{ this.setState(Spry.Widget.ValidationTextarea.VALID); this.isMaxInvalid = false; } } this.counterChar(); return ret; }; Spry.Widget.ValidationTextarea.prototype.validateMinRequired = function(val){ var oldInvalid = false; if (typeof this.notFireMinYet == 'undefined'){ this.notFireMinYet = false; }else{ oldInvalid = true; this.notFireMinYet = true; } if (this.onBlurOn){ this.notFireMinYet = true; }else if (!this.onKeyEventOn){ this.notFireMinYet = true; } if (this.input && this.options && this.options.isRequired){ if (val.length > 0 && this.isRequireInvalid && (!this.hint || (this.hint && !this.flags.hintOn) || (this.hint && val != this.hint))){ this.switchClassName(this.validClass); this.setState(Spry.Widget.ValidationTextarea.VALID); this.isRequireInvalid = false; }else if ((val.length == 0 || !(!this.hint || (this.hint && !this.flags.hintOn) || (this.hint && val != this.hint))) && (!this.isRequireInvalid || oldInvalid)){ if (this.notFireMinYet || Spry.is.ie){ this.switchClassName(this.requiredClass); this.setState(Spry.Widget.ValidationTextarea.REQUIRED); } this.isRequireInvalid = true; this.isMinInvalid = false; } } if (this.input && this.options && this.options.minChars > 0 && !this.isRequireInvalid){ if (val.length >= this.options.minChars && (!this.hint || (this.hint && !this.flags.hintOn) || (this.hint && val != this.hint)) && this.isMinInvalid){ this.switchClassName(this.validClass); this.setState(Spry.Widget.ValidationTextarea.VALID); this.isMinInvalid = false; }else if ( (val.length < this.options.minChars || (this.hint && val == this.hint && this.flags.hintOn)) && !this.isMinInvalid){ this.switchClassName(this.invalidCharsMinClass); this.setState(Spry.Widget.ValidationTextarea.MINIMUM); this.isMinInvalid = true; } } }; Spry.Widget.ValidationTextarea.prototype.counterChar = function(){ if (!this.counterEl || !this.options || !this.options.counterType || (this.options.counterType != 'chars_remaining' && this.options.counterType != 'chars_count')){ return; } if (this.options.counterType == 'chars_remaining') { if (this.options.maxChars > 0){ if (this.flags.hintOn){ this.setCounterElementValue(this.options.maxChars); } else { if (this.options.maxChars > this.input.value.length){ this.setCounterElementValue(this.options.maxChars - this.input.value.length); }else{ this.setCounterElementValue(0); } } } } else { if (this.flags.hintOn){ this.setCounterElementValue(0); } else { if (this.useCharacterMasking && typeof this.options.maxChars != 'undefined' && this.options.maxChars < this.input.value.length){ this.setCounterElementValue(this.options.maxChars); } else { this.setCounterElementValue(this.input.value.length); } } } }; Spry.Widget.ValidationTextarea.prototype.setCounterElementValue = function(val){ if ( this.counterEl.nodeName.toLowerCase() != 'input' && this.counterEl.nodeName.toLowerCase() != 'textarea' && this.counterEl.nodeName.toLowerCase() != 'select' && this.counterEl.nodeName.toLowerCase() != 'img'){ this.counterEl.innerHTML = val; } }; Spry.Widget.ValidationTextarea.prototype.reset = function() { this.removeHint(); this.removeClassName(this.requiredClass); this.removeClassName(this.invalidCharsMinClass); this.removeClassName(this.invalidCharsMaxClass); this.removeClassName(this.validClass); this.setState(Spry.Widget.ValidationTextarea.INITIAL); var self = this; setTimeout(function() {self.putHint();self.counterChar();}, 10); }; Spry.Widget.ValidationTextarea.prototype.validate = function(){ if (this.input.disabled == true || this.input.readOnly == true){ return true; } if (this.validateOn & Spry.Widget.ValidationTextarea.ONSUBMIT) { this.removeHint(); } var val = this.input.value; this.validateMinRequired(val); var ret = !this.isMinInvalid && !this.isRequireInvalid; if (ret && this.options.maxChars > 0 && !this.useCharacterMasking){ if (val.length <= this.options.maxChars || (this.hint && this.hint == val && this.flags.hintOn)) { this.switchClassName(this.validClass); this.setState(Spry.Widget.ValidationTextarea.VALID); this.isMaxInvalid = false; }else{ this.switchClassName(this.invalidCharsMaxClass); this.setState(Spry.Widget.ValidationTextarea.MAXIMUM); this.isMaxInvalid = true; } } ret = ret && !this.isMaxInvalid; if (ret) { this.switchClassName(this.validClass); } this.counterChar(); /**************************************************** M O D I F I E D *************************************************/ if( typeof(spry_additional_error) != "undefined" ) { if(spry_additional_error) { page_validation(ret, VAL_ADDFIELD_TEXTAREA, this); } } /**************************************************** M O D I F I E D *************************************************/ return ret; }; Spry.Widget.ValidationTextarea.prototype.setState = function(newstate){ this.state = newstate; }; Spry.Widget.ValidationTextarea.prototype.getState = function(){ return this.state; }; Spry.Widget.ValidationTextarea.prototype.removeHint = function() { if (this.flags.hintOn) { this.flags.locked = true; this.input.value = ""; this.flags.locked = false; this.flags.hintOn = false; this.removeClassName(this.hintClass); } }; Spry.Widget.ValidationTextarea.prototype.putHint = function() { if(this.hint && this.input.value == "") { this.flags.hintOn = true; this.input.value = this.hint; this.addClassName(this.hintClass); } }; Spry.Widget.ValidationTextarea.prototype.redTextFlash = function() { var self = this; this.addClassName(this.textareaFlashClass); setTimeout(function() { self.removeClassName(self.textareaFlashClass) }, 200); }; Spry.Widget.ValidationTextarea.prototype.onKeyPress = function(e) { //ENTER has length 2 on IE Windows, so will exceed maxLength on proximity if (Spry.is.ie && Spry.is.windows && e.keyCode == 13) { if ( (this.initialCursor.length + this.options.maxChars - this.input.value.length) < 2) { Spry.Widget.Utils.stopEvent(e); return false; } } }; Spry.Widget.ValidationTextarea.prototype.onKeyDown = function(e) { this.saveState(); this.keyCode = e.keyCode; return true; }; /* * hadle for the max chars restrictions * if key pressed or the input text is invalid it returns false * */ Spry.Widget.ValidationTextarea.prototype.onKeyEvent = function(e){ // on IE we look only for this input value changes if (e.type == 'propertychange' && e.propertyName != 'value'){ return true; } var allow = this.onTyping(e); if (!allow){ Spry.Widget.Utils.stopEvent(e); } //return allow; }; /* * handle for the min or required value * if the input text is invalid it returns false * */ Spry.Widget.ValidationTextarea.prototype.onChange = function(e){ if (Spry.is.ie && e && e.type == 'propertychange' && e.propertyName != 'value') { return true; } if (this.flags.drop) { //delay this if it's a drop operation var self = this; setTimeout(function() { self.flags.drop = false; self.onChange(null); }, 0); return true; } if (this.flags.hintOn) { return true; } this.onKeyEventOn = true; var answer = this.validate(); this.onKeyEventOn = false; return answer; }; Spry.Widget.ValidationTextarea.prototype.onMouseDown = function(e) { if (this.flags.active) { //mousedown fires before focus //avoid double saveState on first focus by mousedown by checking if the control has focus //do nothing if it's not focused because saveState will be called onfocus this.saveState(); } }; Spry.Widget.ValidationTextarea.prototype.onDrop = function(e) { //mark that a drop operation is in progress to avoid race conditions with event handlers for other events //especially onchange and onfocus this.flags.drop = true; this.removeHint(); if (Spry.is.ie) { var rng = document.body.createTextRange(); rng.moveToPoint(e.x, e.y); rng.select(); } this.saveState(); this.flags.active = true; this.addClassName(this.focusClass); }; Spry.Widget.ValidationTextarea.prototype.onFocus = function(e) { if (this.flags.drop) { return; } this.removeHint(); this.saveState(); this.flags.active = true; this.addClassName(this.focusClass); }; Spry.Widget.ValidationTextarea.prototype.onBlur = function(e){ this.removeClassName(this.focusClass); if (this.validateOn & Spry.Widget.ValidationTextarea.ONBLUR) { this.onBlurOn = true; this.validate(); this.onBlurOn = false; } this.flags.active = false; var self = this; setTimeout(function() {self.putHint();}, 10); }; Spry.Widget.ValidationTextarea.prototype.safariMouseDown = function(e){ this.safariClicked = true; }; Spry.Widget.ValidationTextarea.prototype.safariChangeMouseUp = function(e){ if (!this.safariClicked){ this.onKeyDown(e); return this.safariChangeValidate(e, false); }else{ this.safariClicked = false; return true; } }; Spry.Widget.ValidationTextarea.prototype.safariMouseUp = function(e){ if (!this.safariClicked){ this.onKeyDown(e); return this.safariValidate(e, false); }else{ this.safariClicked = false; return true; } }; Spry.Widget.ValidationTextarea.prototype.safariKeyPress = function(e){ this.safariFlag = new Date(); return this.safariValidate(e, true); }; Spry.Widget.ValidationTextarea.prototype.safariValidate = function(e, recall) { if (e.keyCode && Spry.Widget.Utils.isSpecialKey(e) && e.keyCode != 8 && e.keyCode != 46){ return true; } var answer = this.onTyping(e); // the answer to this is not yet final - we schedule another closing check if (new Date() - this.safariFlag < 1000 && recall){ var self = this; setTimeout(function(){self.safariValidate(e, false);}, 1000); } return answer; }; Spry.Widget.ValidationTextarea.prototype.safariChangeKeyPress = function(e){ this.safariChangeFlag = new Date(); return this.safariChangeValidate(e, true); }; Spry.Widget.ValidationTextarea.prototype.safariChangeValidate = function(e, recall){ if(e.keyCode && Spry.Widget.Utils.isSpecialKey(e) && e.keyCode != 8 && e.keyCode != 46){ return true; } var answer = this.onChange(e); // the answer to this is not yet final - we schedule another closing check if (new Date() - this.safariChangeFlag < 1000 && recall){ var self = this; setTimeout(function(){ self.safariChangeValidate(e, false);}, 1000 - new Date() + this.safariChangeFlag); } return answer; }; /* * save an initial state of the input to restore if the value is invalid * */ Spry.Widget.ValidationTextarea.prototype.saveState = function(e){ // we don't need this initial value that is already invalid if (this.options.maxChars > 0 && this.input.value.length > this.options.maxChars){ return; } this.cursorPosition.update(); if (!this.flags.hintOn){ this.initialValue = this.input.value; }else{ this.initialValue = ''; } this.initialCursor = this.cursorPosition; return true; }; Spry.Widget.ValidationTextarea.prototype.checkClassName = function(ele, className){ if (!ele || !className){ return false; } if (typeof ele == 'string' ) { ele = document.getElementById(ele); if (!ele){ return false; } } if (!ele.className){ ele.className = ' '; } return ele; }; Spry.Widget.ValidationTextarea.prototype.switchClassName = function (className){ var classes = [this.invalidCharsMaxClass, this.validClass, this.requiredClass, this.invalidCharsMinClass]; for (var k = 0; k < classes.length; k++){ if (classes[k] != className){ this.removeClassName(classes[k]); } } this.addClassName(className); }; Spry.Widget.ValidationTextarea.prototype.addClassName = function(clssName){ var ele = this.checkClassName(this.element, clssName); var add = this.checkClassName(this.additionalError, clssName); if (!ele || ele.className.search(new RegExp("\\b" + clssName + "\\b")) != -1){ return; } this.element.className += ' ' + clssName; if (add) add.className += ' ' + clssName; }; Spry.Widget.ValidationTextarea.prototype.removeClassName = function(className){ var ele = this.checkClassName(this.element, className); var add = this.checkClassName(this.additionalError, className); if (!ele){ return; } ele.className = ele.className.replace(new RegExp("\\s*\\b" + className + "\\b", "g"), ''); if (add){ add.className = add.className.replace(new RegExp("\\s*\\b" + className + "\\b", "g"), ''); } }; /** * SelectionDescriptor is a wrapper for input type text selection methods and properties * as implemented by various browsers */ Spry.Widget.SelectionDescriptor = function (element) { this.element = element; this.update(); }; Spry.Widget.SelectionDescriptor.prototype.update = function() { if (Spry.is.ie && Spry.is.windows) { var sel = this.element.ownerDocument.selection; if (this.element.nodeName == "TEXTAREA") { if (sel.type != 'None') { try{var range = sel.createRange();}catch(err){return;} if (range.parentElement() == this.element){ var range_all = this.element.ownerDocument.body.createTextRange(); range_all.moveToElementText(this.element); for (var sel_start = 0; range_all.compareEndPoints('StartToStart', range) < 0; sel_start ++){ range_all.moveStart('character', 1); } this.start = sel_start; // create a selection of the whole this.element range_all = this.element.ownerDocument.body.createTextRange(); range_all.moveToElementText(this.element); for (var sel_end = 0; range_all.compareEndPoints('StartToEnd', range) < 0; sel_end++){ range_all.moveStart('character', 1); } this.end = sel_end; this.length = this.end - this.start; // get selected and surrounding text this.text = range.text; } } } else if (this.element.nodeName == "INPUT"){ try{this.range = sel.createRange();}catch(err){return;} this.length = this.range.text.length; var clone = this.range.duplicate(); this.start = -clone.moveStart("character", -10000); clone = this.range.duplicate(); clone.collapse(false); this.end = -clone.moveStart("character", -10000); this.text = this.range.text; } } else { var tmp = this.element; var selectionStart = 0; var selectionEnd = 0; try { selectionStart = tmp.selectionStart;} catch(err) {} try { selectionEnd = tmp.selectionEnd;} catch(err) {} if (Spry.is.safari) { if (selectionStart == 2147483647) { selectionStart = 0; } if (selectionEnd == 2147483647) { selectionEnd = 0; } } this.start = selectionStart; this.end = selectionEnd; this.length = selectionEnd - selectionStart; this.text = this.element.value.substring(selectionStart, selectionEnd); } }; Spry.Widget.SelectionDescriptor.prototype.destroy = function() { try { delete this.range} catch(err) {} try { delete this.element} catch(err) {} }; Spry.Widget.SelectionDescriptor.prototype.moveTo = function(start, end) { if (Spry.is.ie && Spry.is.windows) { if (this.element.nodeName == "TEXTAREA") { var ta_range = this.element.createTextRange(); this.range = this.element.createTextRange(); this.range.move("character", start); this.range.moveEnd("character", end - start); var c1 = this.range.compareEndPoints("StartToStart", ta_range); if (c1 < 0) { this.range.setEndPoint("StartToStart", ta_range); } var c2 = this.range.compareEndPoints("EndToEnd", ta_range); if (c2 > 0) { this.range.setEndPoint("EndToEnd", ta_range); } } else if (this.element.nodeName == "INPUT"){ this.range = this.element.ownerDocument.selection.createRange(); this.range.move("character", -10000); this.start = this.range.moveStart("character", start); this.end = this.start + this.range.moveEnd("character", end - start); } this.range.select(); } else { this.start = start; try { this.element.selectionStart = start; } catch(err) {} this.end = end; try { this.element.selectionEnd = end; } catch(err) {} } this.ignore = true; this.update(); }; ////////////////////////////////////////////////////////////////////// // // Spry.Widget.Form - common for all widgets // ////////////////////////////////////////////////////////////////////// if (!Spry.Widget.Form) Spry.Widget.Form = {}; //if (!Spry.Widget.Form.onSubmitWidgetQueue) Spry.Widget.Form.onSubmitWidgetQueue = []; if (!Spry.Widget.Form.validate) { Spry.Widget.Form.validate = function(vform) { var isValid = true; var isElementValid = true; var q = Spry.Widget.Form.onSubmitWidgetQueue; var qlen = q.length; for (var i = 0; i < qlen; i++) { if (!q[i].isDisabled() && q[i].form == vform) { isElementValid = q[i].validate(); isValid = isElementValid && isValid; } } return isValid; } }; if(typeof(spry_popup_warning) == "undefined") { function spry_popup_warning() { if(typeof(document.getElementById("spry_popup_warning_message")) != "undefined" && document.getElementById("spry_popup_warning_message")) { document.getElementById("spry_popup_warning_message").style.display = "block"; if(typeof(spry_popup_warning_message_delay) != "undefined" && spry_popup_warning_message_delay) { setTimeout(function(){ reset_spry_popup_warning(); }, (spry_popup_warning_message_delay * 1000)); } else { setTimeout(function(){ reset_spry_popup_warning(); }, (3 * 1000)); } } } } if(typeof(reset_spry_popup_warning) == "undefined") { function reset_spry_popup_warning() { if(typeof(document.getElementById("spry_popup_warning_message")) != "undefined" && document.getElementById("spry_popup_warning_message")) { document.getElementById("spry_popup_warning_message").style.display = "none"; } } } if (!Spry.Widget.Form.onSubmit) { Spry.Widget.Form.onSubmit = function(e, form) { /**************************************************** M O D I F I E D *************************************************/ if(typeof(spry_validation_extension) == "function") { if(spry_validation_extension() == false) { spry_popup_warning(); return false; } } /**************************************************** M O D I F I E D *************************************************/ if (Spry.Widget.Form.validate(form) == false) { spry_popup_warning(); return false; } reset_spry_popup_warning(); return true; }; }; if (!Spry.Widget.Form.onReset) { Spry.Widget.Form.onReset = function(e, vform) { var q = Spry.Widget.Form.onSubmitWidgetQueue; var qlen = q.length; for (var i = 0; i < qlen; i++) { if (!q[i].isDisabled() && q[i].form == vform && typeof(q[i].reset) == 'function') { q[i].reset(); } } return true; }; }; if (!Spry.Widget.Form.destroy) { Spry.Widget.Form.destroy = function(form) { var q = Spry.Widget.Form.onSubmitWidgetQueue; for (var i = 0; i < Spry.Widget.Form.onSubmitWidgetQueue.length; i++) { if (q[i].form == form && typeof(q[i].destroy) == 'function') { q[i].destroy(); i--; } } } }; if (!Spry.Widget.Form.destroyAll) { Spry.Widget.Form.destroyAll = function() { var q = Spry.Widget.Form.onSubmitWidgetQueue; for (var i = 0; i < Spry.Widget.Form.onSubmitWidgetQueue.length; i++) { if (typeof(q[i].destroy) == 'function') { q[i].destroy(); i--; } } } }; ////////////////////////////////////////////////////////////////////// // // Spry.Widget.Utils // ////////////////////////////////////////////////////////////////////// if (!Spry.Widget.Utils) Spry.Widget.Utils = {}; Spry.Widget.Utils.setOptions = function(obj, optionsObj, ignoreUndefinedProps) { if (!optionsObj) return; for (var optionName in optionsObj) { if (ignoreUndefinedProps && optionsObj[optionName] == undefined) continue; obj[optionName] = optionsObj[optionName]; } }; Spry.Widget.Utils.firstValid = function() { var ret = null; for(var i=0; i- Enter Postcode -'); hidden_premises_inputs.set('html', ''); //Clear values address_street.set('value', ''); address_town.set('value', ''); address_county.set('value', ''); } //Set address else if(data) { address_building_options += ''; for(var key in data.premises) { if($type(key * 1) == "number") { //Create select options address_building_options += ''; //Create hidden inputs so values can be used on the site if(data.premises[key].organisation != '' && data.premises[key].building != '') { address_building_details += ''; } else if(data.premises[key].organisation != '') { address_building_details += ''; } else if(data.premises[key].building != '') { address_building_details += ''; } else { address_building_details += ''; } address_building_details += ''; } } //Add in other option in case address is not returned address_building_options += ''; //Set values address_building.set('html', address_building_options); hidden_premises_inputs.set('html', address_building_details); address_street.set('value', data.street); address_town.set('value', data.town); address_county.set('value', data.county); } //Hide House Name and number in case they are visible (this is possible) //address_building_name_container.setStyle('display','none'); //address_building_number_container.setStyle('display','none'); } function set_building_details() { var address_building = $$("#input_select_building select"); var address_building_name_container = $$("#input_text_house_name"); var address_building_name = $$("#text_house_name"); var address_building_number_container = $$("#input_text_house_number"); var address_building_number = $$("#text_house_number"); var premises_id = address_building.get('value'); var building = ''; var number = ''; //If 'Other' is selected, show house name and number if(premises_id == 'other') { //address_building_name_container.setStyle('display','block'); //address_building_number_container.setStyle('display','block'); } //If not default option else if(premises_id != '') { building = $$('#premises_' + premises_id + '_building').get('value'); number = $$('#premises_' + premises_id + '_number').get('value'); //address_building_name_container.setStyle('display','none'); //address_building_number_container.setStyle('display','none'); } //If default option else { //address_building_name_container.setStyle('display','none'); //address_building_number_container.setStyle('display','none'); } address_building_name.set('value', building); address_building_number.set('value', number); } //Stop form submitting on keypress of 'Return'/'Enter' in postcode var keyDown = function(event){ if(event.key == 'enter') { return false; } }; window.addEvent('domready', function() { $$('#text_post_code').addEvent('keydown', keyDown); });// JavaScript Document function hide_registration_fields() { $$('.show_contact_details').setStyle('display', 'block'); $$('.contact_details_address').setStyle('display', 'none'); $$('.contact_details_telephone_number').setStyle('display', 'none'); removeActivators(); $$('.show_contact_details_yes').addEvent('click', function(){ $$('.show_contact_details_yes').each(function(item){ if (item.get('checked')) { $$('.contact_details_address').setStyle('display', 'block'); $$('.contact_details_telephone_number').setStyle('display', 'block'); addActivators(); } else { $$('.contact_details_address').setStyle('display', 'none'); $$('.contact_details_telephone_number').setStyle('display', 'none'); removeActivators(); } }); }); $$('.show_contact_details_no').addEvent('click', function(){ $$('.show_contact_details_yes').each(function(item){ if (item.get('checked')) { $$('.contact_details_address').setStyle('display', 'block'); $$('.contact_details_telephone_number').setStyle('display', 'block'); addActivators(); } else { $$('.contact_details_address').setStyle('display', 'none'); $$('.contact_details_telephone_number').setStyle('display', 'none'); removeActivators(); } }); }); } function removeActivators() { window.input_text_telephone.destroy(); //window.input_text_house_number.destroy(); window.input_text_street.destroy(); window.input_text_city.destroy(); //window.input_text_county.destroy(); window.input_text_post_code.destroy(); } function addActivators() { window.input_text_telephone = new Spry.Widget.ValidationTextField("input_text_telephone", "none", {isRequired:false,validateOn:["blur", "change"], minChars:10}); //window.input_text_house_number = new Spry.Widget.ValidationTextField("input_text_house_number", "none", {validateOn:["blur", "change"], minChars:1}); window.input_text_street = new Spry.Widget.ValidationTextField("input_text_street", "none", {validateOn:["blur", "change"], minChars:3}); window.input_text_city = new Spry.Widget.ValidationTextField("input_text_city", "none", {validateOn:["blur", "change"], minChars:3}); //window.input_text_county = new Spry.Widget.ValidationTextField("input_text_county", "none", {validateOn:["blur", "change"], minChars:2}); window.input_text_post_code = new Spry.Widget.ValidationTextField("input_text_post_code", "none", {validateOn:["blur", "change"], minChars:3}); } window.addEvent('domready', function(){ //addActivators(); });