This repository has been archived on 2024-10-25. You can view files and clone it, but cannot push or open issues or pull requests.
Sequenzia/public/assets/moe-legacy/application.js

824 lines
364 KiB
JavaScript
Raw Normal View History

2016-05-21 09:04:21 +02:00
var Prototype={Version:"1.7",Browser:function(){var a=navigator.userAgent,b="[object Opera]"==Object.prototype.toString.call(window.opera);return{IE:!!window.attachEvent&&!b,Opera:b,WebKit:-1<a.indexOf("AppleWebKit/"),Gecko:-1<a.indexOf("Gecko")&&-1===a.indexOf("KHTML"),MobileSafari:/Apple.*Mobile/.test(a)}}(),BrowserFeatures:{XPath:!!document.evaluate,SelectorsAPI:!!document.querySelector,ElementExtensions:function(){var a=window.Element||window.HTMLElement;return!(!a||!a.prototype)}(),SpecificElementExtensions:function(){if("undefined"!==
typeof window.HTMLDivElement)return!0;var a=document.createElement("div"),b=document.createElement("form"),c=!1;a.__proto__&&a.__proto__!==b.__proto__&&(c=!0);return c}()},ScriptFragment:"<script[^>]*>([\\S\\s]*?)\x3c/script>",JSONFilter:/^\/\*-secure-([\s\S]*)\*\/\s*$/,emptyFunction:function(){},K:function(a){return a}};Prototype.Browser.MobileSafari&&(Prototype.BrowserFeatures.SpecificElementExtensions=!1);
var Class=function(){function a(){}var b=function(){for(var a in{toString:1})if("toString"===a)return!1;return!0}();return{create:function(){function b(){this.initialize.apply(this,arguments)}var d=null,e=$A(arguments);Object.isFunction(e[0])&&(d=e.shift());Object.extend(b,Class.Methods);b.superclass=d;b.subclasses=[];d&&(a.prototype=d.prototype,b.prototype=new a,d.subclasses.push(b));for(var d=0,f=e.length;d<f;d++)b.addMethods(e[d]);b.prototype.initialize||(b.prototype.initialize=Prototype.emptyFunction);
return b.prototype.constructor=b},Methods:{addMethods:function(a){var d=this.superclass&&this.superclass.prototype,e=Object.keys(a);b&&(a.toString!=Object.prototype.toString&&e.push("toString"),a.valueOf!=Object.prototype.valueOf&&e.push("valueOf"));for(var f=0,g=e.length;f<g;f++){var h=e[f],l=a[h];if(d&&Object.isFunction(l)&&"$super"==l.argumentNames()[0]){var m=l,l=function(a){return function(){return d[a].apply(this,arguments)}}(h).wrap(m);l.valueOf=m.valueOf.bind(m);l.toString=m.toString.bind(m)}this.prototype[h]=
l}return this}}}}();
(function(){function a(a){switch(a){case null:return"Null";case void 0:return"Undefined"}switch(typeof a){case "boolean":return"Boolean";case "number":return"Number";case "string":return"String"}return"Object"}function b(a,b){for(var c in b)a[c]=b[c];return a}function c(a){return d("",{"":a},[])}function d(b,c,e){c=c[b];"Object"===a(c)&&"function"===typeof c.toJSON&&(c=c.toJSON(b));b=l.call(c);switch(b){case "[object Number]":case "[object Boolean]":case "[object String]":c=c.valueOf()}switch(c){case null:return"null";case !0:return"true";
case !1:return"false"}switch(typeof c){case "string":return c.inspect(!0);case "number":return isFinite(c)?String(c):"null";case "object":for(var g=0,f=e.length;g<f;g++)if(e[g]===c)throw new TypeError;e.push(c);var h=[];if("[object Array]"===b){g=0;for(f=c.length;g<f;g++){var C=d(g,c,e);h.push("undefined"===typeof C?"null":C)}h="["+h.join(",")+"]"}else{for(var m=Object.keys(c),g=0,f=m.length;g<f;g++)b=m[g],C=d(b,c,e),"undefined"!==typeof C&&h.push(b.inspect(!0)+":"+C);h="{"+h.join(",")+"}"}e.pop();
return h}}function e(a){return JSON.stringify(a)}function f(b){if("Object"!==a(b))throw new TypeError;var c=[],d;for(d in b)b.hasOwnProperty(d)&&c.push(d);return c}function g(a){return"[object Array]"===l.call(a)}function h(a){return"undefined"===typeof a}var l=Object.prototype.toString,m=window.JSON&&"function"===typeof JSON.stringify&&"0"===JSON.stringify(0)&&"undefined"===typeof JSON.stringify(Prototype.K);"function"==typeof Array.isArray&&Array.isArray([])&&!Array.isArray({})&&(g=Array.isArray);
b(Object,{extend:b,inspect:function(a){try{return h(a)?"undefined":null===a?"null":a.inspect?a.inspect():String(a)}catch(b){if(b instanceof RangeError)return"...";throw b;}},toJSON:m?e:c,toQueryString:function(a){return $H(a).toQueryString()},toHTML:function(a){return a&&a.toHTML?a.toHTML():String.interpret(a)},keys:Object.keys||f,values:function(a){var b=[],c;for(c in a)b.push(a[c]);return b},clone:function(a){return b({},a)},isElement:function(a){return!(!a||1!=a.nodeType)},isArray:g,isHash:function(a){return a instanceof
Hash},isFunction:function(a){return"[object Function]"===l.call(a)},isString:function(a){return"[object String]"===l.call(a)},isNumber:function(a){return"[object Number]"===l.call(a)},isDate:function(a){return"[object Date]"===l.call(a)},isUndefined:h})})();
Object.extend(Function.prototype,function(){function a(a,b){for(var c=a.length,g=b.length;g--;)a[c+g]=b[g];return a}function b(b,e){b=c.call(b,0);return a(b,e)}var c=Array.prototype.slice;return{argumentNames:function(){var a=this.toString().match(/^[\s\(]*function[^(]*\(([^)]*)\)/)[1].replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g,"").replace(/\s+/g,"").split(",");return 1!=a.length||a[0]?a:[]},bind:function(a){if(2>arguments.length&&Object.isUndefined(arguments[0]))return this;var e=this,f=c.call(arguments,
1);return function(){var c=b(f,arguments);return e.apply(a,c)}},bindAsEventListener:function(b){var e=this,f=c.call(arguments,1);return function(c){c=a([c||window.event],f);return e.apply(b,c)}},curry:function(){if(!arguments.length)return this;var a=this,e=c.call(arguments,0);return function(){var c=b(e,arguments);return a.apply(this,c)}},delay:function(a){var b=this,f=c.call(arguments,1);return window.setTimeout(function(){return b.apply(b,f)},1E3*a)},defer:function(){var b=a([.01],arguments);return this.delay.apply(this,
b)},wrap:function(b){var c=this;return function(){var f=a([c.bind(this)],arguments);return b.apply(this,f)}},methodize:function(){if(this._methodized)return this._methodized;var b=this;return this._methodized=function(){var c=a([this],arguments);return b.apply(null,c)}}}}());
(function(a){function b(){return this.getUTCFullYear()+"-"+(this.getUTCMonth()+1).toPaddedString(2)+"-"+this.getUTCDate().toPaddedString(2)+"T"+this.getUTCHours().toPaddedString(2)+":"+this.getUTCMinutes().toPaddedString(2)+":"+this.getUTCSeconds().toPaddedString(2)+"Z"}function c(){return this.toISOString()}a.toISOString||(a.toISOString=b);a.toJSON||(a.toJSON=c)})(Date.prototype);RegExp.prototype.match=RegExp.prototype.test;
RegExp.escape=function(a){return String(a).replace(/([.*+?^=!:${}()|[\]\/\\])/g,"\\$1")};
var PeriodicalExecuter=Class.create({initialize:function(a,b){this.callback=a;this.frequency=b;this.currentlyExecuting=!1;this.registerCallback()},registerCallback:function(){this.timer=setInterval(this.onTimerEvent.bind(this),1E3*this.frequency)},execute:function(){this.callback(this)},stop:function(){this.timer&&(clearInterval(this.timer),this.timer=null)},onTimerEvent:function(){if(!this.currentlyExecuting)try{this.currentlyExecuting=!0,this.execute(),this.currentlyExecuting=!1}catch(a){throw this.currentlyExecuting=
!1,a;}}});Object.extend(String,{interpret:function(a){return null==a?"":String(a)},specialChar:{"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r","\\":"\\\\"}});
Object.extend(String.prototype,function(){function a(a){if(Object.isFunction(a))return a;var b=new Template(a);return function(a){return b.evaluate(a)}}function b(){return this.replace(/^\s+/,"").replace(/\s+$/,"")}function c(a){var b=this.strip().match(/([^?#]*)(#.*)?$/);return b?b[1].split(a||"&").inject({},function(a,b){if((b=b.split("="))[0]){var c=decodeURIComponent(b.shift()),d=1<b.length?b.join("="):b[0];void 0!=d&&(d=decodeURIComponent(d));c in a?(Object.isArray(a[c])||(a[c]=[a[c]]),a[c].push(d)):
a[c]=d}return a}):{}}function d(a){var b=this.unfilterJSON(),c=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;c.test(b)&&(b=b.replace(c,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)}));try{if(!a||b.isJSON())return eval("("+b+")")}catch(d){}throw new SyntaxError("Badly formed JSON string: "+this.inspect());}function e(){var a=this.unfilterJSON();return JSON.parse(a)}var f=window.JSON&&"function"===typeof JSON.parse&&
JSON.parse('{"test": true}').test;return{gsub:function(b,c){var d="",e=this,f;c=a(c);Object.isString(b)&&(b=RegExp.escape(b));if(!b.length&&!b.source)return c=c(""),c+e.split("").join(c)+c;for(;0<e.length;)(f=e.match(b))?(d+=e.slice(0,f.index),d+=String.interpret(c(f)),e=e.slice(f.index+f[0].length)):(d+=e,e="");return d},sub:function(b,c,d){c=a(c);d=Object.isUndefined(d)?1:d;return this.gsub(b,function(a){return 0>--d?a[0]:c(a)})},scan:function(a,b){this.gsub(a,b);return String(this)},truncate:function(a,
b){a=a||30;b=Object.isUndefined(b)?"...":b;return this.length>a?this.slice(0,a-b.length)+b:String(this)},strip:String.prototype.trim||b,stripTags:function(){return this.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi,"")},stripScripts:function(){return this.replace(new RegExp(Prototype.ScriptFragment,"img"),"")},extractScripts:function(){var a=new RegExp(Prototype.ScriptFragment,"im");return(this.match(new RegExp(Prototype.ScriptFragment,"img"))||[]).map(function(b){return(b.match(a)||["",
""])[1]})},evalScripts:function(){return this.extractScripts().map(function(a){return eval(a)})},escapeHTML:function(){return this.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")},unescapeHTML:function(){return this.stripTags().replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")},toQueryParams:c,parseQuery:c,toArray:function(){return this.split("")},succ:function(){return this.slice(0,this.length-1)+String.fromCharCode(this.charCodeAt(this.length-1)+1)},times:function(a){return 1>
a?"":Array(a+1).join(this)},camelize:function(){return this.replace(/-+(.)?/g,function(a,b){return b?b.toUpperCase():""})},capitalize:function(){return this.charAt(0).toUpperCase()+this.substring(1).toLowerCase()},underscore:function(){return this.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/-/g,"_").toLowerCase()},dasherize:function(){return this.replace(/_/g,"-")},inspect:function(a){var b=this.replace(/[\x00-\x1f\\]/g,function(a){return a in
String.specialChar?String.specialChar[a]:"\\u00"+a.charCodeAt().toPaddedString(2,16)});return a?'"'+b.replace(/"/g,'\\"')+'"':"'"+b.replace(/'/g,"\\'")+"'"},unfilterJSON:function(a){return this.replace(a||Prototype.JSONFilter,"$1")},isJSON:function(){var a=this;if(a.blank())return!1;a=a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@");a=a.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]");a=a.replace(/(?:^|:|,)(?:\s*\[)+/g,"");return/^[\],:{}\s]*$/.test(a)},evalJSON:f?
e:d,include:function(a){return-1<this.indexOf(a)},startsWith:function(a){return 0===this.lastIndexOf(a,0)},endsWith:function(a){var b=this.length-a.length;return 0<=b&&this.indexOf(a,b)===b},empty:function(){return""==this},blank:function(){return/^\s*$/.test(this)},interpolate:function(a,b){return(new Template(this,b)).evaluate(a)}}}());
var Template=Class.create({initialize:function(a,b){this.template=a.toString();this.pattern=b||Template.Pattern},evaluate:function(a){a&&Object.isFunction(a.toTemplateReplacements)&&(a=a.toTemplateReplacements());return this.template.gsub(this.pattern,function(b){if(null==a)return b[1]+"";var c=b[1]||"";if("\\"==c)return b[2];var d=a,e=b[3],f=/^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;b=f.exec(e);if(null==b)return c;for(;null!=b;){var g=b[1].startsWith("[")?b[2].replace(/\\\\]/g,"]"):b[1],d=d[g];if(null==
d||""==b[3])break;e=e.substring("["==b[3]?b[1].length:b[0].length);b=f.exec(e)}return c+String.interpret(d)})}});Template.Pattern=/(^|.|\r|\n)(#\{(.*?)\})/;
var $break={},Enumerable=function(){function a(a,b){a=a||Prototype.K;var c=!0;this.each(function(d,e){c=c&&!!a.call(b,d,e);if(!c)throw $break;});return c}function b(a,b){a=a||Prototype.K;var c=!1;this.each(function(d,e){if(c=!!a.call(b,d,e))throw $break;});return c}function c(a,b){a=a||Prototype.K;var c=[];this.each(function(d,e){c.push(a.call(b,d,e))});return c}function d(a,b){var c;this.each(function(d,e){if(a.call(b,d,e))throw c=d,$break;});return c}function e(a,b){var c=[];this.each(function(d,
e){a.call(b,d,e)&&c.push(d)});return c}function f(a){if(Object.isFunction(this.indexOf)&&-1!=this.indexOf(a))return!0;var b=!1;this.each(function(c){if(c==a)throw b=!0,$break;});return b}function g(){return this.map()}return{each:function(a,b){var c=0;try{this._each(function(d){a.call(b,d,c++)})}catch(d){if(d!=$break)throw d;}return this},eachSlice:function(a,b,c){var d=-a,e=[],g=this.toArray();if(1>a)return g;for(;(d+=a)<g.length;)e.push(g.slice(d,d+a));return e.collect(b,c)},all:a,every:a,any:b,
some:b,collect:c,map:c,detect:d,findAll:e,select:e,filter:e,grep:function(a,b,c){b=b||Prototype.K;var d=[];Object.isString(a)&&(a=new RegExp(RegExp.escape(a)));this.each(function(e,g){a.match(e)&&d.push(b.call(c,e,g))});return d},include:f,member:f,inGroupsOf:function(a,b){b=Object.isUndefined(b)?null:b;return this.eachSlice(a,function(c){for(;c.length<a;)c.push(b);return c})},inject:function(a,b,c){this.each(function(d,e){a=b.call(c,a,d,e)});return a},invoke:function(a){var b=$A(arguments).slice(1);
return this.map(function(c){return c[a].apply(c,b)})},max:function(a,b){a=a||Prototype.K;var c;this.each(function(d,e){d=a.call(b,d,e);if(null==c||d>=c)c=d});return c},min:function(a,b){a=a||Prototype.K;var c;this.each(function(d,e){d=a.call(b,d,e);if(null==c||d<c)c=d});return c},partition:function(a,b){a=a||Prototype.K;var c=[],d=[];this.each(function(e,g){(a.call(b,e,g)?c:d).push(e)});return[c,d]},pluck:function(a){var b=[];this.each(function(c){b.push(c[a])});return b},reject:function(a,b){var c=
[];this.each(function(d,e){a.call(b,d,e)||c.push(d)});return c},sortBy:function(a,b){return this.map(function(c,d){return{value:c,criteria:a.call(b,c,d)}}).sort(function(a,b){var c=a.criteria,d=b.criteria;return c<d?-1:c>d?1:0}).pluck("value")},toArray:g,entries:g,zip:function(){var a=Prototype.K,b=$A(arguments);Object.isFunction(b.last())&&(a=b.pop());var c=[this].concat(b).map($A);return this.map(function(b,d){return a(c.pluck(d))})},size:function(){return this.toArray().length},inspect:function(){return"#<Enumerable:"+
this.toArray().inspect()+">"},find:d}}();function $A(a){if(!a)return[];if("toArray"in Object(a))return a.toArray();for(var b=a.length||0,c=Array(b);b--;)c[b]=a[b];return c}function $w(a){return Object.isString(a)?(a=a.strip())?a.split(/\s+/):[]:[]}Array.from=$A;
(function(){function a(a,b){for(var c=0,d=this.length>>>0;c<d;c++)c in this&&a.call(b,this[c],c,this)}function b(){return g.call(this,0)}function c(a,b){b||(b=0);var c=this.length;for(0>b&&(b=c+b);b<c;b++)if(this[b]===a)return b;return-1}function d(a,b){b=isNaN(b)?this.length:(0>b?this.length+b:b)+1;var c=this.slice(0,b).reverse().indexOf(a);return 0>c?c:b-c-1}function e(){for(var a=g.call(this,0),b,c=0,d=arguments.length;c<d;c++)if(b=arguments[c],!Object.isArray(b)||"callee"in b)a.push(b);else for(var e=
0,f=b.length;e<f;e++)a.push(b[e]);return a}var f=Array.prototype,g=f.slice,h=f.forEach;h||(h=a);Object.extend(f,Enumerable);f._reverse||(f._reverse=f.reverse);Object.extend(f,{_each:h,clear:function(){this.length=0;return this},first:function(){return this[0]},last:function(){return this[this.length-1]},compact:function(){return this.select(function(a){return null!=a})},flatten:function(){return this.inject([],function(a,b){if(Object.isArray(b))return a.concat(b.flatten());a.push(b);return a})},without:function(){var a=
g.call(arguments,0);return this.select(function(b){return!a.include(b)})},reverse:function(a){return(!1===a?this.toArray():this)._reverse()},uniq:function(a){return this.inject([],function(b,c,d){0!=d&&(a?b.last()==c:b.include(c))||b.push(c);return b})},intersect:function(a){return this.uniq().findAll(function(b){return a.detect(function(a){return b===a})})},clone:b,toArray:b,size:function(){return this.length},inspect:function(){return"["+this.map(Object.inspect).join(", ")+"]"}});(function(){return 1!==
[].concat(arguments)[0][0]})(1,2)&&(f.concat=e);f.indexOf||(f.indexOf=c);f.lastIndexOf||(f.lastIndexOf=d)})();function $H(a){return new Hash(a)}
var Hash=Class.create(Enumerable,function(){function a(){return Object.clone(this._object)}function b(a,b){return Object.isUndefined(b)?a:a+"="+encodeURIComponent(String.interpret(b))}return{initialize:function(a){this._object=Object.isHash(a)?a.toObject():Object.clone(a)},_each:function(a){for(var b in this._object){var e=this._object[b],f=[b,e];f.key=b;f.value=e;a(f)}},set:function(a,b){return this._object[a]=b},get:function(a){if(this._object[a]!==Object.prototype[a])return this._object[a]},unset:function(a){var b=
this._object[a];delete this._object[a];return b},toObject:a,toTemplateReplacements:a,keys:function(){return this.pluck("key")},values:function(){return this.pluck("value")},index:function(a){var b=this.detect(function(b){return b.value===a});return b&&b.key},merge:function(a){return this.clone().update(a)},update:function(a){return(new Hash(a)).inject(this,function(a,b){a.set(b.key,b.value);return a})},toQueryString:function(){return this.inject([],function(a,d){var e=encodeURIComponent(d.key),f=
d.value;if(f&&"object"==typeof f){if(Object.isArray(f)){for(var g=[],h=0,l=f.length,m;h<l;h++)m=f[h],g.push(b(e,m));return a.concat(g)}}else a.push(b(e,f));return a}).join("&")},inspect:function(){return"#<Hash:{"+this.map(function(a){return a.map(Object.inspect).join(": ")}).join(", ")+"}>"},toJSON:a,clone:function(){return new Hash(this)}}}());Hash.from=$H;
Object.extend(Number.prototype,function(){return{toColorPart:function(){return this.toPaddedString(2,16)},succ:function(){return this+1},times:function(a,b){$R(0,this,!0).each(a,b);return this},toPaddedString:function(a,b){var c=this.toString(b||10);return"0".times(a-c.length)+c},abs:function(){return Math.abs(this)},round:function(){return Math.round(this)},ceil:function(){return Math.ceil(this)},floor:function(){return Math.floor(this)}}}());function $R(a,b,c){return new ObjectRange(a,b,c)}
var ObjectRange=Class.create(Enumerable,function(){return{initialize:function(a,b,c){this.start=a;this.end=b;this.exclusive=c},_each:function(a){for(var b=this.start;this.include(b);)a(b),b=b.succ()},include:function(a){return a<this.start?!1:this.exclusive?a<this.end:a<=this.end}}}()),Abstract={},Try={these:function(){for(var a,b=0,c=arguments.length;b<c;b++){var d=arguments[b];try{a=d();break}catch(e){}}return a}},Ajax={getTransport:function(){return Try.these(function(){return new XMLHttpRequest},
function(){return new ActiveXObject("Msxml2.XMLHTTP")},function(){return new ActiveXObject("Microsoft.XMLHTTP")})||!1},activeRequestCount:0,Responders:{responders:[],_each:function(a){this.responders._each(a)},register:function(a){this.include(a)||this.responders.push(a)},unregister:function(a){this.responders=this.responders.without(a)},dispatch:function(a,b,c,d){this.each(function(e){if(Object.isFunction(e[a]))try{e[a].apply(e,[b,c,d])}catch(f){}})}}};Object.extend(Ajax.Responders,Enumerable);
Ajax.Responders.register({onCreate:function(){Ajax.activeRequestCount++},onComplete:function(){Ajax.activeRequestCount--}});Ajax.Base=Class.create({initialize:function(a){this.options={method:"post",asynchronous:!0,contentType:"application/x-www-form-urlencoded",encoding:"UTF-8",parameters:"",evalJSON:!0,evalJS:!0};Object.extend(this.options,a||{});this.options.method=this.options.method.toLowerCase();Object.isHash(this.options.parameters)&&(this.options.parameters=this.options.parameters.toObject())}});
Ajax.Request=Class.create(Ajax.Base,{_complete:!1,initialize:function($super,b,c){$super(c);this.transport=Ajax.getTransport();this.request(b)},request:function(a){this.url=a;this.method=this.options.method;a=Object.isString(this.options.parameters)?this.options.parameters:Object.toQueryString(this.options.parameters);["get","post"].include(this.method)||(a+=(a?"&":"")+"_method="+this.method,this.method="post");a&&"get"===this.method&&(this.url+=(this.url.include("?")?"&":"?")+a);this.parameters=
a.toQueryParams();try{var b=new Ajax.Response(this);if(this.options.onCreate)this.options.onCreate(b);Ajax.Responders.dispatch("onCreate",this,b);this.transport.open(this.method.toUpperCase(),this.url,this.options.asynchronous);this.options.asynchronous&&this.respondToReadyState.bind(this).defer(1);this.transport.onreadystatechange=this.onStateChange.bind(this);this.setRequestHeaders();this.body="post"==this.method?this.options.postBody||a:null;this.transport.send(this.body);if(!this.options.asynchronous&&
this.transport.overrideMimeType)this.onStateChange()}catch(c){this.dispatchException(c)}},onStateChange:function(){var a=this.transport.readyState;1<a&&(4!=a||!this._complete)&&this.respondToReadyState(this.transport.readyState)},setRequestHeaders:function(){var a={"X-Requested-With":"XMLHttpRequest","X-Prototype-Version":Prototype.Version,Accept:"text/javascript, text/html, application/xml, text/xml, */*"};"post"==this.method&&(null!=this.options.contentType&&(a["Content-type"]=this.options.contentType+
(this.options.encoding?"; charset="+this.options.encoding:"")),this.transport.overrideMimeType&&2005>(navigator.userAgent.match(/Gecko\/(\d{4})/)||[0,2005])[1]&&(a.Connection="close"));if("object"==typeof this.options.requestHeaders){var b=this.options.requestHeaders;if(Object.isFunction(b.push))for(var c=0,d=b.length;c<d;c+=2)a[b[c]]=b[c+1];else $H(b).each(function(b){a[b.key]=b.value})}for(var e in a)this.transport.setRequestHeader(e,a[e])},success:function(){var a=this.getStatus();return!a||200<=
a&&300>a||304==a},getStatus:function(){try{return 1223===this.transport.status?204:this.transport.status||0}catch(a){return 0}},respondToReadyState:function(a){a=Ajax.Request.Events[a];var b=new Ajax.Response(this);if("Complete"==a){try{this._complete=!0,(this.options["on"+b.status]||this.options["on"+(this.success()?"Success":"Failure")]||Prototype.emptyFunction)(b,b.headerJSON)}catch(d){this.dispatchException(d)}var c=b.getHeader("Content-type");("force"==this.options.evalJS||this.options.evalJS&&
this.isSameOrigin()&&c&&c.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i))&&this.evalResponse()}try{(this.options["on"+a]||Prototype.emptyFunction)(b,b.headerJSON),Ajax.Responders.dispatch("on"+a,this,b,b.headerJSON)}catch(d){this.dispatchException(d)}"Complete"==a&&(this.transport.onreadystatechange=Prototype.emptyFunction)},isSameOrigin:function(){var a=this.url.match(/^\s*https?:\/\/[^\/]*/);return!a||a[0]=="#{protocol}//#{domain}#{port}".interpolate({protocol:location.protocol,
domain:document.domain,port:location.port?":"+location.port:""})},getHeader:function(a){try{return this.transport.getResponseHeader(a)||null}catch(b){return null}},evalResponse:function(){try{return eval((this.transport.responseText||"").unfilterJSON())}catch(a){this.dispatchException(a)}},dispatchException:function(a){(this.options.onException||Prototype.emptyFunction)(this,a);Ajax.Responders.dispatch("onException",this,a)}});
Ajax.Request.Events=["Uninitialized","Loading","Loaded","Interactive","Complete"];
Ajax.Response=Class.create({initialize:function(a){this.request=a;a=this.transport=a.transport;var b=this.readyState=a.readyState;if(2<b&&!Prototype.Browser.IE||4==b)this.status=this.getStatus(),this.statusText=this.getStatusText(),this.responseText=String.interpret(a.responseText),this.headerJSON=this._getHeaderJSON();4==b&&(a=a.responseXML,this.responseXML=Object.isUndefined(a)?null:a,this.responseJSON=this._getResponseJSON())},status:0,statusText:"",getStatus:Ajax.Request.prototype.getStatus,getStatusText:function(){try{return this.transport.statusText||
""}catch(a){return""}},getHeader:Ajax.Request.prototype.getHeader,getAllHeaders:function(){try{return this.getAllResponseHeaders()}catch(a){return null}},getResponseHeader:function(a){return this.transport.getResponseHeader(a)},getAllResponseHeaders:function(){return this.transport.getAllResponseHeaders()},_getHeaderJSON:function(){var a=this.getHeader("X-JSON");if(!a)return null;a=decodeURIComponent(escape(a));try{return a.evalJSON(this.request.options.sanitizeJSON||!this.request.isSameOrigin())}catch(b){this.request.dispatchException(b)}},
_getResponseJSON:function(){var a=this.request.options;if(!a.evalJSON||"force"!=a.evalJSON&&!(this.getHeader("Content-type")||"").include("application/json")||this.responseText.blank())return null;try{return this.responseText.evalJSON(a.sanitizeJSON||!this.request.isSameOrigin())}catch(b){this.request.dispatchException(b)}}});
Ajax.Updater=Class.create(Ajax.Request,{initialize:function($super,b,c,d){this.container={success:b.success||b,failure:b.failure||(b.success?null:b)};d=Object.clone(d);var e=d.onComplete;d.onComplete=function(b,c){this.updateContent(b.responseText);Object.isFunction(e)&&e(b,c)}.bind(this);$super(c,d)},updateContent:function(a){var b=this.container[this.success()?"success":"failure"],c=this.options;c.evalScripts||(a=a.stripScripts());if(b=$(b))if(c.insertion)if(Object.isString(c.insertion)){var d=
{};d[c.insertion]=a;b.insert(d)}else c.insertion(b,a);else b.update(a)}});
Ajax.PeriodicalUpdater=Class.create(Ajax.Base,{initialize:function($super,b,c,d){$super(d);this.onComplete=this.options.onComplete;this.frequency=this.options.frequency||2;this.decay=this.options.decay||1;this.updater={};this.container=b;this.url=c;this.start()},start:function(){this.options.onComplete=this.updateComplete.bind(this);this.onTimerEvent()},stop:function(){this.updater.options.onComplete=void 0;clearTimeout(this.timer);(this.onComplete||Prototype.emptyFunction).apply(this,arguments)},
updateComplete:function(a){this.options.decay&&(this.decay=a.responseText==this.lastText?this.decay*this.options.decay:1,this.lastText=a.responseText);this.timer=this.onTimerEvent.bind(this).delay(this.decay*this.frequency)},onTimerEvent:function(){this.updater=new Ajax.Updater(this.container,this.url,this.options)}});
function $(a){if(1<arguments.length){for(var b=0,c=[],d=arguments.length;b<d;b++)c.push($(arguments[b]));return c}Object.isString(a)&&(a=document.getElementById(a));return Element.extend(a)}Prototype.BrowserFeatures.XPath&&(document._getElementsByXPath=function(a,b){for(var c=[],d=document.evaluate(a,$(b)||document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null),e=0,f=d.snapshotLength;e<f;e++)c.push(Element.extend(d.snapshotItem(e)));return c});if(!Node)var Node={};
Node.ELEMENT_NODE||Object.extend(Node,{ELEMENT_NODE:1,ATTRIBUTE_NODE:2,TEXT_NODE:3,CDATA_SECTION_NODE:4,ENTITY_REFERENCE_NODE:5,ENTITY_NODE:6,PROCESSING_INSTRUCTION_NODE:7,COMMENT_NODE:8,DOCUMENT_NODE:9,DOCUMENT_TYPE_NODE:10,DOCUMENT_FRAGMENT_NODE:11,NOTATION_NODE:12});
(function(a){var b=function(){try{var a=document.createElement('<input name="x">');return"input"===a.tagName.toLowerCase()&&"x"===a.name}catch(b){return!1}}(),c=a.Element;a.Element=function(a,c){c=c||{};a=a.toLowerCase();var f=Element.cache;if(b&&c.name)return a="<"+a+' name="'+c.name+'">',delete c.name,Element.writeAttribute(document.createElement(a),c);f[a]||(f[a]=Element.extend(document.createElement(a)));f="select"===a||"type"in c?document.createElement(a):f[a].cloneNode(!1);return Element.writeAttribute(f,
c)};Object.extend(a.Element,c||{});c&&(a.Element.prototype=c.prototype)})(this);Element.idCounter=1;Element.cache={};Element._purgeElement=function(a){var b=a._prototypeUID;b&&(Element.stopObserving(a),a._prototypeUID=void 0,delete Element.Storage[b])};
Element.Methods={visible:function(a){return"none"!=$(a).style.display},toggle:function(a){a=$(a);Element[Element.visible(a)?"hide":"show"](a);return a},hide:function(a){a=$(a);a.style.display="none";return a},show:function(a){a=$(a);a.style.display="";return a},remove:function(a){a=$(a);a.parentNode.removeChild(a);return a},update:function(){var a=function(){var a=document.createElement("select"),b=!0;a.innerHTML='<option value="test">test</option>';a.options&&a.options[0]&&(b="OPTION"!==a.options[0].nodeName.toUpperCase());
return b}(),b=function(){try{var a=document.createElement("table");if(a&&a.tBodies)return a.innerHTML="<tbody><tr><td>test</td></tr></tbody>","undefined"==typeof a.tBodies[0]}catch(b){return!0}}(),c=function(){try{var a=document.createElement("div");a.innerHTML="<link>";return 0===a.childNodes.length}catch(b){return!0}}(),d=a||b||c,e=function(){var a=document.createElement("script"),b=!1;try{a.appendChild(document.createTextNode("")),b=!a.firstChild||a.firstChild&&3!==a.firstChild.nodeType}catch(c){b=
!0}return b}();return function(a,b){a=$(a);for(var h=Element._purgeElement,l=a.getElementsByTagName("*"),m=l.length;m--;)h(l[m]);b&&b.toElement&&(b=b.toElement());if(Object.isElement(b))return a.update().insert(b);b=Object.toHTML(b);h=a.tagName.toUpperCase();if("SCRIPT"===h&&e)return a.text=b,a;if(d)if(h in Element._insertionTranslations.tags){for(;a.firstChild;)a.removeChild(a.firstChild);Element._getContentFromAnonymousElement(h,b.stripScripts()).each(function(b){a.appendChild(b)})}else if(c&&Object.isString(b)&&
-1<b.indexOf("<link")){for(;a.firstChild;)a.removeChild(a.firstChild);Element._getContentFromAnonymousElement(h,b.stripScripts(),!0).each(function(b){a.appendChild(b)})}else a.innerHTML=b.stripScripts();else a.innerHTML=b.stripScripts();b.evalScripts.bind(b).defer();return a}}(),replace:function(a,b){a=$(a);if(b&&b.toElement)b=b.toElement();else if(!Object.isElement(b)){b=Object.toHTML(b);var c=a.ownerDocument.createRange();c.selectNode(a);b.evalScripts.bind(b).defer();b=c.createContextualFragment(b.stripScripts())}a.parentNode.replaceChild(b,
a);return a},insert:function(a,b){a=$(a);if(Object.isString(b)||Object.isNumber(b)||Object.isElement(b)||b&&(b.toElement||b.toHTML))b={bottom:b};var c,d,e,f;for(f in b)c=b[f],f=f.toLowerCase(),d=Element._insertionTranslations[f],c&&c.toElement&&(c=c.toElement()),Object.isElement(c)?d(a,c):(c=Object.toHTML(c),e=("before"==f||"after"==f?a.parentNode:a).tagName.toUpperCase(),e=Element._getContentFromAnonymousElement(e,c.stripScripts()),"top"!=f&&"after"!=f||e.reverse(),e.each(d.curry(a)),c.evalScripts.bind(c).defer());
return a},wrap:function(a,b,c){a=$(a);Object.isElement(b)?$(b).writeAttribute(c||{}):b=Object.isString(b)?new Element(b,c):new Element("div",b);a.parentNode&&a.parentNode.replaceChild(b,a);b.appendChild(a);return b},inspect:function(a){a=$(a);var b="<"+a.tagName.toLowerCase();$H({id:"id",className:"class"}).each(function(c){var d=c.first();c=c.last();(d=(a[d]||"").toString())&&(b+=" "+c+"="+d.inspect(!0))});return b+">"},recursivelyCollect:function(a,b,c){a=$(a);c=c||-1;for(var d=[];(a=a[b])&&(1==
a.nodeType&&d.push(Element.extend(a)),d.length!=c););return d},ancestors:function(a){return Element.recursivelyCollect(a,"parentNode")},descendants:function(a){return Element.select(a,"*")},firstDescendant:function(a){for(a=$(a).firstChild;a&&1!=a.nodeType;)a=a.nextSibling;return $(a)},immediateDescendants:function(a){var b=[];for(a=$(a).firstChild;a;)1===a.nodeType&&b.push(Element.extend(a)),a=a.nextSibling;return b},previousSiblings:function(a,b){return Element.recursivelyCollect(a,"previousSibling")},
nextSiblings:function(a){return Element.recursivelyCollect(a,"nextSibling")},siblings:function(a){a=$(a);return Element.previousSiblings(a).reverse().concat(Element.nextSiblings(a))},match:function(a,b){a=$(a);return Object.isString(b)?Prototype.Selector.match(a,b):b.match(a)},up:function(a,b,c){a=$(a);if(1==arguments.length)return $(a.parentNode);var d=Element.ancestors(a);return Object.isNumber(b)?d[b]:Prototype.Selector.find(d,b,c)},down:function(a,b,c){a=$(a);return 1==arguments.length?Element.firstDescendant(a):
Object.isNumber(b)?Element.descendants(a)[b]:Element.select(a,b)[c||0]},previous:function(a,b,c){a=$(a);Object.isNumber(b)&&(c=b,b=!1);Object.isNumber(c)||(c=0);return b?Prototype.Selector.find(a.previousSiblings(),b,c):a.recursivelyCollect("previousSibling",c+1)[c]},next:function(a,b,c){a=$(a);Object.isNumber(b)&&(c=b,b=!1);Object.isNumber(c)||(c=0);if(b)return Prototype.Selector.find(a.nextSiblings(),b,c);Object.isNumber(c);return a.recursivelyCollect("nextSibling",c+1)[c]},select:function(a){a=
$(a);var b=Array.prototype.slice.call(arguments,1).join(", ");return Prototype.Selector.select(b,a)},adjacent:function(a){a=$(a);var b=Array.prototype.slice.call(arguments,1).join(", ");return Prototype.Selector.select(b,a.parentNode).without(a)},identify:function(a){a=$(a);var b=Element.readAttribute(a,"id");if(b)return b;do b="anonymous_element_"+Element.idCounter++;while($(b));Element.writeAttribute(a,"id",b);return b},readAttribute:function(a,b){a=$(a);if(Prototype.Browser.IE){var c=Element._attributeTranslations.read;
if(c.values[b])return c.values[b](a,b);c.names[b]&&(b=c.names[b]);if(b.include(":"))return a.attributes&&a.attributes[b]?a.attributes[b].value:null}return a.getAttribute(b)},writeAttribute:function(a,b,c){a=$(a);var d={},e=Element._attributeTranslations.write;"object"==typeof b?d=b:d[b]=Object.isUndefined(c)?!0:c;for(var f in d)b=e.names[f]||f,c=d[f],e.values[f]&&(b=e.values[f](a,c)),!1===c||null===c?a.removeAttribute(b):!0===c?a.setAttribute(b,b):a.setAttribute(b,c);return a},getHeight:function(a){return Element.getDimensions(a).height},
getWidth:function(a){return Element.getDimensions(a).width},classNames:function(a){return new Element.ClassNames(a)},hasClassName:function(a,b){if(a=$(a)){var c=a.className;return 0<c.length&&(c==b||(new RegExp("(^|\\s)"+b+"(\\s|$)")).test(c))}},addClassName:function(a,b){if(a=$(a))return Element.hasClassName(a,b)||(a.className+=(a.className?" ":"")+b),a},removeClassName:function(a,b){if(a=$(a))return a.className=a.className.replace(new RegExp("(^|\\s+)"+b+"(\\s+|$)")," ").strip(),a},toggleClassName:function(a,
b){if(a=$(a))return Element[Element.hasClassName(a,b)?"removeClassName":"addClassName"](a,b)},cleanWhitespace:function(a){a=$(a);for(var b=a.firstChild;b;){var c=b.nextSibling;3!=b.nodeType||/\S/.test(b.nodeValue)||a.removeChild(b);b=c}return a},empty:function(a){return $(a).innerHTML.blank()},descendantOf:function(a,b){a=$(a);b=$(b);if(a.compareDocumentPosition)return 8===(a.compareDocumentPosition(b)&8);if(b.contains)return b.contains(a)&&b!==a;for(;a=a.parentNode;)if(a==b)return!0;return!1},scrollTo:function(a){a=
$(a);var b=Element.cumulativeOffset(a);window.scrollTo(b[0],b[1]);return a},getStyle:function(a,b){a=$(a);b="float"==b?"cssFloat":b.camelize();var c=a.style[b];c&&"auto"!=c||(c=(c=document.defaultView.getComputedStyle(a,null))?c[b]:null);return"opacity"==b?c?parseFloat(c):1:"auto"==c?null:c},getOpacity:function(a){return $(a).getStyle("opacity")},setStyle:function(a,b){a=$(a);var c=a.style;if(Object.isString(b))return a.style.cssText+=";"+b,b.include("opacity")?a.setOpacity(b.match(/opacity:\s*(\d?\.?\d*)/)[1]):
a;for(var d in b)"opacity"==d?a.setOpacity(b[d]):c["float"==d||"cssFloat"==d?Object.isUndefined(c.styleFloat)?"cssFloat":"styleFloat":d]=b[d];return a},setOpacity:function(a,b){a=$(a);a.style.opacity=1==b||""===b?"":1E-5>b?0:b;return a},makePositioned:function(a){a=$(a);var b=Element.getStyle(a,"position");"static"!=b&&b||(a._madePositioned=!0,a.style.position="relative",Prototype.Browser.Opera&&(a.style.top=0,a.style.left=0));return a},undoPositioned:function(a){a=$(a);a._madePositioned&&(a._madePositioned=
void 0,a.style.position=a.style.top=a.style.left=a.style.bottom=a.style.right="");return a},makeClipping:function(a){a=$(a);if(a._overflow)return a;a._overflow=Element.getStyle(a,"overflow")||"auto";"hidden"!==a._overflow&&(a.style.overflow="hidden");return a},undoClipping:function(a){a=$(a);if(!a._overflow)return a;a.style.overflow="auto"==a._overflow?"":a._overflow;a._overflow=null;return a},clonePosition:function(a,b,c){c=Object.extend({setLeft:!0,setTop:!0,setWidth:!0,setHeight:!0,offsetTop:0,
offsetLeft:0},c||{});b=$(b);var d=Element.viewportOffset(b),e=[0,0],f=null;a=$(a);"absolute"==Element.getStyle(a,"position")&&(f=Element.getOffsetParent(a),e=Element.viewportOffset(f));f==document.body&&(e[0]-=document.body.offsetLeft,e[1]-=document.body.offsetTop);c.setLeft&&(a.style.left=d[0]-e[0]+c.offsetLeft+"px");c.setTop&&(a.style.top=d[1]-e[1]+c.offsetTop+"px");c.setWidth&&(a.style.width=b.offsetWidth+"px");c.setHeight&&(a.style.height=b.offsetHeight+"px");return a}};
Object.extend(Element.Methods,{getElementsBySelector:Element.Methods.select,childElements:Element.Methods.immediateDescendants});Element._attributeTranslations={write:{names:{className:"class",htmlFor:"for"},values:{}}};
Prototype.Browser.Opera?(Element.Methods.getStyle=Element.Methods.getStyle.wrap(function(a,b,c){switch(c){case "height":case "width":if(!Element.visible(b))return null;var d=parseInt(a(b,c),10);return d!==b["offset"+c.capitalize()]?d+"px":("height"===c?["border-top-width","padding-top","padding-bottom","border-bottom-width"]:["border-left-width","padding-left","padding-right","border-right-width"]).inject(d,function(c,d){var g=a(b,d);return null===g?c:c-parseInt(g,10)})+"px";default:return a(b,c)}}),
Element.Methods.readAttribute=Element.Methods.readAttribute.wrap(function(a,b,c){return"title"===c?b.title:a(b,c)})):Prototype.Browser.IE?(Element.Methods.getStyle=function(a,b){a=$(a);b="float"==b||"cssFloat"==b?"styleFloat":b.camelize();var c=a.style[b];!c&&a.currentStyle&&(c=a.currentStyle[b]);return"opacity"==b?(c=(a.getStyle("filter")||"").match(/alpha\(opacity=(.*)\)/))&&c[1]?parseFloat(c[1])/100:1:"auto"==c?"width"!=b&&"height"!=b||"none"==a.getStyle("display")?null:a["offset"+b.capitalize()]+
"px":c},Element.Methods.setOpacity=function(a,b){a=$(a);var c=a.currentStyle;if(c&&!c.hasLayout||!c&&"normal"==a.style.zoom)a.style.zoom=1;var c=a.getStyle("filter"),d=a.style;if(1==b||""===b)return(c=c.replace(/alpha\([^\)]*\)/gi,""))?d.filter=c:d.removeAttribute("filter"),a;1E-5>b&&(b=0);d.filter=c.replace(/alpha\([^\)]*\)/gi,"")+"alpha(opacity="+100*b+")";return a},Element._attributeTranslations=function(){var a="className",b="for",c=document.createElement("div");c.setAttribute(a,"x");"x"!==c.className&&
(c.setAttribute("class","x"),"x"===c.className&&(a="class"));c=null;c=document.createElement("label");c.setAttribute(b,"x");"x"!==c.htmlFor&&(c.setAttribute("htmlFor","x"),"x"===c.htmlFor&&(b="htmlFor"));c=null;return{read:{names:{"class":a,className:a,"for":b,htmlFor:b},values:{_getAttr:function(a,b){return a.getAttribute(b)},_getAttr2:function(a,b){return a.getAttribute(b,2)},_getAttrNode:function(a,b){var c=a.getAttributeNode(b);return c?c.value:""},_getEv:function(){var a=document.createElement("div"),
b;a.onclick=Prototype.emptyFunction;a=a.getAttribute("onclick");-1<String(a).indexOf("{")?b=function(a,b){b=a.getAttribute(b);if(!b)return null;b=b.toString();b=b.split("{")[1];b=b.split("}")[0];return b.strip()}:""===a&&(b=function(a,b){return(b=a.getAttribute(b))?b.strip():null});a=null;return b}(),_flag:function(a,b){return $(a).hasAttribute(b)?b:null},style:function(a){return a.style.cssText.toLowerCase()},title:function(a){return a.title}}}}}(),Element._attributeTranslations.write={names:Object.extend({cellpadding:"cellPadding",
cellspacing:"cellSpacing"},Element._attributeTranslations.read.names),values:{checked:function(a,b){a.checked=!!b},style:function(a,b){a.style.cssText=b?b:""}}},Element._attributeTranslations.has={},$w("colSpan rowSpan vAlign dateTime accessKey tabIndex encType maxLength readOnly longDesc frameBorder").each(function(a){Element._attributeTranslations.write.names[a.toLowerCase()]=a;Element._attributeTranslations.has[a.toLowerCase()]=a}),function(a){Object.extend(a,{href:a._getAttr2,src:a._getAttr2,
type:a._getAttr,action:a._getAttrNode,disabled:a._flag,checked:a._flag,readonly:a._flag,multiple:a._flag,onload:a._getEv,onunload:a._getEv,onclick:a._getEv,ondblclick:a._getEv,onmousedown:a._getEv,onmouseup:a._getEv,onmouseover:a._getEv,onmousemove:a._getEv,onmouseout:a._getEv,onfocus:a._getEv,onblur:a._getEv,onkeypress:a._getEv,onkeydown:a._getEv,onkeyup:a._getEv,onsubmit:a._getEv,onreset:a._getEv,onselect:a._getEv,onchange:a._getEv})}(Element._attributeTranslations.read.values),Prototype.BrowserFeatures.ElementExtensions&&
function(){Element.Methods.down=function(a,b,c){a=$(a);if(1==arguments.length)return a.firstDescendant();var d;if(Object.isNumber(b)){d=a.getElementsByTagName("*");for(var e=[],f=0,g;g=d[f];f++)"!"!==g.tagName&&e.push(g);d=e[b]}else d=Element.select(a,b)[c||0];return d}}()):Prototype.Browser.Gecko&&/rv:1\.8\.0/.test(navigator.userAgent)?Element.Methods.setOpacity=function(a,b){a=$(a);a.style.opacity=1==b?.999999:""===b?"":1E-5>b?0:b;return a}:Prototype.Browser.WebKit&&(Element.Methods.setOpacity=
function(a,b){a=$(a);a.style.opacity=1==b||""===b?"":1E-5>b?0:b;if(1==b)if("IMG"==a.tagName.toUpperCase()&&a.width)a.width++,a.width--;else try{var c=document.createTextNode(" ");a.appendChild(c);a.removeChild(c)}catch(d){}return a});
"outerHTML"in document.documentElement&&(Element.Methods.replace=function(a,b){a=$(a);b&&b.toElement&&(b=b.toElement());if(Object.isElement(b))return a.parentNode.replaceChild(b,a),a;b=Object.toHTML(b);var c=a.parentNode,d=c.tagName.toUpperCase();if(Element._insertionTranslations.tags[d]){var e=a.next(),d=Element._getContentFromAnonymousElement(d,b.stripScripts());c.removeChild(a);e?d.each(function(a){c.insertBefore(a,e)}):d.each(function(a){c.appendChild(a)})}else a.outerHTML=b.stripScripts();b.evalScripts.bind(b).defer();
return a});Element._returnOffset=function(a,b){var c=[a,b];c.left=a;c.top=b;return c};Element._getContentFromAnonymousElement=function(a,b,c){var d=new Element("div");a=Element._insertionTranslations.tags[a];var e=!1;a?e=!0:c&&(e=!0,a=["","",0]);if(e)for(d.innerHTML="&nbsp;"+a[0]+b+a[1],d.removeChild(d.firstChild),b=a[2];b--;)d=d.firstChild;else d.innerHTML=b;return $A(d.childNodes)};
Element._insertionTranslations={before:function(a,b){a.parentNode.insertBefore(b,a)},top:function(a,b){a.insertBefore(b,a.firstChild)},bottom:function(a,b){a.appendChild(b)},after:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},tags:{TABLE:["<table>","</table>",1],TBODY:["<table><tbody>","</tbody></table>",2],TR:["<table><tbody><tr>","</tr></tbody></table>",3],TD:["<table><tbody><tr><td>","</td></tr></tbody></table>",4],SELECT:["<select>","</select>",1]}};
(function(){var a=Element._insertionTranslations.tags;Object.extend(a,{THEAD:a.TBODY,TFOOT:a.TBODY,TH:a.TD})})();Element.Methods.Simulated={hasAttribute:function(a,b){b=Element._attributeTranslations.has[b]||b;var c=$(a).getAttributeNode(b);return!(!c||!c.specified)}};Element.Methods.ByTag={};Object.extend(Element,Element.Methods);
(function(a){!Prototype.BrowserFeatures.ElementExtensions&&a.__proto__&&(window.HTMLElement={},window.HTMLElement.prototype=a.__proto__,Prototype.BrowserFeatures.ElementExtensions=!0)})(document.createElement("div"));
Element.extend=function(){function a(a,b){for(var c in b){var d=b[c];!Object.isFunction(d)||c in a||(a[c]=d.methodize())}}var b=function(a){if("undefined"!=typeof window.Element){var b=window.Element.prototype;if(b){var c="_"+(Math.random()+"").slice(2);a=document.createElement(a);b[c]="x";a="x"!==a[c];delete b[c];return a}}return!1}("object");if(Prototype.BrowserFeatures.SpecificElementExtensions)return b?function(b){if(b&&"undefined"==typeof b._extendedByPrototype){var c=b.tagName;c&&/^(?:object|applet|embed)$/i.test(c)&&
(a(b,Element.Methods),a(b,Element.Methods.Simulated),a(b,Element.Methods.ByTag[c.toUpperCase()]))}return b}:Prototype.K;var c={},d=Element.Methods.ByTag,b=Object.extend(function(b){if(!b||"undefined"!=typeof b._extendedByPrototype||1!=b.nodeType||b==window)return b;var f=Object.clone(c),g=b.tagName.toUpperCase();d[g]&&Object.extend(f,d[g]);a(b,f);b._extendedByPrototype=Prototype.emptyFunction;return b},{refresh:function(){Prototype.BrowserFeatures.ElementExtensions||(Object.extend(c,Element.Methods),
Object.extend(c,Element.Methods.Simulated))}});b.refresh();return b}();Element.hasAttribute=document.documentElement.hasAttribute?function(a,b){return a.hasAttribute(b)}:Element.Methods.Simulated.hasAttribute;
Element.addMethods=function(a){function b(b){b=b.toUpperCase();Element.Methods.ByTag[b]||(Element.Methods.ByTag[b]={});Object.extend(Element.Methods.ByTag[b],a)}function c(a,b,c){c=c||!1;for(var d in a){var e=a[d];Object.isFunction(e)&&(c&&d in b||(b[d]=e.methodize()))}}function d(a){var b,c={OPTGROUP:"OptGroup",TEXTAREA:"TextArea",P:"Paragraph",FIELDSET:"FieldSet",UL:"UList",OL:"OList",DL:"DList",DIR:"Directory",H1:"Heading",H2:"Heading",H3:"Heading",H4:"Heading",H5:"Heading",H6:"Heading",Q:"Quote",
INS:"Mod",DEL:"Mod",A:"Anchor",IMG:"Image",CAPTION:"TableCaption",COL:"TableCol",COLGROUP:"TableCol",THEAD:"TableSection",TFOOT:"TableSection",TBODY:"TableSection",TR:"TableRow",TH:"TableCell",TD:"TableCell",FRAMESET:"FrameSet",IFRAME:"IFrame"};c[a]&&(b="HTML"+c[a]+"Element");if(window[b])return window[b];b="HTML"+a+"Element";if(window[b])return window[b];b="HTML"+a.capitalize()+"Element";if(window[b])return window[b];a=document.createElement(a);return a.__proto__||a.constructor.prototype}var e=Prototype.BrowserFeatures,
f=Element.Methods.ByTag;a||(Object.extend(Form,Form.Methods),Object.extend(Form.Element,Form.Element.Methods),Object.extend(Element.Methods.ByTag,{FORM:Object.clone(Form.Methods),INPUT:Object.clone(Form.Element.Methods),SELECT:Object.clone(Form.Element.Methods),TEXTAREA:Object.clone(Form.Element.Methods),BUTTON:Object.clone(Form.Element.Methods)}));if(2==arguments.length){var g=a;a=arguments[1]}g?Object.isArray(g)?g.each(b):b(g):Object.extend(Element.Methods,a||{});g=window.HTMLElement?HTMLElement.prototype:
Element.prototype;e.ElementExtensions&&(c(Element.Methods,g),c(Element.Methods.Simulated,g,!0));if(e.SpecificElementExtensions)for(var h in Element.Methods.ByTag)e=d(h),Object.isUndefined(e)||c(f[h],e.prototype);Object.extend(Element,Element.Methods);delete Element.ByTag;Element.extend.refresh&&Element.extend.refresh();Element.cache={}};
document.viewport={getDimensions:function(){return{width:this.getWidth(),height:this.getHeight()}},getScrollOffsets:function(){return Element._returnOffset(window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft,window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop)}};
(function(a){function b(b){e||(e=c.WebKit&&!d.evaluate?document:c.Opera&&9.5>window.parseFloat(window.opera.version())?document.body:document.documentElement);f[b]="client"+b;a["get"+b]=function(){return e[f[b]]};return a["get"+b]()}var c=Prototype.Browser,d=document,e,f={};a.getWidth=b.curry("Width");a.getHeight=b.curry("Height")})(document.viewport);Element.Storage={UID:1};
Element.addMethods({getStorage:function(a){if(a=$(a))return a===window?a=0:("undefined"===typeof a._prototypeUID&&(a._prototypeUID=Element.Storage.UID++),a=a._prototypeUID),Element.Storage[a]||(Element.Storage[a]=$H()),Element.Storage[a]},store:function(a,b,c){if(a=$(a))return 2===arguments.length?Element.getStorage(a).update(b):Element.getStorage(a).set(b,c),a},retrieve:function(a,b,c){if(a=$(a)){a=Element.getStorage(a);var d=a.get(b);Object.isUndefined(d)&&(a.set(b,c),d=c);return d}},clone:function(a,
b){if(a=$(a)){var c=a.cloneNode(b);c._prototypeUID=void 0;if(b)for(var d=Element.select(c,"*"),e=d.length;e--;)d[e]._prototypeUID=void 0;return Element.extend(c)}},purge:function(a){if(a=$(a)){var b=Element._purgeElement;b(a);a=a.getElementsByTagName("*");for(var c=a.length;c--;)b(a[c]);return null}}});
(function(){function a(a,b,c){var d=null;Object.isElement(a)&&(d=a,a=d.getStyle(b));if(null===a)return null;if(/^(?:-)?\d+(\.\d+)?(px)?$/i.test(a))return window.parseFloat(a);var e=a.include("%"),f=c===document.viewport;return!(/\d/.test(a)&&d&&d.runtimeStyle)||e&&f?d&&e?(c=c||d.parentNode,a=(a=a.match(/^(\d+)%?$/i))?Number(a[1])/100:null,e=null,d.getStyle("position"),d=b.include("left")||b.include("right")||b.include("width"),b=b.include("top")||b.include("bottom")||b.include("height"),c===document.viewport?
d?e=document.viewport.getWidth():b&&(e=document.viewport.getHeight()):d?e=$(c).measure("width"):b&&(e=$(c).measure("height")),null===e?0:e*a):0:(c=d.style.left,b=d.runtimeStyle.left,d.runtimeStyle.left=d.currentStyle.left,d.style.left=a||0,a=d.style.pixelLeft,d.style.left=c,d.runtimeStyle.left=b,a)}function b(a){a=$(a);if(a.nodeType===Node.DOCUMENT_NODE||e(a)||"BODY"===a.nodeName.toUpperCase()||"HTML"===a.nodeName.toUpperCase())return $(document.body);if("inline"!==Element.getStyle(a,"display")&&
a.offsetParent)return $(a.offsetParent);for(;(a=a.parentNode)&&a!==document.body;)if("static"!==Element.getStyle(a,"position"))return"HTML"===a.nodeName.toUpperCase()?$(document.body):$(a);return $(document.body)}function c(a){a=$(a);var b=0,c=0;if(a.parentNode){do b+=a.offsetTop||0,c+=a.offsetLeft||0,a=a.offsetParent;while(a)}return new Element.Offset(c,b)}function d(a){a=$(a);var b=a.getLayout(),c=0,d=0;do if(c+=a.offsetTop||0,d+=a.offsetLeft||0,a=a.offsetParent){if("BODY"===a.nodeName.toUpperCase())break;
if("static"!==Element.getStyle(a,"position"))break}while(a);d-=b.get("margin-top");c-=b.get("margin-left");return new Element.Offset(d,c)}function e(a){return a!==document.body&&!Element.descendantOf(a,document.body)}var f=Prototype.K;"currentStyle"in document.documentElement&&(f=function(a){a.currentStyle.hasLayout||(a.style.zoom=1);return a});Element.Layout=Class.create(Hash,{initialize:function($super,a,b){$super();this.element=$(a);Element.Layout.PROPERTIES.each(function(a){this._set(a,null)},
this);b&&(this._preComputing=!0,this._begin(),Element.Layout.PROPERTIES.each(this._compute,this),this._end(),this._preComputing=!1)},_set:function(a,b){return Hash.prototype.set.call(this,a,b)},set:function(a,b){throw"Properties of Element.Layout are read-only.";},get:function($super,a){var b=$super(a);return null===b?this._compute(a):b},_begin:function(){if(!this._prepared){var b=this.element,c;a:{for(c=b;c&&c.parentNode;){if("none"===c.getStyle("display")){c=!1;break a}c=$(c.parentNode)}c=!0}if(!c){b.store("prototype_original_styles",
{position:b.style.position||"",width:b.style.width||"",visibility:b.style.visibility||"",display:b.style.display||""});c=b.getStyle("position");var d=b.getStyle("width");if("0px"===d||null===d)b.style.display="block",d=b.getStyle("width");var e="fixed"===c?document.viewport:b.parentNode;b.setStyle({position:"absolute",visibility:"hidden",display:"block"});var f=b.getStyle("width");c=d&&f===d?a(b,"width",e):"absolute"===c||"fixed"===c?a(b,"width",e):$(b.parentNode).getLayout().get("width")-this.get("margin-left")-
this.get("border-left")-this.get("padding-left")-this.get("padding-right")-this.get("border-right")-this.get("margin-right");b.setStyle({width:c+"px"})}this._prepared=!0}},_end:function(){var a=this.element,b=a.retrieve("prototype_original_styles");a.store("prototype_original_styles",null);a.setStyle(b);this._prepared=!1},_compute:function(a){var b=Element.Layout.COMPUTATIONS;if(!(a in b))throw"Property not found.";return this._set(a,b[a].call(this,this.element))},toObject:function(){var a=$A(arguments),
b={};(0===a.length?Element.Layout.PROPERTIES:a.join(" ").split(" ")).each(function(a){if(Element.Layout.PROPERTIES.include(a)){var c=this.get(a);null!=c&&(b[a]=c)}},this);return b},toHash:function(){var a=this.toObject.apply(this,arguments);return new Hash(a)},toCSS:function(){var a=$A(arguments),b={};(0===a.length?Element.Layout.PROPERTIES:a.join(" ").split(" ")).each(function(a){if(Element.Layout.PROPERTIES.include(a)&&!Element.Layout.COMPOSITE_PROPERTIES.include(a)){var c=this.get(a);null!=c&&
(a.include("border")&&(a+="-width"),a=a.camelize(),b[a]=c+"px")}},this);return b},inspect:function(){return"#<Element.Layout>"}});Object.extend(Element.Layout,{PROPERTIES:$w("height width top left right bottom border-left border-right border-top border-bottom padding-left padding-right padding-top padding-bottom margin-top margin-bottom margin-left margin-right padding-box-width padding-box-height border-box-width border-box-height margin-box-width margin-box-height"),COMPOSITE_PROPERTIES:$w("padding-box-width padding-box-height margin-box-width margin-box-height border-box-width border-box-height"),
COMPUTATIONS:{height:function(a){this._preComputing||this._begin();a=this.get("border-box-height");if(0>=a)return this._preComputing||this._end(),0;var b=this.get("border-top"),c=this.get("border-bottom"),d=this.get("padding-top"),e=this.get("padding-bottom");this._preComputing||this._end();return a-b-c-d-e},width:function(a){this._preComputing||this._begin();a=this.get("border-box-width");if(0>=a)return this._preComputing||this._end(),0;var b=this.get("border-left"),c=this.get("border-right"),d=
this.get("padding-left"),e=this.get("padding-right");this._preComputing||this._end();return a-b-c-d-e},"padding-box-height":function(a){a=this.get("height");var b=this.get("padding-top"),c=this.get("padding-bottom");return a+b+c},"padding-box-width":function(a){a=this.get("width");var b=this.get("padding-left"),c=this.get("padding-right");return a+b+c},"border-box-height":function(a){this._preComputing||this._begin();a=a.offsetHeight;this._preComputing||this._end();return a},"border-box-width":function(a){this._preComputing||
this._begin();a=a.offsetWidth;this._preComputing||this._end();return a},"margin-box-height":function(a){a=this.get("border-box-height");var b=this.get("margin-top"),c=this.get("margin-bottom");return 0>=a?0:a+b+c},"margin-box-width":function(a){a=this.get("border-box-width");var b=this.get("margin-left"),c=this.get("margin-right");return 0>=a?0:a+b+c},top:function(a){return a.positionedOffset().top},bottom:function(a){var b=a.positionedOffset();a=a.getOffsetParent().measure("height");var c=this.get("border-box-height");
return a-c-b.top},left:function(a){return a.positionedOffset().left},right:function(a){var b=a.positionedOffset();a=a.getOffsetParent().measure("width");var c=this.get("border-box-width");return a-c-b.left},"padding-top":function(b){return a(b,"paddingTop")},"padding-bottom":function(b){return a(b,"paddingBottom")},"padding-left":function(b){return a(b,"paddingLeft")},"padding-right":function(b){return a(b,"paddingRight")},"border-top":function(b){return a(b,"borderTopWidth")},"border-bottom":function(b){return a(b,
"borderBottomWidth")},"border-left":function(b){return a(b,"borderLeftWidth")},"border-right":function(b){return a(b,"borderRightWidth")},"margin-top":function(b){return a(b,"marginTop")},"margin-bottom":function(b){return a(b,"marginBottom")},"margin-left":function(b){return a(b,"marginLeft")},"margin-right":function(b){return a(b,"marginRight")}}});"getBoundingClientRect"in document.documentElement&&Object.extend(Element.Layout.COMPUTATIONS,{right:function(a){var b=f(a.getOffsetParent());a=a.getBoundingClientRect();
return(b.getBoundingClientRect().right-a.right).round()},bottom:function(a){var b=f(a.getOffsetParent());a=a.getBoundingClientRect();return(b.getBoundingClientRect().bottom-a.bottom).round()}});Element.Offset=Class.create({initialize:function(a,b){this.left=a.round();this.top=b.round();this[0]=this.left;this[1]=this.top},relativeTo:function(a){return new Element.Offset(this.left-a.left,this.top-a.top)},inspect:function(){return"#<Element.Offset left: #{left} top: #{top}>".interpolate(this)},toString:function(){return"[#{left}, #{top}]".interpolate(this)},
toArray:function(){return[this.left,this.top]}});Prototype.Browser.IE?(b=b.wrap(function(a,b){b=$(b);if(b.nodeType===Node.DOCUMENT_NODE||e(b)||"BODY"===b.nodeName.toUpperCase()||"HTML"===b.nodeName.toUpperCase())return $(document.body);var c=b.getStyle("position");if("static"!==c)return a(b);b.setStyle({position:"relative"});var d=a(b);b.setStyle({position:c});return d}),d=d.wrap(function(a,b){b=$(b);if(!b.parentNode)return new Element.Offset(0,0);var c=b.getStyle("position");if("static"!==c)return a(b);
var d=b.getOffsetParent();d&&"fixed"===d.getStyle("position")&&f(d);b.setStyle({position:"relative"});d=a(b);b.setStyle({position:c});return d})):Prototype.Browser.Webkit&&(c=function(a){a=$(a);var b=0,c=0;do{b+=a.offsetTop||0;c+=a.offsetLeft||0;if(a.offsetParent==document.body&&"absolute"==Element.getStyle(a,"position"))break;a=a.offsetParent}while(a);return new Element.Offset(c,b)});Element.addMethods({getLayout:function(a,b){return new Element.Layout(a,b)},measure:function(a,b){return $(a).getLayout().get(b)},
getDimensions:function(a){a=$(a);var b=Element.getStyle(a,"display");if(b&&"none"!==b)return{width:a.offsetWidth,height:a.offsetHeight};var b=a.style,b={visibility:b.visibility,position:b.position,display:b.display},c={visibility:"hidden",display:"block"};"fixed"!==b.position&&(c.position="absolute");Element.setStyle(a,c);c={width:a.offsetWidth,height:a.offsetHeight};Element.setStyle(a,b);return c},getOffsetParent:b,cumulativeOffset:c,positionedOffset:d,cumulativeScrollOffset:function(a){var b=0,
c=0;do b+=a.scrollTop||0,c+=a.scrollLeft||0,a=a.parentNode;while(a);return new Element.Offset(c,b)},viewportOffset:function(a){$(e);var b=0,c=0,d=document.body,e=a;do if(b+=e.offsetTop||0,c+=e.offsetLeft||0,e.offsetParent==d&&"absolute"==Element.getStyle(e,"position"))break;while(e=e.offsetParent);e=a;do e!=d&&(b-=e.scrollTop||0,c-=e.scrollLeft||0);while(e=e.parentNode);return new Element.Offset(c,b)},absolutize:function(a){a=$(a);if("absolute"===Element.getStyle(a,"position"))return a;var c=b(a),
d=a.viewportOffset(),c=c.viewportOffset(),d=d.relativeTo(c),c=a.getLayout();a.store("prototype_absolutize_original_styles",{left:a.getStyle("left"),top:a.getStyle("top"),width:a.getStyle("width"),height:a.getStyle("height")});a.setStyle({position:"absolute",top:d.top+"px",left:d.left+"px",width:c.get("width")+"px",height:c.get("height")+"px"});return a},relativize:function(a){a=$(a);if("relative"===Element.getStyle(a,"position"))return a;var b=a.retrieve("prototype_absolutize_original_styles");b&&
a.setStyle(b);return a}});"getBoundingClientRect"in document.documentElement&&Element.addMethods({viewportOffset:function(a){a=$(a);if(e(a))return new Element.Offset(0,0);a=a.getBoundingClientRect();var b=document.documentElement;return new Element.Offset(a.left-b.clientLeft,a.top-b.clientTop)}})})();window.$$=function(){var a=$A(arguments).join(", ");return Prototype.Selector.select(a,document)};
Prototype.Selector=function(){function a(a){for(var b=0,e=a.length;b<e;b++)Element.extend(a[b]);return a}var b=Prototype.K;return{select:function(){throw Error('Method "Prototype.Selector.select" must be defined.');},match:function(){throw Error('Method "Prototype.Selector.match" must be defined.');},find:function(a,b,e){e=e||0;var f=Prototype.Selector.match,g=a.length,h=0,l;for(l=0;l<g;l++)if(f(a[l],b)&&e==h++)return Element.extend(a[l])},extendElements:Element.extend===b?b:a,extendElement:Element.extend}}();
(function(){function a(a,b,c,d,e,f){e="previousSibling"==a&&!f;for(var g=0,h=d.length;g<h;g++){var l=d[g];if(l){e&&1===l.nodeType&&(l.sizcache=c,l.sizset=g);for(var l=l[a],m=!1;l;){if(l.sizcache===c){m=d[l.sizset];break}1!==l.nodeType||f||(l.sizcache=c,l.sizset=g);if(l.nodeName===b){m=l;break}l=l[a]}d[g]=m}}}function b(a,b,c,d,e,f){e="previousSibling"==a&&!f;for(var g=0,w=d.length;g<w;g++){var l=d[g];if(l){e&&1===l.nodeType&&(l.sizcache=c,l.sizset=g);for(var l=l[a],m=!1;l;){if(l.sizcache===c){m=d[l.sizset];
break}if(1===l.nodeType)if(f||(l.sizcache=c,l.sizset=g),"string"!==typeof b){if(l===b){m=!0;break}}else if(0<h.filter(b,[l]).length){m=l;break}l=l[a]}d[g]=m}}}var c=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d=0,e=Object.prototype.toString,f=!1,g=!0;[0,0].sort(function(){g=!1;return 0});var h=function(a,b,d,f){d=d||[];var g=b=b||document;if(1!==b.nodeType&&9!==b.nodeType)return[];if(!a||"string"!==typeof a)return d;
for(var q=[],r,w,u,F,t=!0,I=A(b),D=a;null!==(c.exec(""),r=c.exec(D));)if(D=r[3],q.push(r[1]),r[2]){F=r[3];break}if(1<q.length&&m.exec(a))if(2===q.length&&l.relative[q[0]])w=E(q[0]+q[1],b);else for(w=l.relative[q[0]]?[b]:h(q.shift(),b);q.length;)a=q.shift(),l.relative[a]&&(a+=q.shift()),w=E(a,w);else if(!f&&1<q.length&&9===b.nodeType&&!I&&l.match.ID.test(q[0])&&!l.match.ID.test(q[q.length-1])&&(r=h.find(q.shift(),b,I),b=r.expr?h.filter(r.expr,r.set)[0]:r.set[0]),b)for(r=f?{expr:q.pop(),set:n(f)}:h.find(q.pop(),
1!==q.length||"~"!==q[0]&&"+"!==q[0]||!b.parentNode?b:b.parentNode,I),w=r.expr?h.filter(r.expr,r.set):r.set,0<q.length?u=n(w):t=!1;q.length;){var z=q.pop();r=z;l.relative[z]?r=q.pop():z="";null==r&&(r=b);l.relative[z](u,r,I)}else u=[];u||(u=w);if(!u)throw"Syntax error, unrecognized expression: "+(z||a);if("[object Array]"===e.call(u))if(t)if(b&&1===b.nodeType)for(a=0;null!=u[a];a++)u[a]&&(!0===u[a]||1===u[a].nodeType&&G(b,u[a]))&&d.push(w[a]);else for(a=0;null!=u[a];a++)u[a]&&1===u[a].nodeType&&d.push(w[a]);
else d.push.apply(d,u);else n(u,d);F&&(h(F,g,d,f),h.uniqueSort(d));return d};h.uniqueSort=function(a){if(v&&(f=g,a.sort(v),f))for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1);return a};h.matches=function(a,b){return h(a,null,null,b)};h.find=function(a,b,c){var d,e;if(!a)return[];for(var f=0,g=l.order.length;f<g;f++){var h=l.order[f];if(e=l.leftMatch[h].exec(a)){var m=e[1];e.splice(1,1);if("\\"!==m.substr(m.length-1)&&(e[1]=(e[1]||"").replace(/\\/g,""),d=l.find[h](e,b,c),null!=d)){a=a.replace(l.match[h],
"");break}}}d||(d=b.getElementsByTagName("*"));return{set:d,expr:a}};h.filter=function(a,b,c,d){for(var e=a,f=[],g=b,h,m,F=b&&b[0]&&A(b[0]);a&&b.length;){for(var n in l.filter)if(null!=(h=l.match[n].exec(a))){var t=l.filter[n],D,z;m=!1;g==f&&(f=[]);if(l.preFilter[n])if(h=l.preFilter[n](h,g,c,f,d,F),!h)m=D=!0;else if(!0===h)continue;if(h)for(var J=0;null!=(z=g[J]);J++)if(z){D=t(z,h,J,g);var v=d^!!D;c&&null!=D?v?m=!0:g[J]=!1:v&&(f.push(z),m=!0)}if(void 0!==D){c||(g=f);a=a.replace(l.match[n],"");if(!m)return[];
break}}if(a==e){if(null==m)throw"Syntax error, unrecognized expression: "+a;break}e=a}return g};var l=h.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,
PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")}},relative:{"+":function(a,b,c){var d="string"===typeof b,e=d&&!/\W/.test(b),d=d&&!e;e&&!c&&(b=b.toUpperCase());c=0;for(var e=a.length,f;c<e;c++)if(f=a[c]){for(;(f=f.previousSibling)&&1!==f.nodeType;);a[c]=d||f&&f.nodeName===b?f||!1:f===b}d&&h.filter(b,a,!0)},">":function(a,b,c){var d="string"===
typeof b;if(d&&!/\W/.test(b)){b=c?b:b.toUpperCase();c=0;for(var e=a.length;c<e;c++){var f=a[c];f&&(d=f.parentNode,a[c]=d.nodeName===b?d:!1)}}else{c=0;for(e=a.length;c<e;c++)(f=a[c])&&(a[c]=d?f.parentNode:f.parentNode===b);d&&h.filter(b,a,!0)}},"":function(c,e,f){var g=d++,h=b;if(!/\W/.test(e))var l=e=f?e:e.toUpperCase(),h=a;h("parentNode",e,g,c,l,f)},"~":function(c,e,f){var g=d++,h=b;if("string"===typeof e&&!/\W/.test(e))var l=e=f?e:e.toUpperCase(),h=a;h("previousSibling",e,g,c,l,f)}},find:{ID:function(a,
b,c){if("undefined"!==typeof b.getElementById&&!c)return(a=b.getElementById(a[1]))?[a]:[]},NAME:function(a,b,c){if("undefined"!==typeof b.getElementsByName){c=[];b=b.getElementsByName(a[1]);for(var d=0,e=b.length;d<e;d++)b[d].getAttribute("name")===a[1]&&c.push(b[d]);return 0===c.length?null:c}},TAG:function(a,b){return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(/\\/g,"")+" ";if(f)return a;f=0;for(var g;null!=(g=b[f]);f++)g&&(e^(g.className&&0<=(" "+g.className+
" ").indexOf(a))?c||d.push(g):c&&(b[f]=!1));return!1},ID:function(a){return a[1].replace(/\\/g,"")},TAG:function(a,b){for(var c=0;!1===b[c];c++);return b[c]&&A(b[c])?a[1]:a[1].toUpperCase()},CHILD:function(a){if("nth"==a[1]){var b=/(-?)(\d*)n((?:\+|-)?\d*)/.exec("even"==a[2]&&"2n"||"odd"==a[2]&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0;a[3]=b[3]-0}a[0]=d++;return a},ATTR:function(a,b,c,d,e,f){b=a[1].replace(/\\/g,"");!f&&l.attrMap[b]&&(a[1]=l.attrMap[b]);"~="===a[2]&&(a[4]=
" "+a[4]+" ");return a},PSEUDO:function(a,b,d,e,f){if("not"===a[1])if(1<(c.exec(a[3])||"").length||/^\w/.test(a[3]))a[3]=h(a[3],null,null,b);else return a=h.filter(a[3],b,d,1^f),d||e.push.apply(e,a),!1;else if(l.match.POS.test(a[0])||l.match.CHILD.test(a[0]))return!0;return a},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return!1===a.disabled&&"hidden"!==a.type},disabled:function(a){return!0===a.disabled},checked:function(a){return!0===a.checked},selected:function(a){a.parentNode.selectedIndex;
return!0===a.selected},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!h(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){return"text"===a.type},radio:function(a){return"radio"===a.type},checkbox:function(a){return"checkbox"===a.type},file:function(a){return"file"===a.type},password:function(a){return"password"===a.type},submit:function(a){return"submit"===a.type},image:function(a){return"image"===a.type},
reset:function(a){return"reset"===a.type},button:function(a){return"button"===a.type||"BUTTON"===a.nodeName.toUpperCase()},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)}},setFilters:{first:function(a,b){return 0===b},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return 0===b%2},odd:function(a,b){return 1===b%2},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0==b},eq:function(a,b,c){return c[3]-0==
b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=l.filters[e];if(f)return f(a,c,b,d);if("contains"===e)return 0<=(a.textContent||a.innerText||"").indexOf(b[3]);if("not"===e){b=b[3];c=0;for(d=b.length;c<d;c++)if(b[c]===a)return!1;return!0}},CHILD:function(a,b){var c=b[1],d=a;switch(c){case "only":case "first":for(;d=d.previousSibling;)if(1===d.nodeType)return!1;if("first"==c)return!0;d=a;case "last":for(;d=d.nextSibling;)if(1===d.nodeType)return!1;return!0;case "nth":var c=b[2],e=b[3];if(1==c&&0==
e)return!0;var f=b[0],g=a.parentNode;if(g&&(g.sizcache!==f||!a.nodeIndex)){for(var h=0,d=g.firstChild;d;d=d.nextSibling)1===d.nodeType&&(d.nodeIndex=++h);g.sizcache=f}d=a.nodeIndex-e;return 0==c?0==d:0==d%c&&0<=d/c}},ID:function(a,b){return 1===a.nodeType&&a.getAttribute("id")===b},TAG:function(a,b){return"*"===b&&1===a.nodeType||a.nodeName===b},CLASS:function(a,b){return-1<(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)},ATTR:function(a,b){var c=b[1],c=l.attrHandle[c]?l.attrHandle[c](a):
null!=a[c]?a[c]:a.getAttribute(c),d=c+"",e=b[2],f=b[4];return null==c?"!="===e:"="===e?d===f:"*="===e?0<=d.indexOf(f):"~="===e?0<=(" "+d+" ").indexOf(f):f?"!="===e?d!=f:"^="===e?0===d.indexOf(f):"$="===e?d.substr(d.length-f.length)===f:"|="===e?d===f||d.substr(0,f.length+1)===f+"-":!1:d&&!1!==c},POS:function(a,b,c,d){var e=l.setFilters[b[2]];if(e)return e(a,c,b,d)}}},m=l.match.POS,t;for(t in l.match)l.match[t]=new RegExp(l.match[t].source+/(?![^\[]*\])(?![^\(]*\))/.source),l.leftMatch[t]=new RegExp(/(^(?:.|\r|\n)*?)/.source+
l.match[t].source);var n=function(a,b){a=Array.prototype.slice.call(a,0);return b?(b.push.apply(b,a),b):a};try{Array.prototype.slice.call(document.documentElement.childNodes,0)}catch(C){n=function(a,b){var c=b||[];if("[object Array]"===e.call(a))Array.prototype.push.apply(c,a);else if("number"===typeof a.length)for(var d=0,f=a.length;d<f;d++)c.push(a[d]);else for(d=0;a[d];d++)c.push(a[d]);return c}}var v;document.documentElement.compareDocumentPosition?v=function(a,b){if(!a.compareDocumentPosition||
!b.compareDocumentPosition)return a==b&&(f=!0),0;var c=a.compareDocumentPosition(b)&4?-1:a===b?0:1;0===c&&(f=!0);return c}:"sourceIndex"in document.documentElement?v=function(a,b){if(!a.sourceIndex||!b.sourceIndex)return a==b&&(f=!0),0;var c=a.sourceIndex-b.sourceIndex;0===c&&(f=!0);return c}:document.createRange&&(v=function(a,b){if(!a.ownerDocument||!b.ownerDocument)return a==b&&(f=!0),0;var c=a.ownerDocument.createRange(),d=b.ownerDocument.createRange();c.setStart(a,0);c.setEnd(a,0);d.setStart(b,
0);d.setEnd(b,0);c=c.compareBoundaryPoints(Range.START_TO_END,d);0===c&&(f=!0);return c});(function(){var a=document.createElement("div"),b="script"+(new Date).getTime();a.innerHTML="<a name='"+b+"'/>";var c=document.documentElement;c.insertBefore(a,c.firstChild);document.getElementById(b)&&(l.find.ID=function(a,b,c){if("undefined"!==typeof b.getElementById&&!c)return(b=b.getElementById(a[1]))?b.id===a[1]||"undefined"!==typeof b.getAttributeNode&&b.getAttributeNode("id").nodeValue===a[1]?[b]:void 0:
[]},l.filter.ID=function(a,b){var c="undefined"!==typeof a.getAttributeNode&&a.getAttributeNode("id");return 1===a.nodeType&&c&&c.nodeValue===b});c.removeChild(a);c=a=null})();(function(){var a=document.createElement("div");a.appendChild(document.createComment(""));0<a.getElementsByTagName("*").length&&(l.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if("*"===a[1]){for(var d=[],e=0;c[e];e++)1===c[e].nodeType&&d.push(c[e]);c=d}return c});a.innerHTML="<a href='#'></a>";a.firstChild&&"undefined"!==
typeof a.firstChild.getAttribute&&"#"!==a.firstChild.getAttribute("href")&&(l.attrHandle.href=function(a){return a.getAttribute("href",2)});a=null})();document.querySelectorAll&&function(){var a=h,b=document.createElement("div");b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||0!==b.querySelectorAll(".TEST").length){h=function(b,c,d,e){c=c||document;if(!e&&9===c.nodeType&&!A(c))try{return n(c.querySelectorAll(b),d)}catch(f){}return a(b,c,d,e)};for(var c in a)h[c]=a[c];b=null}}();document.getElementsByClassName&&
document.documentElement.getElementsByClassName&&function(){var a=document.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";0!==a.getElementsByClassName("e").length&&(a.lastChild.className="e",1!==a.getElementsByClassName("e").length&&(l.order.splice(1,0,"CLASS"),l.find.CLASS=function(a,b,c){if("undefined"!==typeof b.getElementsByClassName&&!c)return b.getElementsByClassName(a[1])},a=null))}();var G=document.compareDocumentPosition?function(a,b){return a.compareDocumentPosition(b)&
16}:function(a,b){return a!==b&&(a.contains?a.contains(b):!0)},A=function(a){return 9===a.nodeType&&"HTML"!==a.documentElement.nodeName||!!a.ownerDocument&&"HTML"!==a.ownerDocument.documentElement.nodeName},E=function(a,b){for(var c=[],d="",e,f=b.nodeType?[b]:b;e=l.match.PSEUDO.exec(a);)d+=e[0],a=a.replace(l.match.PSEUDO,"");a=l.relative[a]?a+"*":a;e=0;for(var g=f.length;e<g;e++)h(a,f[e],c);return h.filter(d,c)};window.Sizzle=h})();Prototype._original_property=window.Sizzle;
(function(a){var b=Prototype.Selector.extendElements;Prototype.Selector.engine=a;Prototype.Selector.select=function(c,d){return b(a(c,d||document))};Prototype.Selector.match=function(b,d){return 1==a.matches(d,[b]).length}})(Sizzle);window.Sizzle=Prototype._original_property;delete Prototype._original_property;
var Form={reset:function(a){a=$(a);a.reset();return a},serializeElements:function(a,b){"object"!=typeof b?b={hash:!!b}:Object.isUndefined(b.hash)&&(b.hash=!0);var c,d,e=!1,f=b.submit,g,h;b.hash?(h={},g=function(a,b,c){b in a?(Object.isArray(a[b])||(a[b]=[a[b]]),a[b].push(c)):a[b]=c;return a}):(h="",g=function(a,b,c){return a+(a?"&":"")+encodeURIComponent(b)+"="+encodeURIComponent(c)});return a.inject(h,function(a,b){!b.disabled&&b.name&&(c=b.name,d=$(b).getValue(),null==d||"file"==b.type||"submit"==
b.type&&(e||!1===f||f&&c!=f||!(e=!0))||(a=g(a,c,d)));return a})},Methods:{serialize:function(a,b){return Form.serializeElements(Form.getElements(a),b)},getElements:function(a){a=$(a).getElementsByTagName("*");for(var b,c=[],d=Form.Element.Serializers,e=0;b=a[e];e++)c.push(b);return c.inject([],function(a,b){d[b.tagName.toLowerCase()]&&a.push(Element.extend(b));return a})},getInputs:function(a,b,c){a=$(a);a=a.getElementsByTagName("input");if(!b&&!c)return $A(a).map(Element.extend);for(var d=0,e=[],
f=a.length;d<f;d++){var g=a[d];b&&g.type!=b||c&&g.name!=c||e.push(Element.extend(g))}return e},disable:function(a){a=$(a);Form.getElements(a).invoke("disable");return a},enable:function(a){a=$(a);Form.getElements(a).invoke("enable");return a},findFirstElement:function(a){a=$(a).getElements().findAll(function(a){return"hidden"!=a.type&&!a.disabled});var b=a.findAll(function(a){return a.hasAttribute("tabIndex")&&0<=a.tabIndex}).sortBy(function(a){return a.tabIndex}).first();return b?b:a.find(function(a){return/^(?:input|select|textarea)$/i.test(a.tagName)})},
focusFirstElement:function(a){a=$(a);var b=a.findFirstElement();b&&b.activate();return a},request:function(a,b){a=$(a);b=Object.clone(b||{});var c=b.parameters,d=a.readAttribute("action")||"";d.blank()&&(d=window.location.href);b.parameters=a.serialize(!0);c&&(Object.isString(c)&&(c=c.toQueryParams()),Object.extend(b.parameters,c));a.hasAttribute("method")&&!b.method&&(b.method=a.method);return new Ajax.Request(d,b)}},Element:{focus:function(a){$(a).focus();return a},select:function(a){$(a).select();
return a}}};
Form.Element.Methods={serialize:function(a){a=$(a);if(!a.disabled&&a.name){var b=a.getValue();if(void 0!=b){var c={};c[a.name]=b;return Object.toQueryString(c)}}return""},getValue:function(a){a=$(a);var b=a.tagName.toLowerCase();return Form.Element.Serializers[b](a)},setValue:function(a,b){a=$(a);var c=a.tagName.toLowerCase();Form.Element.Serializers[c](a,b);return a},clear:function(a){$(a).value="";return a},present:function(a){return""!=$(a).value},activate:function(a){a=$(a);try{a.focus(),!a.select||
"input"==a.tagName.toLowerCase()&&/^(?:button|reset|submit)$/i.test(a.type)||a.select()}catch(b){}return a},disable:function(a){a=$(a);a.disabled=!0;return a},enable:function(a){a=$(a);a.disabled=!1;return a}};var Field=Form.Element,$F=Form.Element.Methods.getValue;
Form.Element.Serializers=function(){function a(a,b){if(Object.isUndefined(b))return a.checked?a.value:null;a.checked=!!b}function b(a,b){if(Object.isUndefined(b))return a.value;a.value=b}function c(a){var b=a.selectedIndex;return 0<=b?e(a.options[b]):null}function d(a){var b,c=a.length;if(!c)return null;var d=0;for(b=[];d<c;d++){var m=a.options[d];m.selected&&b.push(e(m))}return b}function e(a){return Element.hasAttribute(a,"value")?a.value:a.text}return{input:function(c,d){switch(c.type.toLowerCase()){case "checkbox":case "radio":return a(c,
d);default:return b(c,d)}},inputSelector:a,textarea:b,select:function(a,b){if(Object.isUndefined(b))return("select-one"===a.type?c:d)(a);for(var e,l,m=!Object.isArray(b),t=0,n=a.length;t<n;t++)if(e=a.options[t],l=this.optionValue(e),m){if(l==b){e.selected=!0;break}}else e.selected=b.include(l)},selectOne:c,selectMany:d,optionValue:e,button:b}}();
Abstract.TimedObserver=Class.create(PeriodicalExecuter,{initialize:function($super,b,c,d){$super(d,c);this.element=$(b);this.lastValue=this.getValue()},execute:function(){var a=this.getValue();if(Object.isString(this.lastValue)&&Object.isString(a)?this.lastValue!=a:String(this.lastValue)!=String(a))this.callback(this.element,a),this.lastValue=a}});Form.Element.Observer=Class.create(Abstract.TimedObserver,{getValue:function(){return Form.Element.getValue(this.element)}});
Form.Observer=Class.create(Abstract.TimedObserver,{getValue:function(){return Form.serialize(this.element)}});
Abstract.EventObserver=Class.create({initialize:function(a,b){this.element=$(a);this.callback=b;this.lastValue=this.getValue();"form"==this.element.tagName.toLowerCase()?this.registerFormCallbacks():this.registerCallback(this.element)},onElementEvent:function(){var a=this.getValue();this.lastValue!=a&&(this.callback(this.element,a),this.lastValue=a)},registerFormCallbacks:function(){Form.getElements(this.element).each(this.registerCallback,this)},registerCallback:function(a){if(a.type)switch(a.type.toLowerCase()){case "checkbox":case "radio":Event.observe(a,
"click",this.onElementEvent.bind(this));break;default:Event.observe(a,"change",this.onElementEvent.bind(this))}}});Form.Element.EventObserver=Class.create(Abstract.EventObserver,{getValue:function(){return Form.Element.getValue(this.element)}});Form.EventObserver=Class.create(Abstract.EventObserver,{getValue:function(){return Form.serialize(this.element)}});
(function(){function a(a,b){return a.which?a.which===b+1:a.button===b}function b(a,b){return a.button===C[b]}function c(a,b){switch(b){case 0:return 1==a.which&&!a.metaKey;case 1:return 2==a.which||1==a.which&&a.metaKey;case 2:return 3==a.which;default:return!1}}function d(a){var b=document.documentElement,c=document.body||{scrollLeft:0};return a.pageX||a.clientX+(b.scrollLeft||c.scrollLeft)-(b.clientLeft||0)}function e(a){var b=document.documentElement,c=document.body||{scrollTop:0};return a.pageY||
a.clientY+(b.scrollTop||c.scrollTop)-(b.clientTop||0)}function f(a,b,c){var d=Element.retrieve(a,"prototype_event_registry");Object.isUndefined(d)&&(H.push(a),d=Element.retrieve(a,"prototype_event_registry",$H()));var e=d.get(b);Object.isUndefined(e)&&(e=[],d.set(b,e));if(e.pluck("handler").include(c))return!1;var f;if(b.include(":"))f=function(d){if(Object.isUndefined(d.eventName)||d.eventName!==b)return!1;n.extend(d,a);c.call(a,d)};else if(G||"mouseenter"!==b&&"mouseleave"!==b)f=function(b){n.extend(b,
a);c.call(a,b)};else if("mouseenter"===b||"mouseleave"===b)f=function(b){n.extend(b,a);for(var d=b.relatedTarget;d&&d!==a;)try{d=d.parentNode}catch(e){d=a}d!==a&&c.call(a,b)};f.handler=c;e.push(f);return f}function g(){for(var a=0,b=H.length;a<b;a++)n.stopObserving(H[a]),H[a]=null}function h(a,b,c){a=$(a);c=f(a,b,c);if(!c)return a;b.include(":")?a.addEventListener?a.addEventListener("dataavailable",c,!1):(a.attachEvent("ondataavailable",c),a.attachEvent("onlosecapture",c)):(b=q(b),a.addEventListener?
a.addEventListener(b,c,!1):a.attachEvent("on"+b,c));return a}function l(a,b,c){a=$(a);var d=Element.retrieve(a,"prototype_event_registry");if(!d)return a;if(!b)return d.each(function(b){l(a,b.key)}),a;var e=d.get(b);if(!e)return a;if(!c)return e.each(function(c){l(a,b,c.handler)}),a;for(var f=e.length,g;f--;)if(e[f].handler===c){g=e[f];break}if(!g)return a;b.include(":")?a.removeEventListener?a.removeEventListener("dataavailable",g,!1):(a.detachEvent("ondataavailable",g),a.detachEvent("onlosecapture",
g)):(c=q(b),a.removeEventListener?a.removeEventListener(c,g,!1):a.detachEvent("on"+c,g));d.set(b,e.without(g));return a}function m(a,b,c,d){a=$(a);Object.isUndefined(d)&&(d=!0);a==document&&document.createEvent&&!a.dispatchEvent&&(a=document.documentElement);var e;document.createEvent?(e=document.createEvent("HTMLEvents"),e.initEvent("dataavailable",d,!0)):(e=document.createEventObject(),e.eventType=d?"ondataavailable":"onlosecapture");e.eventName=b;e.memo=c||{};document.createEvent?a.dispatchEvent(e):
a.fireEvent(e.eventType,e);return n.extend(e)}function t(a,b,c,d){a=$(a);Object.isFunction(c)&&Object.isUndefined(d)&&(d=c,c=null);return(new n.Handler(a,b,c,d)).start()}var n={KEY_BACKSPACE:8,KEY_TAB:9,KEY_RETURN:13,KEY_ESC:27,KEY_LEFT:37,KEY_UP:38,KEY_RIGHT:39,KEY_DOWN:40,KEY_DELETE:46,KEY_HOME:36,KEY_END:35,KEY_PAGEUP:33,KEY_PAGEDOWN:34,KEY_INSERT:45,cache:{}},v=document.documentElement,G="onmouseenter"in v&&"onmouseleave"in v,A=function(a){return!1};window.attachEvent&&(A=window.addEventListener?
function(a){return!(a instanceof window.Event)}:function(a){return!0});var E,C={0:1,1:4,2:2};E=window.attachEvent?window.addEventListener?function(c,d){return A(c)?b(c,d):a(c,d)}:b:Prototype.Browser.WebKit?c:a;n.Methods={isLeftClick:function(a){return E(a,0)},isMiddleClick:function(a){return E(a,1)},isRightClick:function(a){return E(a,2)},element:function(a){a=n.extend(a);var b=a.target,c=a.type;(a=a.currentTarget)&&a.tagName&&("load"===c||"error"===c||"click"===c&&"input"===a.tagName.toLowerCase()&&
"radio"===a.type)&&(b=a);b.nodeType==Node.TEXT_NODE&&(b=b.parentNode);return Element.extend(b)},findElement:function(a,b){var c=n.element(a);if(!b)return c;for(;c;){if(Object.isElement(c)&&Prototype.Selector.match(c,b))return Element.extend(c);c=c.parentNode}},pointer:function(a){return{x:d(a),y:e(a)}},pointerX:d,pointerY:e,stop:function(a){n.extend(a);a.preventDefault();a.stopPropagation();a.stopped=!0}};var K=Object.keys(n.Methods).inject({},function(a,b){a[b]=n.Methods[b].methodize();return a});
if(window.attachEvent){var L=function(a){switch(a.type){case "mouseover":case "mouseenter":a=a.fromElement;break;case "mouseout":case "mouseleave":a=a.toElement;break;default:return null}return Element.extend(a)},M={stopPropagation:function(){this.cancelBubble=!0},preventDefault:function(){this.returnValue=!1},inspect:function(){return"[object Event]"}};n.extend=function(a,b){if(!a)return!1;if(!A(a)||a._extendedByPrototype)return a;a._extendedByPrototype=Prototype.emptyFunction;var c=n.pointer(a);
Object.extend(a,{target:a.srcElement||b,relatedTarget:L(a),pageX:c.x,pageY:c.y});Object.extend(a,K);Object.extend(a,M);return a}}else n.extend=Prototype.K;window.addEventListener&&(n.prototype=window.Event.prototype||document.createEvent("HTMLEvents").__proto__,Object.extend(n.prototype,K));var H=[];Prototype.Browser.IE&&window.attachEvent("onunload",g);Prototype.Browser.WebKit&&window.addEventListener("unload",Prototype.emptyFunction,!1);var q=Prototype.K,r={mouseenter:"mouseover",mouseleave:"mouseout"};
G||(q=function(a){return r[a]||a});n.Handler=Class.create({initialize:function(a,b,c,d){this.element=$(a);this.eventName=b;this.selector=c;this.callback=d;this.handler=this.handleEvent.bind(this)},start:function(){n.observe(this.element,this.eventName,this.handler);return this},stop:function(){n.stopObserving(this.element,this.eventName,this.handler);return this},handleEvent:function(a){var b=n.findElement(a,this.selector);b&&this.callback.call(this.element,a,b)}});Object.extend(n,n.Methods);Object.extend(n,
{fire:m,observe:h,stopObserving:l,on:t});Element.addMethods({fire:m,observe:h,stopObserving:l,on:t});Object.extend(document,{fire:m.methodize(),observe:h.methodize(),stopObserving:l.methodize(),on:t.methodize(),loaded:!1});window.Event?Object.extend(window.Event,n):window.Event=n})();
(function(){function a(){document.loaded||(d&&window.clearTimeout(d),document.loaded=!0,document.fire("dom:loaded"))}function b(){"complete"===document.readyState&&(document.stopObserving("readystatechange",b),a())}function c(){try{document.documentElement.doScroll("left")}catch(b){d=c.defer();return}a()}var d;document.addEventListener?document.addEventListener("DOMContentLoaded",a,!1):(document.observe("readystatechange",b),window==top&&(d=c.defer()));Event.observe(window,"load",a)})();Element.addMethods();
Hash.toQueryString=Object.toQueryString;var Toggle={display:Element.toggle};Element.Methods.childOf=Element.Methods.descendantOf;
var Insertion={Before:function(a,b){return Element.insert(a,{before:b})},Top:function(a,b){return Element.insert(a,{top:b})},Bottom:function(a,b){return Element.insert(a,{bottom:b})},After:function(a,b){return Element.insert(a,{after:b})}},$continue=Error('"throw $continue" is deprecated, use "return" instead'),Position={includeScrollOffsets:!1,prepare:function(){this.deltaX=window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft||0;this.deltaY=window.pageYOffset||document.documentElement.scrollTop||
document.body.scrollTop||0},within:function(a,b,c){if(this.includeScrollOffsets)return this.withinIncludingScrolloffsets(a,b,c);this.xcomp=b;this.ycomp=c;this.offset=Element.cumulativeOffset(a);return c>=this.offset[1]&&c<this.offset[1]+a.offsetHeight&&b>=this.offset[0]&&b<this.offset[0]+a.offsetWidth},withinIncludingScrolloffsets:function(a,b,c){var d=Element.cumulativeScrollOffset(a);this.xcomp=b+d[0]-this.deltaX;this.ycomp=c+d[1]-this.deltaY;this.offset=Element.cumulativeOffset(a);return this.ycomp>=
this.offset[1]&&this.ycomp<this.offset[1]+a.offsetHeight&&this.xcomp>=this.offset[0]&&this.xcomp<this.offset[0]+a.offsetWidth},overlap:function(a,b){if(!a)return 0;if("vertical"==a)return(this.offset[1]+b.offsetHeight-this.ycomp)/b.offsetHeight;if("horizontal"==a)return(this.offset[0]+b.offsetWidth-this.xcomp)/b.offsetWidth},cumulativeOffset:Element.Methods.cumulativeOffset,positionedOffset:Element.Methods.positionedOffset,absolutize:function(a){Position.prepare();return Element.absolutize(a)},relativize:function(a){Position.prepare();
return Element.relativize(a)},realOffset:Element.Methods.cumulativeScrollOffset,offsetParent:Element.Methods.getOffsetParent,page:Element.Methods.viewportOffset,clone:function(a,b,c){c=c||{};return Element.clonePosition(b,a,c)}};
document.getElementsByClassName||(document.getElementsByClassName=function(a){function b(a){return a.blank()?null:"[contains(concat(' ', @class, ' '), ' "+a+" ')]"}a.getElementsByClassName=Prototype.BrowserFeatures.XPath?function(a,d){d=d.toString().strip();var e=/\s/.test(d)?$w(d).map(b).join(""):b(d);return e?document._getElementsByXPath(".//*"+e,a):[]}:function(a,b){b=b.toString().strip();var e=[],f=/\s/.test(b)?$w(b):null;if(!f&&!b)return e;var g=$(a).getElementsByTagName("*");b=" "+b+" ";for(var h=
0,l,m;l=g[h];h++)l.className&&(m=" "+l.className+" ")&&(m.include(b)||f&&f.all(function(a){return!a.toString().blank()&&m.include(" "+a+" ")}))&&e.push(Element.extend(l));return e};return function(a,b){return $(b||document.body).getElementsByClassName(a)}}(Element.Methods));Element.ClassNames=Class.create();
Element.ClassNames.prototype={initialize:function(a){this.element=$(a)},_each:function(a){this.element.className.split(/\s+/).select(function(a){return 0<a.length})._each(a)},set:function(a){this.element.className=a},add:function(a){this.include(a)||this.set($A(this).concat(a).join(" "))},remove:function(a){this.include(a)&&this.set($A(this).without(a).join(" "))},toString:function(){return $A(this).join(" ")}};Object.extend(Element.ClassNames.prototype,Enumerable);
(function(){window.Selector=Class.create({initialize:function(a){this.expression=a.strip()},findElements:function(a){return Prototype.Selector.select(this.expression,a)},match:function(a){return Prototype.Selector.match(a,this.expression)},toString:function(){return this.expression},inspect:function(){return"#<Selector: "+this.expression+">"}});Object.extend(Selector,{matchElements:function(a,b){for(var c=Prototype.Selector.match,d=[],e=0,f=a.length;e<f;e++){var g=a[e];c(g,b)&&d.push(Element.extend(g))}return d},
findElement:function(a,b,c){c=c||0;for(var d=0,e,f=0,g=a.length;f<g;f++)if(e=a[f],Prototype.Selector.match(e,b)&&c===d++)return Element.extend(e)},findChildElements:function(a,b){var c=b.toArray().join(", ");return Prototype.Selector.select(c,a||document)}})})();
var Scriptaculous={Version:"1.9.0",require:function(a){try{document.write('<script type="text/javascript" src="'+a+'">\x3c/script>')}catch(c){var b=document.createElement("script");b.type="text/javascript";b.src=a;document.getElementsByTagName("head")[0].appendChild(b)}},REQUIRED_PROTOTYPE:"1.6.0.3",load:function(){function a(a){var b=a.replace(/_.*|\./g,""),b=parseInt(b+"0".times(4-b.length));return-1<a.indexOf("_")?b-1:b}if("undefined"==typeof Prototype||"undefined"==typeof Element||"undefined"==
typeof Element.Methods||a(Prototype.Version)<a(Scriptaculous.REQUIRED_PROTOTYPE))throw"script.aculo.us requires the Prototype JavaScript framework >= "+Scriptaculous.REQUIRED_PROTOTYPE;var b=/scriptaculous\.js(\?.*)?$/;$$("script[src]").findAll(function(a){return a.src.match(b)}).each(function(a){var d=a.src.replace(b,"");a=a.src.match(/\?.*load=([a-z,]*)/);(a?a[1]:"builder,effects,dragdrop,controls,slider,sound").split(",").each(function(a){Scriptaculous.require(d+a+".js")})})}};Scriptaculous.load();
String.prototype.parseColor=function(a){var b="#";if("rgb("==this.slice(0,4)){var c=this.slice(4,this.length-1).split(","),d=0;do b+=parseInt(c[d]).toColorPart();while(3>++d)}else if("#"==this.slice(0,1)){if(4==this.length)for(d=1;4>d;d++)b+=(this.charAt(d)+this.charAt(d)).toLowerCase();7==this.length&&(b=this.toLowerCase())}return 7==b.length?b:a||this};
Element.collectTextNodes=function(a){return $A($(a).childNodes).collect(function(a){return 3==a.nodeType?a.nodeValue:a.hasChildNodes()?Element.collectTextNodes(a):""}).flatten().join("")};Element.collectTextNodesIgnoreClass=function(a,b){return $A($(a).childNodes).collect(function(a){return 3==a.nodeType?a.nodeValue:a.hasChildNodes()&&!Element.hasClassName(a,b)?Element.collectTextNodesIgnoreClass(a,b):""}).flatten().join("")};
Element.setContentZoom=function(a,b){a=$(a);a.setStyle({fontSize:b/100+"em"});Prototype.Browser.WebKit&&window.scrollBy(0,0);return a};Element.getInlineOpacity=function(a){return $(a).style.opacity||""};Element.forceRerendering=function(a){try{a=$(a);var b=document.createTextNode(" ");a.appendChild(b);a.removeChild(b)}catch(c){}};
var Effect={_elementDoesNotExistError:{name:"ElementDoesNotExistError",message:"The specified DOM element does not exist, but is required for this effect to operate"},Transitions:{linear:Prototype.K,sinoidal:function(a){return-Math.cos(a*Math.PI)/2+.5},reverse:function(a){return 1-a},flicker:function(a){a=-Math.cos(a*Math.PI)/4+.75+Math.random()/4;return 1<a?1:a},wobble:function(a){return-Math.cos(a*Math.PI*9*a)/2+.5},pulse:function(a,b){return-Math.cos(a*((b||5)-.5)*2*Math.PI)/2+.5},spring:function(a){return 1-
Math.cos(4.5*a*Math.PI)*Math.exp(6*-a)},none:function(a){return 0},full:function(a){return 1}},DefaultOptions:{duration:1,fps:100,sync:!1,from:0,to:1,delay:0,queue:"parallel"},tagifyText:function(a){var b="position:relative";Prototype.Browser.IE&&(b+=";zoom:1");a=$(a);$A(a.childNodes).each(function(c){3==c.nodeType&&(c.nodeValue.toArray().each(function(d){a.insertBefore((new Element("span",{style:b})).update(" "==d?String.fromCharCode(160):d),c)}),Element.remove(c))})},multiple:function(a,b,c){a=
("object"==typeof a||Object.isFunction(a))&&a.length?a:$(a).childNodes;var d=Object.extend({speed:.1,delay:0},c||{}),e=d.delay;$A(a).each(function(a,c){new b(a,Object.extend(d,{delay:c*d.speed+e}))})},PAIRS:{slide:["SlideDown","SlideUp"],blind:["BlindDown","BlindUp"],appear:["Appear","Fade"]},toggle:function(a,b,c){a=$(a);b=(b||"appear").toLowerCase();return Effect[Effect.PAIRS[b][a.visible()?1:0]](a,Object.extend({queue:{position:"end",scope:a.id||"global",limit:1}},c||{}))}};
Effect.DefaultOptions.transition=Effect.Transitions.sinoidal;
Effect.ScopedQueue=Class.create(Enumerable,{initialize:function(){this.effects=[];this.interval=null},_each:function(a){this.effects._each(a)},add:function(a){var b=(new Date).getTime();switch(Object.isString(a.options.queue)?a.options.queue:a.options.queue.position){case "front":this.effects.findAll(function(a){return"idle"==a.state}).each(function(b){b.startOn+=a.finishOn;b.finishOn+=a.finishOn});break;case "with-last":b=this.effects.pluck("startOn").max()||b;break;case "end":b=this.effects.pluck("finishOn").max()||
b}a.startOn+=b;a.finishOn+=b;(!a.options.queue.limit||this.effects.length<a.options.queue.limit)&&this.effects.push(a);this.interval||(this.interval=setInterval(this.loop.bind(this),15))},remove:function(a){this.effects=this.effects.reject(function(b){return b==a});0==this.effects.length&&(clearInterval(this.interval),this.interval=null)},loop:function(){for(var a=(new Date).getTime(),b=0,c=this.effects.length;b<c;b++)this.effects[b]&&this.effects[b].loop(a)}});
Effect.Queues={instances:$H(),get:function(a){return Object.isString(a)?this.instances.get(a)||this.instances.set(a,new Effect.ScopedQueue):a}};Effect.Queue=Effect.Queues.get("global");
Effect.Base=Class.create({position:null,start:function(a){a&&!1===a.transition&&(a.transition=Effect.Transitions.linear);this.options=Object.extend(Object.extend({},Effect.DefaultOptions),a||{});this.currentFrame=0;this.state="idle";this.startOn=1E3*this.options.delay;this.finishOn=this.startOn+1E3*this.options.duration;this.fromToDelta=this.options.to-this.options.from;this.totalTime=this.finishOn-this.startOn;this.totalFrames=this.options.fps*this.options.duration;this.render=function(){function a(b,
d){if(b.options[d+"Internal"])b.options[d+"Internal"](b);if(b.options[d])b.options[d](b)}return function(c){"idle"===this.state&&(this.state="running",a(this,"beforeSetup"),this.setup&&this.setup(),a(this,"afterSetup"));"running"===this.state&&(this.position=c=this.options.transition(c)*this.fromToDelta+this.options.from,a(this,"beforeUpdate"),this.update&&this.update(c),a(this,"afterUpdate"))}}();this.event("beforeStart");this.options.sync||Effect.Queues.get(Object.isString(this.options.queue)?"global":
this.options.queue.scope).add(this)},loop:function(a){if(a>=this.startOn)if(a>=this.finishOn)this.render(1),this.cancel(),this.event("beforeFinish"),this.finish&&this.finish(),this.event("afterFinish");else{a=(a-this.startOn)/this.totalTime;var b=(a*this.totalFrames).round();b>this.currentFrame&&(this.render(a),this.currentFrame=b)}},cancel:function(){this.options.sync||Effect.Queues.get(Object.isString(this.options.queue)?"global":this.options.queue.scope).remove(this);this.state="finished"},event:function(a){if(this.options[a+
"Internal"])this.options[a+"Internal"](this);if(this.options[a])this.options[a](this)},inspect:function(){var a=$H();for(property in this)Object.isFunction(this[property])||a.set(property,this[property]);return"#<Effect:"+a.inspect()+",options:"+$H(this.options).inspect()+">"}});
Effect.Parallel=Class.create(Effect.Base,{initialize:function(a,b){this.effects=a||[];this.start(b)},update:function(a){this.effects.invoke("render",a)},finish:function(a){this.effects.each(function(b){b.render(1);b.cancel();b.event("beforeFinish");b.finish&&b.finish(a);b.event("afterFinish")})}});
Effect.Tween=Class.create(Effect.Base,{initialize:function(a,b,c){a=Object.isString(a)?$(a):a;var d=$A(arguments),e=d.last(),d=5==d.length?d[3]:null;this.method=Object.isFunction(e)?e.bind(a):Object.isFunction(a[e])?a[e].bind(a):function(b){a[e]=b};this.start(Object.extend({from:b,to:c},d||{}))},update:function(a){this.method(a)}});Effect.Event=Class.create(Effect.Base,{initialize:function(a){this.start(Object.extend({duration:0},a||{}))},update:Prototype.emptyFunction});
Effect.Opacity=Class.create(Effect.Base,{initialize:function(a,b){this.element=$(a);if(!this.element)throw Effect._elementDoesNotExistError;Prototype.Browser.IE&&!this.element.currentStyle.hasLayout&&this.element.setStyle({zoom:1});var c=Object.extend({from:this.element.getOpacity()||0,to:1},b||{});this.start(c)},update:function(a){this.element.setOpacity(a)}});
Effect.Move=Class.create(Effect.Base,{initialize:function(a,b){this.element=$(a);if(!this.element)throw Effect._elementDoesNotExistError;var c=Object.extend({x:0,y:0,mode:"relative"},b||{});this.start(c)},setup:function(){this.element.makePositioned();this.originalLeft=parseFloat(this.element.getStyle("left")||"0");this.originalTop=parseFloat(this.element.getStyle("top")||"0");"absolute"==this.options.mode&&(this.options.x-=this.originalLeft,this.options.y-=this.originalTop)},update:function(a){this.element.setStyle({left:(this.options.x*
a+this.originalLeft).round()+"px",top:(this.options.y*a+this.originalTop).round()+"px"})}});Effect.MoveBy=function(a,b,c,d){return new Effect.Move(a,Object.extend({x:c,y:b},d||{}))};
Effect.Scale=Class.create(Effect.Base,{initialize:function(a,b,c){this.element=$(a);if(!this.element)throw Effect._elementDoesNotExistError;a=Object.extend({scaleX:!0,scaleY:!0,scaleContent:!0,scaleFromCenter:!1,scaleMode:"box",scaleFrom:100,scaleTo:b},c||{});this.start(a)},setup:function(){this.restoreAfterFinish=this.options.restoreAfterFinish||!1;this.elementPositioning=this.element.getStyle("position");this.originalStyle={};["top","left","width","height","fontSize"].each(function(a){this.originalStyle[a]=
this.element.style[a]}.bind(this));this.originalTop=this.element.offsetTop;this.originalLeft=this.element.offsetLeft;var a=this.element.getStyle("font-size")||"100%";["em","px","%","pt"].each(function(b){0<a.indexOf(b)&&(this.fontSize=parseFloat(a),this.fontSizeType=b)}.bind(this));this.factor=(this.options.scaleTo-this.options.scaleFrom)/100;this.dims=null;"box"==this.options.scaleMode&&(this.dims=[this.element.offsetHeight,this.element.offsetWidth]);/^content/.test(this.options.scaleMode)&&(this.dims=
[this.element.scrollHeight,this.element.scrollWidth]);this.dims||(this.dims=[this.options.scaleMode.originalHeight,this.options.scaleMode.originalWidth])},update:function(a){a=this.options.scaleFrom/100+this.factor*a;this.options.scaleContent&&this.fontSize&&this.element.setStyle({fontSize:this.fontSize*a+this.fontSizeType});this.setDimensions(this.dims[0]*a,this.dims[1]*a)},finish:function(a){this.restoreAfterFinish&&this.element.setStyle(this.originalStyle)},setDimensions:function(a,b){var c={};
this.options.scaleX&&(c.width=b.round()+"px");this.options.scaleY&&(c.height=a.round()+"px");if(this.options.scaleFromCenter){var d=(a-this.dims[0])/2,e=(b-this.dims[1])/2;"absolute"==this.elementPositioning?(this.options.scaleY&&(c.top=this.originalTop-d+"px"),this.options.scaleX&&(c.left=this.originalLeft-e+"px")):(this.options.scaleY&&(c.top=-d+"px"),this.options.scaleX&&(c.left=-e+"px"))}this.element.setStyle(c)}});
Effect.Highlight=Class.create(Effect.Base,{initialize:function(a,b){this.element=$(a);if(!this.element)throw Effect._elementDoesNotExistError;var c=Object.extend({startcolor:"#ffff99"},b||{});this.start(c)},setup:function(){"none"==this.element.getStyle("display")?this.cancel():(this.oldStyle={},this.options.keepBackgroundImage||(this.oldStyle.backgroundImage=this.element.getStyle("background-image"),this.element.setStyle({backgroundImage:"none"})),this.options.endcolor||(this.options.endcolor=this.element.getStyle("background-color").parseColor("#ffffff")),
this.options.restorecolor||(this.options.restorecolor=this.element.getStyle("background-color")),this._base=$R(0,2).map(function(a){return parseInt(this.options.startcolor.slice(2*a+1,2*a+3),16)}.bind(this)),this._delta=$R(0,2).map(function(a){return parseInt(this.options.endcolor.slice(2*a+1,2*a+3),16)-this._base[a]}.bind(this)))},update:function(a){this.element.setStyle({backgroundColor:$R(0,2).inject("#",function(b,c,d){return b+(this._base[d]+this._delta[d]*a).round().toColorPart()}.bind(this))})},
finish:function(){this.element.setStyle(Object.extend(this.oldStyle,{backgroundColor:this.options.restorecolor}))}});Effect.ScrollTo=function(a,b){var c=b||{},d=document.viewport.getScrollOffsets(),e=$(a).cumulativeOffset();c.offset&&(e[1]+=c.offset);return new Effect.Tween(null,d.top,e[1],c,function(a){scrollTo(d.left,a.round())})};
Effect.Fade=function(a,b){a=$(a);var c=a.getInlineOpacity(),d=Object.extend({from:a.getOpacity()||1,to:0,afterFinishInternal:function(a){0==a.options.to&&a.element.hide().setStyle({opacity:c})}},b||{});return new Effect.Opacity(a,d)};
Effect.Appear=function(a,b){a=$(a);var c=Object.extend({from:"none"==a.getStyle("display")?0:a.getOpacity()||0,to:1,afterFinishInternal:function(a){a.element.forceRerendering()},beforeSetup:function(a){a.element.setOpacity(a.options.from).show()}},b||{});return new Effect.Opacity(a,c)};
Effect.Puff=function(a,b){a=$(a);var c={opacity:a.getInlineOpacity(),position:a.getStyle("position"),top:a.style.top,left:a.style.left,width:a.style.width,height:a.style.height};return new Effect.Parallel([new Effect.Scale(a,200,{sync:!0,scaleFromCenter:!0,scaleContent:!0,restoreAfterFinish:!0}),new Effect.Opacity(a,{sync:!0,to:0})],Object.extend({duration:1,beforeSetupInternal:function(a){Position.absolutize(a.effects[0].element)},afterFinishInternal:function(a){a.effects[0].element.hide().setStyle(c)}},
b||{}))};Effect.BlindUp=function(a,b){a=$(a);a.makeClipping();return new Effect.Scale(a,0,Object.extend({scaleContent:!1,scaleX:!1,restoreAfterFinish:!0,afterFinishInternal:function(a){a.element.hide().undoClipping()}},b||{}))};
Effect.BlindDown=function(a,b){a=$(a);var c=a.getDimensions();return new Effect.Scale(a,100,Object.extend({scaleContent:!1,scaleX:!1,scaleFrom:0,scaleMode:{originalHeight:c.height,originalWidth:c.width},restoreAfterFinish:!0,afterSetup:function(a){a.element.makeClipping().setStyle({height:"0px"}).show()},afterFinishInternal:function(a){a.element.undoClipping()}},b||{}))};
Effect.SwitchOff=function(a,b){a=$(a);var c=a.getInlineOpacity();return new Effect.Appear(a,Object.extend({duration:.4,from:0,transition:Effect.Transitions.flicker,afterFinishInternal:function(a){new Effect.Scale(a.element,1,{duration:.3,scaleFromCenter:!0,scaleX:!1,scaleContent:!1,restoreAfterFinish:!0,beforeSetup:function(a){a.element.makePositioned().makeClipping()},afterFinishInternal:function(a){a.element.hide().undoClipping().undoPositioned().setStyle({opacity:c})}})}},b||{}))};
Effect.DropOut=function(a,b){a=$(a);var c={top:a.getStyle("top"),left:a.getStyle("left"),opacity:a.getInlineOpacity()};return new Effect.Parallel([new Effect.Move(a,{x:0,y:100,sync:!0}),new Effect.Opacity(a,{sync:!0,to:0})],Object.extend({duration:.5,beforeSetup:function(a){a.effects[0].element.makePositioned()},afterFinishInternal:function(a){a.effects[0].element.hide().undoPositioned().setStyle(c)}},b||{}))};
Effect.Shake=function(a,b){a=$(a);var c=Object.extend({distance:20,duration:.5},b||{}),d=parseFloat(c.distance),e=parseFloat(c.duration)/10,f={top:a.getStyle("top"),left:a.getStyle("left")};return new Effect.Move(a,{x:d,y:0,duration:e,afterFinishInternal:function(a){new Effect.Move(a.element,{x:2*-d,y:0,duration:2*e,afterFinishInternal:function(a){new Effect.Move(a.element,{x:2*d,y:0,duration:2*e,afterFinishInternal:function(a){new Effect.Move(a.element,{x:2*-d,y:0,duration:2*e,afterFinishInternal:function(a){new Effect.Move(a.element,
{x:2*d,y:0,duration:2*e,afterFinishInternal:function(a){new Effect.Move(a.element,{x:-d,y:0,duration:e,afterFinishInternal:function(a){a.element.undoPositioned().setStyle(f)}})}})}})}})}})}})};
Effect.SlideDown=function(a,b){a=$(a).cleanWhitespace();var c=a.down().getStyle("bottom"),d=a.getDimensions();return new Effect.Scale(a,100,Object.extend({scaleContent:!1,scaleX:!1,scaleFrom:window.opera?0:1,scaleMode:{originalHeight:d.height,originalWidth:d.width},restoreAfterFinish:!0,afterSetup:function(a){a.element.makePositioned();a.element.down().makePositioned();window.opera&&a.element.setStyle({top:""});a.element.makeClipping().setStyle({height:"0px"}).show()},afterUpdateInternal:function(a){a.element.down().setStyle({bottom:a.dims[0]-
a.element.clientHeight+"px"})},afterFinishInternal:function(a){a.element.undoClipping().undoPositioned();a.element.down().undoPositioned().setStyle({bottom:c})}},b||{}))};
Effect.SlideUp=function(a,b){a=$(a).cleanWhitespace();var c=a.down().getStyle("bottom"),d=a.getDimensions();return new Effect.Scale(a,window.opera?0:1,Object.extend({scaleContent:!1,scaleX:!1,scaleMode:"box",scaleFrom:100,scaleMode:{originalHeight:d.height,originalWidth:d.width},restoreAfterFinish:!0,afterSetup:function(a){a.element.makePositioned();a.element.down().makePositioned();window.opera&&a.element.setStyle({top:""});a.element.makeClipping().show()},afterUpdateInternal:function(a){a.element.down().setStyle({bottom:a.dims[0]-
a.element.clientHeight+"px"})},afterFinishInternal:function(a){a.element.hide().undoClipping().undoPositioned();a.element.down().undoPositioned().setStyle({bottom:c})}},b||{}))};Effect.Squish=function(a){return new Effect.Scale(a,window.opera?1:0,{restoreAfterFinish:!0,beforeSetup:function(a){a.element.makeClipping()},afterFinishInternal:function(a){a.element.hide().undoClipping()}})};
Effect.Grow=function(a,b){a=$(a);var c=Object.extend({direction:"center",moveTransition:Effect.Transitions.sinoidal,scaleTransition:Effect.Transitions.sinoidal,opacityTransition:Effect.Transitions.full},b||{}),d={top:a.style.top,left:a.style.left,height:a.style.height,width:a.style.width,opacity:a.getInlineOpacity()},e=a.getDimensions(),f,g,h,l;switch(c.direction){case "top-left":f=g=h=l=0;break;case "top-right":f=e.width;g=l=0;h=-e.width;break;case "bottom-left":f=h=0;g=e.height;l=-e.height;break;
case "bottom-right":f=e.width;g=e.height;h=-e.width;l=-e.height;break;case "center":f=e.width/2,g=e.height/2,h=-e.width/2,l=-e.height/2}return new Effect.Move(a,{x:f,y:g,duration:.01,beforeSetup:function(a){a.element.hide().makeClipping().makePositioned()},afterFinishInternal:function(a){new Effect.Parallel([new Effect.Opacity(a.element,{sync:!0,to:1,from:0,transition:c.opacityTransition}),new Effect.Move(a.element,{x:h,y:l,sync:!0,transition:c.moveTransition}),new Effect.Scale(a.element,100,{scaleMode:{originalHeight:e.height,
originalWidth:e.width},sync:!0,scaleFrom:window.opera?1:0,transition:c.scaleTransition,restoreAfterFinish:!0})],Object.extend({beforeSetup:function(a){a.effects[0].element.setStyle({height:"0px"}).show()},afterFinishInternal:function(a){a.effects[0].element.undoClipping().undoPositioned().setStyle(d)}},c))}})};
Effect.Shrink=function(a,b){a=$(a);var c=Object.extend({direction:"center",moveTransition:Effect.Transitions.sinoidal,scaleTransition:Effect.Transitions.sinoidal,opacityTransition:Effect.Transitions.none},b||{}),d={top:a.style.top,left:a.style.left,height:a.style.height,width:a.style.width,opacity:a.getInlineOpacity()},e=a.getDimensions(),f,g;switch(c.direction){case "top-left":f=g=0;break;case "top-right":f=e.width;g=0;break;case "bottom-left":f=0;g=e.height;break;case "bottom-right":f=e.width;g=
e.height;break;case "center":f=e.width/2,g=e.height/2}return new Effect.Parallel([new Effect.Opacity(a,{sync:!0,to:0,from:1,transition:c.opacityTransition}),new Effect.Scale(a,window.opera?1:0,{sync:!0,transition:c.scaleTransition,restoreAfterFinish:!0}),new Effect.Move(a,{x:f,y:g,sync:!0,transition:c.moveTransition})],Object.extend({beforeStartInternal:function(a){a.effects[0].element.makePositioned().makeClipping()},afterFinishInternal:function(a){a.effects[0].element.hide().undoClipping().undoPositioned().setStyle(d)}},
c))};Effect.Pulsate=function(a,b){a=$(a);var c=b||{},d=a.getInlineOpacity(),e=c.transition||Effect.Transitions.linear;return new Effect.Opacity(a,Object.extend(Object.extend({duration:2,from:0,afterFinishInternal:function(a){a.element.setStyle({opacity:d})}},c),{transition:function(a){return 1-e(-Math.cos(a*(c.pulses||5)*2*Math.PI)/2+.5)}}))};
Effect.Fold=function(a,b){a=$(a);var c={top:a.style.top,left:a.style.left,width:a.style.width,height:a.style.height};a.makeClipping();return new Effect.Scale(a,5,Object.extend({scaleContent:!1,scaleX:!1,afterFinishInternal:function(b){new Effect.Scale(a,1,{scaleContent:!1,scaleY:!1,afterFinishInternal:function(a){a.element.hide().undoClipping().setStyle(c)}})}},b||{}))};
Effect.Morph=Class.create(Effect.Base,{initialize:function(a,b){this.element=$(a);if(!this.element)throw Effect._elementDoesNotExistError;var c=Object.extend({style:{}},b||{});if(Object.isString(c.style))if(c.style.include(":"))this.style=c.style.parseStyle();else{this.element.addClassName(c.style);this.style=$H(this.element.getStyles());this.element.removeClassName(c.style);var d=this.element.getStyles();this.style=this.style.reject(function(a){return a.value==d[a.key]});c.afterFinishInternal=function(a){a.element.addClassName(a.options.style);
a.transforms.each(function(b){a.element.style[b.style]=""})}}else this.style=$H(c.style);this.start(c)},setup:function(){function a(a){if(!a||["rgba(0, 0, 0, 0)","transparent"].include(a))a="#ffffff";a=a.parseColor();return $R(0,2).map(function(c){return parseInt(a.slice(2*c+1,2*c+3),16)})}this.transforms=this.style.map(function(b){var c=b[0];b=b[1];var d=null;"#zzzzzz"!=b.parseColor("#zzzzzz")?(b=b.parseColor(),d="color"):"opacity"==c?(b=parseFloat(b),Prototype.Browser.IE&&!this.element.currentStyle.hasLayout&&
this.element.setStyle({zoom:1})):Element.CSS_LENGTH.test(b)&&(d=b.match(/^([\+\-]?[0-9\.]+)(.*)$/),b=parseFloat(d[1]),d=3==d.length?d[2]:null);var e=this.element.getStyle(c);return{style:c.camelize(),originalValue:"color"==d?a(e):parseFloat(e||0),targetValue:"color"==d?a(b):b,unit:d}}.bind(this)).reject(function(a){return a.originalValue==a.targetValue||"color"!=a.unit&&(isNaN(a.originalValue)||isNaN(a.targetValue))})},update:function(a){for(var b={},c,d=this.transforms.length;d--;)b[(c=this.transforms[d]).style]=
"color"==c.unit?"#"+Math.round(c.originalValue[0]+(c.targetValue[0]-c.originalValue[0])*a).toColorPart()+Math.round(c.originalValue[1]+(c.targetValue[1]-c.originalValue[1])*a).toColorPart()+Math.round(c.originalValue[2]+(c.targetValue[2]-c.originalValue[2])*a).toColorPart():(c.originalValue+(c.targetValue-c.originalValue)*a).toFixed(3)+(null===c.unit?"":c.unit);this.element.setStyle(b,!0)}});
Effect.Transform=Class.create({initialize:function(a,b){this.tracks=[];this.options=b||{};this.addTracks(a)},addTracks:function(a){a.each(function(a){a=$H(a);var c=a.values().first();this.tracks.push($H({ids:a.keys().first(),effect:Effect.Morph,options:{style:c}}))}.bind(this));return this},play:function(){return new Effect.Parallel(this.tracks.map(function(a){var b=a.get("ids"),c=a.get("effect"),d=a.get("options");return[$(b)||$$(b)].flatten().map(function(a){return new c(a,Object.extend({sync:!0},
d))})}).flatten(),this.options)}});Element.CSS_PROPERTIES=$w("backgroundColor backgroundPosition borderBottomColor borderBottomStyle borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth borderRightColor borderRightStyle borderRightWidth borderSpacing borderTopColor borderTopStyle borderTopWidth bottom clip color fontSize fontWeight height left letterSpacing lineHeight marginBottom marginLeft marginRight marginTop markerOffset maxHeight maxWidth minHeight minWidth opacity outlineColor outlineOffset outlineWidth paddingBottom paddingLeft paddingRight paddingTop right textIndent top width wordSpacing zIndex");
Element.CSS_LENGTH=/^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;String.__parseStyleElement=document.createElement("div");
String.prototype.parseStyle=function(){var a,b=$H();Prototype.Browser.WebKit?a=(new Element("div",{style:this})).style:(String.__parseStyleElement.innerHTML='<div style="'+this+'"></div>',a=String.__parseStyleElement.childNodes[0].style);Element.CSS_PROPERTIES.each(function(c){a[c]&&b.set(c,a[c])});Prototype.Browser.IE&&this.include("opacity")&&b.set("opacity",this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);return b};
Element.getStyles=document.defaultView&&document.defaultView.getComputedStyle?function(a){var b=document.defaultView.getComputedStyle($(a),null);return Element.CSS_PROPERTIES.inject({},function(a,d){a[d]=b[d];return a})}:function(a){a=$(a);var b=a.currentStyle,c;c=Element.CSS_PROPERTIES.inject({},function(a,c){a[c]=b[c];return a});c.opacity||(c.opacity=a.getOpacity());return c};
Effect.Methods={morph:function(a,b,c){a=$(a);new Effect.Morph(a,Object.extend({style:b},c||{}));return a},visualEffect:function(a,b,c){a=$(a);b=b.dasherize().camelize();b=b.charAt(0).toUpperCase()+b.substring(1);new Effect[b](a,c);return a},highlight:function(a,b){a=$(a);new Effect.Highlight(a,b);return a}};
$w("fade appear grow shrink fold blindUp blindDown slideUp slideDown pulsate shake puff squish switchOff dropOut").each(function(a){Effect.Methods[a]=function(b,c){b=$(b);Effect[a.charAt(0).toUpperCase()+a.substring(1)](b,c);return b}});$w("getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles").each(function(a){Effect.Methods[a]=Element[a]});Element.addMethods(Effect.Methods);
var Builder={NODEMAP:{AREA:"map",CAPTION:"table",COL:"table",COLGROUP:"table",LEGEND:"fieldset",OPTGROUP:"select",OPTION:"select",PARAM:"object",TBODY:"table",TD:"table",TFOOT:"table",TH:"table",THEAD:"table",TR:"table"},node:function(a,b,c){a=a.toUpperCase();var d=document.createElement(this.NODEMAP[a]||"div");try{d.innerHTML="<"+a+"></"+a+">"}catch(g){}var e=d.firstChild||null;e&&e.tagName.toUpperCase()!=a&&(e=e.getElementsByTagName(a)[0]);e||(e=document.createElement(a));if(e){if(b)if(this._isStringOrNumber(b)||
b instanceof Array||b.tagName)this._children(e,b);else{var f=this._attributes(b);if(f.length){try{d.innerHTML="<"+a+" "+f+"></"+a+">"}catch(g){}e=d.firstChild||null;if(!e)for(attr in e=document.createElement(a),b)e["class"==attr?"className":attr]=b[attr];e.tagName.toUpperCase()!=a&&(e=d.getElementsByTagName(a)[0])}}c&&this._children(e,c);return $(e)}},_text:function(a){return document.createTextNode(a)},ATTR_MAP:{className:"class",htmlFor:"for"},_attributes:function(a){var b=[];for(attribute in a)b.push((attribute in
this.ATTR_MAP?this.ATTR_MAP[attribute]:attribute)+'="'+a[attribute].toString().escapeHTML().gsub(/"/,"&quot;")+'"');return b.join(" ")},_children:function(a,b){b.tagName?a.appendChild(b):"object"==typeof b?b.flatten().each(function(b){"object"==typeof b?a.appendChild(b):Builder._isStringOrNumber(b)&&a.appendChild(Builder._text(b))}):Builder._isStringOrNumber(b)&&a.appendChild(Builder._text(b))},_isStringOrNumber:function(a){return"string"==typeof a||"number"==typeof a},build:function(a){var b=this.node("div");
$(b).update(a.strip());return b.down()},dump:function(a){"object"!=typeof a&&"function"!=typeof a&&(a=window);"A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR".split(/\s+/).each(function(b){a[b]=
function(){return Builder.node.apply(Builder,[b].concat($A(arguments)))}})}};if("undefined"==typeof Effect)throw"controls.js requires including script.aculo.us' effects.js library";var Autocompleter={};
Autocompleter.Base=Class.create({baseInitialize:function(a,b,c){this.element=a=$(a);this.update=$(b);this.active=this.changed=this.hasFocus=!1;this.entryCount=this.index=0;this.oldElementValue=this.element.value;this.setOptions?this.setOptions(c):this.options=c||{};this.options.paramName=this.options.paramName||this.element.name;this.options.tokens=this.options.tokens||[];this.options.frequency=this.options.frequency||.4;this.options.minChars=this.options.minChars||1;this.options.onShow=this.options.onShow||
function(a,b){b.style.position&&"absolute"!=b.style.position||(b.style.position="absolute",Position.clone(a,b,{setHeight:!1,offsetTop:a.offsetHeight}));Effect.Appear(b,{duration:.15})};this.options.onHide=this.options.onHide||function(a,b){new Effect.Fade(b,{duration:.15})};"string"==typeof this.options.tokens&&(this.options.tokens=Array(this.options.tokens));this.options.tokens.include("\n")||this.options.tokens.push("\n");this.observer=null;this.element.setAttribute("autocomplete","off");Element.hide(this.update);
Event.observe(this.element,"blur",this.onBlur.bindAsEventListener(this));Event.observe(this.element,"keydown",this.onKeyPress.bindAsEventListener(this))},show:function(){if("none"==Element.getStyle(this.update,"display"))this.options.onShow(this.element,this.update);!this.iefix&&Prototype.Browser.IE&&"absolute"==Element.getStyle(this.update,"position")&&(new Insertion.After(this.update,'<iframe id="'+this.update.id+'_iefix" style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" src="javascript:false;" frameborder="0" scrolling="no"></iframe>'),
this.iefix=$(this.update.id+"_iefix"));this.iefix&&setTimeout(this.fixIEOverlapping.bind(this),50)},fixIEOverlapping:function(){Position.clone(this.update,this.iefix,{setTop:!this.update.style.height});this.iefix.style.zIndex=1;this.update.style.zIndex=2;Element.show(this.iefix)},hide:function(){this.stopIndicator();if("none"!=Element.getStyle(this.update,"display"))this.options.onHide(this.element,this.update);this.iefix&&Element.hide(this.iefix)},startIndicator:function(){this.options.indicator&&
Element.show(this.options.indicator)},stopIndicator:function(){this.options.indicator&&Element.hide(this.options.indicator)},onKeyPress:function(a){if(this.active)switch(a.keyCode){case Event.KEY_TAB:case Event.KEY_RETURN:this.selectEntry(),Event.stop(a);case Event.KEY_ESC:this.hide();this.active=!1;Event.stop(a);return;case Event.KEY_LEFT:case Event.KEY_RIGHT:return;case Event.KEY_UP:this.markPrevious();this.render();Event.stop(a);return;case Event.KEY_DOWN:this.markNext();this.render();Event.stop(a);
return}else if(a.keyCode==Event.KEY_TAB||a.keyCode==Event.KEY_RETURN||0<Prototype.Browser.WebKit&&0==a.keyCode)return;this.hasFocus=this.changed=!0;this.observer&&clearTimeout(this.observer);this.observer=setTimeout(this.onObserverEvent.bind(this),1E3*this.options.frequency)},activate:function(){this.changed=!1;this.hasFocus=!0;this.getUpdatedChoices()},onHover:function(a){var b=Event.findElement(a,"LI");this.index!=b.autocompleteIndex&&(this.index=b.autocompleteIndex,this.render());Event.stop(a)},
onClick:function(a){this.index=Event.findElement(a,"LI").autocompleteIndex;this.selectEntry();this.hide()},onBlur:function(a){setTimeout(this.hide.bind(this),250);this.active=this.hasFocus=!1},render:function(){if(0<this.entryCount){for(var a=0;a<this.entryCount;a++)this.index==a?Element.addClassName(this.getEntry(a),"selected"):Element.removeClassName(this.getEntry(a),"selected");this.hasFocus&&(this.show(),this.active=!0)}else this.active=!1,this.hide()},markPrevious:function(){0<this.index?this.index--:
this.index=this.entryCount-1;this.getEntry(this.index).scrollIntoView(!0)},markNext:function(){this.index<this.entryCount-1?this.index++:this.index=0;this.getEntry(this.index).scrollIntoView(!1)},getEntry:function(a){return this.update.firstChild.childNodes[a]},getCurrentEntry:function(){return this.getEntry(this.index)},selectEntry:function(){this.active=!1;this.updateElement(this.getCurrentEntry())},updateElement:function(a){if(this.options.updateElement)this.options.updateElement(a);else{var b=
"";if(this.options.select){var c=$(a).select("."+this.options.select)||[];0<c.length&&(b=Element.collectTextNodes(c[0],this.options.select))}else b=Element.collectTextNodesIgnoreClass(a,"informal");c=this.getTokenBounds();if(-1!=c[0]){var d=this.element.value.substr(0,c[0]),e=this.element.value.substr(c[0]).match(/^\s+/);e&&(d+=e[0]);this.element.value=d+b+this.element.value.substr(c[1])}else this.element.value=b;this.oldElementValue=this.element.value;this.element.focus();this.options.afterUpdateElement&&
this.options.afterUpdateElement(this.element,a)}},updateChoices:function(a){if(!this.changed&&this.hasFocus){this.update.innerHTML=a;Element.cleanWhitespace(this.update);Element.cleanWhitespace(this.update.down());if(this.update.firstChild&&this.update.down().childNodes)for(this.entryCount=this.update.down().childNodes.length,a=0;a<this.entryCount;a++){var b=this.getEntry(a);b.autocompleteIndex=a;this.addObservers(b)}else this.entryCount=0;this.stopIndicator();this.index=0;1==this.entryCount&&this.options.autoSelect?
(this.selectEntry(),this.hide()):this.render()}},addObservers:function(a){Event.observe(a,"mouseover",this.onHover.bindAsEventListener(this));Event.observe(a,"click",this.onClick.bindAsEventListener(this))},onObserverEvent:function(){this.changed=!1;this.tokenBounds=null;this.getToken().length>=this.options.minChars?this.getUpdatedChoices():(this.active=!1,this.hide());this.oldElementValue=this.element.value},getToken:function(){var a=this.getTokenBounds();return this.element.value.substring(a[0],
a[1]).strip()},getTokenBounds:function(){if(null!=this.tokenBounds)return this.tokenBounds;var a=this.element.value;if(a.strip().empty())return[-1,0];for(var b=arguments.callee.getFirstDifferencePos(a,this.oldElementValue),c=b==this.oldElementValue.length?1:0,d=-1,e=a.length,f,g=0,h=this.options.tokens.length;g<h;++g)f=a.lastIndexOf(this.options.tokens[g],b+c-1),f>d&&(d=f),f=a.indexOf(this.options.tokens[g],b+c),-1!=f&&f<e&&(e=f);return this.tokenBounds=[d+1,e]}});
Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos=function(a,b){for(var c=Math.min(a.length,b.length),d=0;d<c;++d)if(a[d]!=b[d])return d;return c};
Ajax.Autocompleter=Class.create(Autocompleter.Base,{initialize:function(a,b,c,d){this.baseInitialize(a,b,d);this.options.asynchronous=!0;this.options.onComplete=this.onComplete.bind(this);this.options.defaultParams=this.options.parameters||null;this.url=c},getUpdatedChoices:function(){this.startIndicator();var a=encodeURIComponent(this.options.paramName)+"="+encodeURIComponent(this.getToken());this.options.parameters=this.options.callback?this.options.callback(this.element,a):a;this.options.defaultParams&&
(this.options.parameters+="&"+this.options.defaultParams);new Ajax.Request(this.url,this.options)},onComplete:function(a){this.updateChoices(a.responseText)}});
Autocompleter.Local=Class.create(Autocompleter.Base,{initialize:function(a,b,c,d){this.baseInitialize(a,b,d);this.options.array=c},getUpdatedChoices:function(){this.updateChoices(this.options.selector(this))},setOptions:function(a){this.options=Object.extend({choices:10,partialSearch:!0,partialChars:2,ignoreCase:!0,fullSearch:!1,selector:function(a){for(var c=[],d=[],e=a.getToken(),f=0;f<a.options.array.length&&c.length<a.options.choices;f++)for(var g=a.options.array[f],h=a.options.ignoreCase?g.toLowerCase().indexOf(e.toLowerCase()):
g.indexOf(e);-1!=h;){if(0==h&&g.length!=e.length){c.push("<li><strong>"+g.substr(0,e.length)+"</strong>"+g.substr(e.length)+"</li>");break}else if(e.length>=a.options.partialChars&&a.options.partialSearch&&-1!=h&&(a.options.fullSearch||/\s/.test(g.substr(h-1,1)))){d.push("<li>"+g.substr(0,h)+"<strong>"+g.substr(h,e.length)+"</strong>"+g.substr(h+e.length)+"</li>");break}h=a.options.ignoreCase?g.toLowerCase().indexOf(e.toLowerCase(),h+1):g.indexOf(e,h+1)}d.length&&(c=c.concat(d.slice(0,a.options.choices-
c.length)));return"<ul>"+c.join("")+"</ul>"}},a||{})}});Field.scrollFreeActivate=function(a){setTimeout(function(){Field.activate(a)},1)};
Ajax.InPlaceEditor=Class.create({initialize:function(a,b,c){this.url=b;this.element=a=$(a);this.prepareOptions();this._controls={};arguments.callee.dealWithDeprecatedOptions(c);Object.extend(this.options,c||{});!this.options.formId&&this.element.id&&(this.options.formId=this.element.id+"-inplaceeditor",$(this.options.formId)&&(this.options.formId=""));this.options.externalControl&&(this.options.externalControl=$(this.options.externalControl));this.options.externalControl||(this.options.externalControlOnly=
!1);this._originalBackground=this.element.getStyle("background-color")||"transparent";this.element.title=this.options.clickToEditText;this._boundCancelHandler=this.handleFormCancellation.bind(this);this._boundComplete=(this.options.onComplete||Prototype.emptyFunction).bind(this);this._boundFailureHandler=this.handleAJAXFailure.bind(this);this._boundSubmitHandler=this.handleFormSubmission.bind(this);this._boundWrapperHandler=this.wrapUp.bind(this);this.registerListeners()},checkForEscapeOrReturn:function(a){!this._editing||
a.ctrlKey||a.altKey||a.shiftKey||(Event.KEY_ESC==a.keyCode?this.handleFormCancellation(a):Event.KEY_RETURN==a.keyCode&&this.handleFormSubmission(a))},createControl:function(a,b,c){var d=this.options[a+"Control"];b=this.options[a+"Text"];"button"==d?(c=document.createElement("input"),c.type="submit",c.value=b,c.className="editor_"+a+"_button","cancel"==a&&(c.onclick=this._boundCancelHandler),this._form.appendChild(c),this._controls[a]=c):"link"==d&&(d=document.createElement("a"),d.href="#",d.appendChild(document.createTextNode(b)),
d.onclick="cancel"==a?this._boundCancelHandler:this._boundSubmitHandler,d.className="editor_"+a+"_link",c&&(d.className+=" "+c),this._form.appendChild(d),this._controls[a]=d)},createEditField:function(){var a=this.options.loadTextURL?this.options.loadingText:this.getText(),b;if(1>=this.options.rows&&!/\r|\n/.test(this.getText())){b=document.createElement("input");b.type="text";var c=this.options.size||this.options.cols||0;0<c&&(b.size=c)}else b=document.createElement("textarea"),b.rows=1>=this.options.rows?
this.options.autoRows:this.options.rows,b.cols=this.options.cols||40;b.name=this.options.paramName;b.value=a;b.className="editor_field";this.options.submitOnBlur&&(b.onblur=this._boundSubmitHandler);this._controls.editor=b;this.options.loadTextURL&&this.loadExternalText();this._form.appendChild(this._controls.editor)},createForm:function(){function a(a,d){var e=b.options["text"+a+"Controls"];e&&!1!==d&&b._form.appendChild(document.createTextNode(e))}var b=this;this._form=$(document.createElement("form"));
this._form.id=this.options.formId;this._form.addClassName(this.options.formClassName);this._form.onsubmit=this._boundSubmitHandler;this.createEditField();"textarea"==this._controls.editor.tagName.toLowerCase()&&this._form.appendChild(document.createElement("br"));if(this.options.onFormCustomization)this.options.onFormCustomization(this,this._form);a("Before",this.options.okControl||this.options.cancelControl);this.createControl("ok",this._boundSubmitHandler);a("Between",this.options.okControl&&this.options.cancelControl);
this.createControl("cancel",this._boundCancelHandler,"editor_cancel");a("After",this.options.okControl||this.options.cancelControl)},destroy:function(){this._oldInnerHTML&&(this.element.innerHTML=this._oldInnerHTML);this.leaveEditMode();this.unregisterListeners()},enterEditMode:function(a){this._saving||this._editing||(this._editing=!0,this.triggerCallback("onEnterEditMode"),this.options.externalControl&&this.options.externalControl.hide(),this.element.hide(),this.createForm(),this.element.parentNode.insertBefore(this._form,
this.element),this.options.loadTextURL||this.postProcessEditField(),a&&Event.stop(a))},enterHover:function(a){this.options.hoverClassName&&this.element.addClassName(this.options.hoverClassName);this._saving||this.triggerCallback("onEnterHover")},getText:function(){return this.element.innerHTML.unescapeHTML()},handleAJAXFailure:function(a){this.triggerCallback("onFailure",a);this._oldInnerHTML&&(this.element.innerHTML=this._oldInnerHTML,this._oldInnerHTML=null)},handleFormCancellation:function(a){this.wrapUp();
a&&Event.stop(a)},handleFormSubmission:function(a){var b=this._form,c=$F(this._controls.editor);this.prepareSubmission();b=this.options.callback(b,c)||"";Object.isString(b)&&(b=b.toQueryParams());b.editorId=this.element.id;this.options.htmlResponse?(c=Object.extend({evalScripts:!0},this.options.ajaxOptions),Object.extend(c,{parameters:b,onComplete:this._boundWrapperHandler,onFailure:this._boundFailureHandler}),new Ajax.Updater({success:this.element},this.url,c)):(c=Object.extend({method:"get"},this.options.ajaxOptions),
Object.extend(c,{parameters:b,onComplete:this._boundWrapperHandler,onFailure:this._boundFailureHandler}),new Ajax.Request(this.url,c));a&&Event.stop(a)},leaveEditMode:function(){this.element.removeClassName(this.options.savingClassName);this.removeForm();this.leaveHover();this.element.style.backgroundColor=this._originalBackground;this.element.show();this.options.externalControl&&this.options.externalControl.show();this._editing=this._saving=!1;this._oldInnerHTML=null;this.triggerCallback("onLeaveEditMode")},
leaveHover:function(a){this.options.hoverClassName&&this.element.removeClassName(this.options.hoverClassName);this._saving||this.triggerCallback("onLeaveHover")},loadExternalText:function(){this._form.addClassName(this.options.loadingClassName);this._controls.editor.disabled=!0;var a=Object.extend({method:"get"},this.options.ajaxOptions);Object.extend(a,{parameters:"editorId="+encodeURIComponent(this.element.id),onComplete:Prototype.emptyFunction,onSuccess:function(a){this._form.removeClassName(this.options.loadingClassName);
a=a.responseText;this.options.stripLoadedTextTags&&(a=a.stripTags());this._controls.editor.value=a;this._controls.editor.disabled=!1;this.postProcessEditField()}.bind(this),onFailure:this._boundFailureHandler});new Ajax.Request(this.options.loadTextURL,a)},postProcessEditField:function(){var a=this.options.fieldPostCreation;if(a)$(this._controls.editor)["focus"==a?"focus":"activate"]()},prepareOptions:function(){this.options=Object.clone(Ajax.InPlaceEditor.DefaultOptions);Object.extend(this.options,
Ajax.InPlaceEditor.DefaultCallbacks);[this._extraDefaultOptions].flatten().compact().each(function(a){Object.extend(this.options,a)}.bind(this))},prepareSubmission:function(){this._saving=!0;this.removeForm();this.leaveHover();this.showSaving()},registerListeners:function(){this._listeners={};var a;$H(Ajax.InPlaceEditor.Listeners).each(function(b){a=this[b.value].bind(this);this._listeners[b.key]=a;this.options.externalControlOnly||this.element.observe(b.key,a);this.options.externalControl&&this.options.externalControl.observe(b.key,
a)}.bind(this))},removeForm:function(){this._form&&(this._form.remove(),this._form=null,this._controls={})},showSaving:function(){this._oldInnerHTML=this.element.innerHTML;this.element.innerHTML=this.options.savingText;this.element.addClassName(this.options.savingClassName);this.element.style.backgroundColor=this._originalBackground;this.element.show()},triggerCallback:function(a,b){if("function"==typeof this.options[a])this.options[a](this,b)},unregisterListeners:function(){$H(this._listeners).each(function(a){this.options.externalControlOnly||
this.element.stopObserving(a.key,a.value);this.options.externalControl&&this.options.externalControl.stopObserving(a.key,a.value)}.bind(this))},wrapUp:function(a){this.leaveEditMode();this._boundComplete(a,this.element)}});Object.extend(Ajax.InPlaceEditor.prototype,{dispose:Ajax.InPlaceEditor.prototype.destroy});
Ajax.InPlaceCollectionEditor=Class.create(Ajax.InPlaceEditor,{initialize:function($super,b,c,d){this._extraDefaultOptions=Ajax.InPlaceCollectionEditor.DefaultOptions;$super(b,c,d)},createEditField:function(){var a=document.createElement("select");a.name=this.options.paramName;a.size=1;this._controls.editor=a;this._collection=this.options.collection||[];this.options.loadCollectionURL?this.loadCollection():this.checkForExternalText();this._form.appendChild(this._controls.editor)},loadCollection:function(){this._form.addClassName(this.options.loadingClassName);
this.showLoadingText(this.options.loadingCollectionText);var a=Object.extend({method:"get"},this.options.ajaxOptions);Object.extend(a,{parameters:"editorId="+encodeURIComponent(this.element.id),onComplete:Prototype.emptyFunction,onSuccess:function(a){a=a.responseText.strip();if(!/^\[.*\]$/.test(a))throw"Server returned an invalid collection representation.";this._collection=eval(a);this.checkForExternalText()}.bind(this),onFailure:this.onFailure});new Ajax.Request(this.options.loadCollectionURL,a)},
showLoadingText:function(a){this._controls.editor.disabled=!0;var b=this._controls.editor.firstChild;b||(b=document.createElement("option"),b.value="",this._controls.editor.appendChild(b),b.selected=!0);b.update((a||"").stripScripts().stripTags())},checkForExternalText:function(){this._text=this.getText();this.options.loadTextURL?this.loadExternalText():this.buildOptionList()},loadExternalText:function(){this.showLoadingText(this.options.loadingText);var a=Object.extend({method:"get"},this.options.ajaxOptions);
Object.extend(a,{parameters:"editorId="+encodeURIComponent(this.element.id),onComplete:Prototype.emptyFunction,onSuccess:function(a){this._text=a.responseText.strip();this.buildOptionList()}.bind(this),onFailure:this.onFailure});new Ajax.Request(this.options.loadTextURL,a)},buildOptionList:function(){this._form.removeClassName(this.options.loadingClassName);this._collection=this._collection.map(function(a){return 2===a.length?a:[a,a].flatten()});var a="value"in this.options?this.options.value:this._text,
b=this._collection.any(function(b){return b[0]==a}.bind(this));this._controls.editor.update("");var c;this._collection.each(function(d,e){c=document.createElement("option");c.value=d[0];c.selected=b?d[0]==a:0==e;c.appendChild(document.createTextNode(d[1]));this._controls.editor.appendChild(c)}.bind(this));this._controls.editor.disabled=!1;Field.scrollFreeActivate(this._controls.editor)}});
Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions=function(a){function b(b,d){b in a||void 0===d||(a[b]=d)}a&&(b("cancelControl",a.cancelLink?"link":a.cancelButton?"button":a.cancelLink==a.cancelButton==0?!1:void 0),b("okControl",a.okLink?"link":a.okButton?"button":a.okLink==a.okButton==0?!1:void 0),b("highlightColor",a.highlightcolor),b("highlightEndColor",a.highlightendcolor))};
Object.extend(Ajax.InPlaceEditor,{DefaultOptions:{ajaxOptions:{},autoRows:3,cancelControl:"link",cancelText:"cancel",clickToEditText:"Click to edit",externalControl:null,externalControlOnly:!1,fieldPostCreation:"activate",formClassName:"inplaceeditor-form",formId:null,highlightColor:"#ffff99",highlightEndColor:"#ffffff",hoverClassName:"",htmlResponse:!0,loadingClassName:"inplaceeditor-loading",loadingText:"Loading...",okControl:"button",okText:"ok",paramName:"value",rows:1,savingClassName:"inplaceeditor-saving",
savingText:"Saving...",size:0,stripLoadedTextTags:!1,submitOnBlur:!1,textAfterControls:"",textBeforeControls:"",textBetweenControls:""},DefaultCallbacks:{callback:function(a){return Form.serialize(a)},onComplete:function(a,b){new Effect.Highlight(b,{startcolor:this.options.highlightColor,keepBackgroundImage:!0})},onEnterEditMode:null,onEnterHover:function(a){a.element.style.backgroundColor=a.options.highlightColor;a._effect&&a._effect.cancel()},onFailure:function(a,b){alert("Error communication with the server: "+
a.responseText.stripTags())},onFormCustomization:null,onLeaveEditMode:null,onLeaveHover:function(a){a._effect=new Effect.Highlight(a.element,{startcolor:a.options.highlightColor,endcolor:a.options.highlightEndColor,restorecolor:a._originalBackground,keepBackgroundImage:!0})}},Listeners:{click:"enterEditMode",keydown:"checkForEscapeOrReturn",mouseover:"enterHover",mouseout:"leaveHover"}});Ajax.InPlaceCollectionEditor.DefaultOptions={loadingCollectionText:"Loading options..."};
Form.Element.DelayedObserver=Class.create({initialize:function(a,b,c){this.delay=b||.5;this.element=$(a);this.callback=c;this.timer=null;this.lastValue=$F(this.element);Event.observe(this.element,"keyup",this.delayedListener.bindAsEventListener(this))},delayedListener:function(a){this.lastValue!=$F(this.element)&&(this.timer&&clearTimeout(this.timer),this.timer=setTimeout(this.onTimerEvent.bind(this),1E3*this.delay),this.lastValue=$F(this.element))},onTimerEvent:function(){this.timer=null;this.callback(this.element,
$F(this.element))}});if(Object.isUndefined(Effect))throw"dragdrop.js requires including script.aculo.us' effects.js library";
var Droppables={drops:[],remove:function(a){this.drops=this.drops.reject(function(b){return b.element==$(a)})},add:function(a,b){a=$(a);var c=Object.extend({greedy:!0,hoverclass:null,tree:!1},b||{});if(c.containment){c._containers=[];var d=c.containment;Object.isArray(d)?d.each(function(a){c._containers.push($(a))}):c._containers.push($(d))}c.accept&&(c.accept=[c.accept].flatten());Element.makePositioned(a);c.element=a;this.drops.push(c)},findDeepestChild:function(a){deepest=a[0];for(i=1;i<a.length;++i)Element.isParent(a[i].element,
deepest.element)&&(deepest=a[i]);return deepest},isContained:function(a,b){var c;c=b.tree?a.treeNode:a.parentNode;return b._containers.detect(function(a){return c==a})},isAffected:function(a,b,c){return c.element!=b&&(!c._containers||this.isContained(b,c))&&(!c.accept||Element.classNames(b).detect(function(a){return c.accept.include(a)}))&&Position.within(c.element,a[0],a[1])},deactivate:function(a){a.hoverclass&&Element.removeClassName(a.element,a.hoverclass);this.last_active=null},activate:function(a){a.hoverclass&&
Element.addClassName(a.element,a.hoverclass);this.last_active=a},show:function(a,b){if(this.drops.length){var c,d=[];this.drops.each(function(c){Droppables.isAffected(a,b,c)&&d.push(c)});0<d.length&&(c=Droppables.findDeepestChild(d));this.last_active&&this.last_active!=c&&this.deactivate(this.last_active);if(c){Position.within(c.element,a[0],a[1]);if(c.onHover)c.onHover(b,c.element,Position.overlap(c.overlap,c.element));c!=this.last_active&&Droppables.activate(c)}}},fire:function(a,b){if(this.last_active&&
(Position.prepare(),this.isAffected([Event.pointerX(a),Event.pointerY(a)],b,this.last_active)&&this.last_active.onDrop))return this.last_active.onDrop(b,this.last_active.element,a),!0},reset:function(){this.last_active&&this.deactivate(this.last_active)}},Draggables={drags:[],observers:[],register:function(a){0==this.drags.length&&(this.eventMouseUp=this.endDrag.bindAsEventListener(this),this.eventMouseMove=this.updateDrag.bindAsEventListener(this),this.eventKeypress=this.keyPress.bindAsEventListener(this),
Event.observe(document,"mouseup",this.eventMouseUp),Event.observe(document,"mousemove",this.eventMouseMove),Event.observe(document,"keypress",this.eventKeypress));this.drags.push(a)},unregister:function(a){this.drags=this.drags.reject(function(b){return b==a});0==this.drags.length&&(Event.stopObserving(document,"mouseup",this.eventMouseUp),Event.stopObserving(document,"mousemove",this.eventMouseMove),Event.stopObserving(document,"keypress",this.eventKeypress))},activate:function(a){a.options.delay?
this._timeout=setTimeout(function(){Draggables._timeout=null;window.focus();Draggables.activeDraggable=a}.bind(this),a.options.delay):(window.focus(),this.activeDraggable=a)},deactivate:function(){this.activeDraggable=null},updateDrag:function(a){if(this.activeDraggable){var b=[Event.pointerX(a),Event.pointerY(a)];this._lastPointer&&this._lastPointer.inspect()==b.inspect()||(this._lastPointer=b,this.activeDraggable.updateDrag(a,b))}},endDrag:function(a){this._timeout&&(clearTimeout(this._timeout),
this._timeout=null);this.activeDraggable&&(this._lastPointer=null,this.activeDraggable.endDrag(a),this.activeDraggable=null)},keyPress:function(a){this.activeDraggable&&this.activeDraggable.keyPress(a)},addObserver:function(a){this.observers.push(a);this._cacheObserverCallbacks()},removeObserver:function(a){this.observers=this.observers.reject(function(b){return b.element==a});this._cacheObserverCallbacks()},notify:function(a,b,c){0<this[a+"Count"]&&this.observers.each(function(d){if(d[a])d[a](a,
b,c)});if(b.options[a])b.options[a](b,c)},_cacheObserverCallbacks:function(){["onStart","onEnd","onDrag"].each(function(a){Draggables[a+"Count"]=Draggables.observers.select(function(b){return b[a]}).length})}},Draggable=Class.create({initialize:function(a,b){var c={handle:!1,reverteffect:function(a,b,c){new Effect.Move(a,{x:-c,y:-b,duration:.02*Math.sqrt(Math.abs(b^2)+Math.abs(c^2)),queue:{scope:"_draggable",position:"end"}})},endeffect:function(a){var b=Object.isNumber(a._opacity)?a._opacity:1;new Effect.Opacity(a,
{duration:.2,from:.7,to:b,queue:{scope:"_draggable",position:"end"},afterFinish:function(){Draggable._dragging[a]=!1}})},zindex:1E3,revert:!1,quiet:!1,scroll:!1,scrollSensitivity:20,scrollSpeed:15,snap:!1,delay:0};b&&!Object.isUndefined(b.endeffect)||Object.extend(c,{starteffect:function(a){a._opacity=Element.getOpacity(a);Draggable._dragging[a]=!0;new Effect.Opacity(a,{duration:.2,from:a._opacity,to:.7})}});c=Object.extend(c,b||{});this.element=$(a);c.handle&&Object.isString(c.handle)&&(this.handle=
this.element.down("."+c.handle,0));this.handle||(this.handle=$(c.handle));this.handle||(this.handle=this.element);!c.scroll||c.scroll.scrollTo||c.scroll.outerHTML||(c.scroll=$(c.scroll),this._isScrollChild=Element.childOf(this.element,c.scroll));Element.makePositioned(this.element);this.options=c;this.dragging=!1;this.eventMouseDown=this.initDrag.bindAsEventListener(this);Event.observe(this.handle,"mousedown",this.eventMouseDown);Draggables.register(this)},destroy:function(){Event.stopObserving(this.handle,
"mousedown",this.eventMouseDown);Draggables.unregister(this)},currentDelta:function(){return[parseInt(Element.getStyle(this.element,"left")||"0"),parseInt(Element.getStyle(this.element,"top")||"0")]},initDrag:function(a){if((Object.isUndefined(Draggable._dragging[this.element])||!Draggable._dragging[this.element])&&Event.isLeftClick(a)&&(!(tag_name=Event.element(a).tagName.toUpperCase())||"INPUT"!=tag_name&&"SELECT"!=tag_name&&"OPTION"!=tag_name&&"BUTTON"!=tag_name&&"TEXTAREA"!=tag_name)){var b=[Event.pointerX(a),
Event.pointerY(a)],c=this.element.cumulativeOffset();this.offset=[0,1].map(function(a){return b[a]-c[a]});Draggables.activate(this);Event.stop(a)}},startDrag:function(a){this.dragging=!0;this.delta||(this.delta=this.currentDelta());this.options.zindex&&(this.originalZ=parseInt(Element.getStyle(this.element,"z-index")||0),this.element.style.zIndex=this.options.zindex);this.options.ghosting&&(this._clone=this.element.cloneNode(!0),(this._originallyAbsolute="absolute"==this.element.getStyle("position"))||
Position.absolutize(this.element),this.element.parentNode.insertBefore(this._clone,this.element));if(this.options.scroll)if(this.options.scroll==window){var b=this._getWindowScroll(this.options.scroll);this.originalScrollLeft=b.left;this.originalScrollTop=b.top}else this.originalScrollLeft=this.options.scroll.scrollLeft,this.originalScrollTop=this.options.scroll.scrollTop;Draggables.notify("onStart",this,a);this.options.starteffect&&this.options.starteffect(this.element)},updateDrag:function(a,b){this.dragging||
this.startDrag(a);this.options.quiet||(Position.prepare(),Droppables.show(b,this.element));Draggables.notify("onDrag",this,a);this.draw(b);this.options.change&&this.options.change(this);if(this.options.scroll){this.stopScrolling();var c;if(this.options.scroll==window)with(this._getWindowScroll(this.options.scroll))c=[left,top,left+width,top+height];else c=Position.page(this.options.scroll).toArray(),c[0]+=this.options.scroll.scrollLeft+Position.deltaX,c[1]+=this.options.scroll.scrollTop+Position.deltaY,
c.push(c[0]+this.options.scroll.offsetWidth),c.push(c[1]+this.options.scroll.offsetHeight);var d=[0,0];b[0]<c[0]+this.options.scrollSensitivity&&(d[0]=b[0]-(c[0]+this.options.scrollSensitivity));b[1]<c[1]+this.options.scrollSensitivity&&(d[1]=b[1]-(c[1]+this.options.scrollSensitivity));b[0]>c[2]-this.options.scrollSensitivity&&(d[0]=b[0]-(c[2]-this.options.scrollSensitivity));b[1]>c[3]-this.options.scrollSensitivity&&(d[1]=b[1]-(c[3]-this.options.scrollSensitivity));this.startScrolling(d)}Prototype.Browser.WebKit&&
window.scrollBy(0,0);Event.stop(a)},finishDrag:function(a,b){this.dragging=!1;if(this.options.quiet){Position.prepare();var c=[Event.pointerX(a),Event.pointerY(a)];Droppables.show(c,this.element)}this.options.ghosting&&(this._originallyAbsolute||Position.relativize(this.element),delete this._originallyAbsolute,Element.remove(this._clone),this._clone=null);c=!1;b&&((c=Droppables.fire(a,this.element))||(c=!1));if(c&&this.options.onDropped)this.options.onDropped(this.element);Draggables.notify("onEnd",
this,a);var d=this.options.revert;d&&Object.isFunction(d)&&(d=d(this.element));var e=this.currentDelta();d&&this.options.reverteffect?0!=c&&"failure"==d||this.options.reverteffect(this.element,e[1]-this.delta[1],e[0]-this.delta[0]):this.delta=e;this.options.zindex&&(this.element.style.zIndex=this.originalZ);this.options.endeffect&&this.options.endeffect(this.element);Draggables.deactivate(this);Droppables.reset()},keyPress:function(a){a.keyCode==Event.KEY_ESC&&(this.finishDrag(a,!1),Event.stop(a))},
endDrag:function(a){this.dragging&&(this.stopScrolling(),this.finishDrag(a,!0),Event.stop(a))},draw:function(a){var b=this.element.cumulativeOffset();if(this.options.ghosting){var c=Position.realOffset(this.element);b[0]+=c[0]-Position.deltaX;b[1]+=c[1]-Position.deltaY}c=this.currentDelta();b[0]-=c[0];b[1]-=c[1];this.options.scroll&&this.options.scroll!=window&&this._isScrollChild&&(b[0]-=this.options.scroll.scrollLeft-this.originalScrollLeft,b[1]-=this.options.scroll.scrollTop-this.originalScrollTop);
c=[0,1].map(function(c){return a[c]-b[c]-this.offset[c]}.bind(this));this.options.snap&&(c=Object.isFunction(this.options.snap)?this.options.snap(c[0],c[1],this):Object.isArray(this.options.snap)?c.map(function(a,b){return(a/this.options.snap[b]).round()*this.options.snap[b]}.bind(this)):c.map(function(a){return(a/this.options.snap).round()*this.options.snap}.bind(this)));var d=this.element.style;this.options.constraint&&"horizontal"!=this.options.constraint||(d.left=c[0]+"px");this.options.constraint&&
"vertical"!=this.options.constraint||(d.top=c[1]+"px");"hidden"==d.visibility&&(d.visibility="")},stopScrolling:function(){this.scrollInterval&&(clearInterval(this.scrollInterval),this.scrollInterval=null,Draggables._lastScrollPointer=null)},startScrolling:function(a){if(a[0]||a[1])this.scrollSpeed=[a[0]*this.options.scrollSpeed,a[1]*this.options.scrollSpeed],this.lastScrolled=new Date,this.scrollInterval=setInterval(this.scroll.bind(this),10)},scroll:function(){var a=new Date,b=a-this.lastScrolled;
this.lastScrolled=a;if(this.options.scroll==window)with(this._getWindowScroll(this.options.scroll)){if(this.scrollSpeed[0]||this.scrollSpeed[1])a=b/1E3,this.options.scroll.scrollTo(left+a*this.scrollSpeed[0],top+a*this.scrollSpeed[1])}else this.options.scroll.scrollLeft+=this.scrollSpeed[0]*b/1E3,this.options.scroll.scrollTop+=this.scrollSpeed[1]*b/1E3;Position.prepare();Droppables.show(Draggables._lastPointer,this.element);Draggables.notify("onDrag",this);this._isScrollChild&&(Draggables._lastScrollPointer=
Draggables._lastScrollPointer||$A(Draggables._lastPointer),Draggables._lastScrollPointer[0]+=this.scrollSpeed[0]*b/1E3,Draggables._lastScrollPointer[1]+=this.scrollSpeed[1]*b/1E3,0>Draggables._lastScrollPointer[0]&&(Draggables._lastScrollPointer[0]=0),0>Draggables._lastScrollPointer[1]&&(Draggables._lastScrollPointer[1]=0),this.draw(Draggables._lastScrollPointer));this.options.change&&this.options.change(this)},_getWindowScroll:function(a){var b,c,d;with(a.document)a.document.documentElement&&documentElement.scrollTop?
(b=documentElement.scrollTop,c=documentElement.scrollLeft):a.document.body&&(b=body.scrollTop,c=body.scrollLeft),a.innerWidth?(d=a.innerWidth,a=a.innerHeight):a.document.documentElement&&documentElement.clientWidth?(d=documentElement.clientWidth,a=documentElement.clientHeight):(d=body.offsetWidth,a=body.offsetHeight);return{top:b,left:c,width:d,height:a}}});Draggable._dragging={};
var SortableObserver=Class.create({initialize:function(a,b){this.element=$(a);this.observer=b;this.lastValue=Sortable.serialize(this.element)},onStart:function(){this.lastValue=Sortable.serialize(this.element)},onEnd:function(){Sortable.unmark();this.lastValue!=Sortable.serialize(this.element)&&this.observer(this.element)}}),Sortable={SERIALIZE_RULE:/^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,sortables:{},_findRootElement:function(a){for(;"BODY"!=a.tagName.toUpperCase();){if(a.id&&Sortable.sortables[a.id])return a;
a=a.parentNode}},options:function(a){if(a=Sortable._findRootElement($(a)))return Sortable.sortables[a.id]},destroy:function(a){a=$(a);if(a=Sortable.sortables[a.id])Draggables.removeObserver(a.element),a.droppables.each(function(a){Droppables.remove(a)}),a.draggables.invoke("destroy"),delete Sortable.sortables[a.element.id]},create:function(a,b){a=$(a);var c=Object.extend({element:a,tag:"li",dropOnEmpty:!1,tree:!1,treeTag:"ul",overlap:"vertical",constraint:"vertical",containment:a,handle:!1,only:!1,
delay:0,hoverclass:null,ghosting:!1,quiet:!1,scroll:!1,scrollSensitivity:20,scrollSpeed:15,format:this.SERIALIZE_RULE,elements:!1,handles:!1,onChange:Prototype.emptyFunction,onUpdate:Prototype.emptyFunction},b||{});this.destroy(a);var d={revert:!0,quiet:c.quiet,scroll:c.scroll,scrollSpeed:c.scrollSpeed,scrollSensitivity:c.scrollSensitivity,delay:c.delay,ghosting:c.ghosting,constraint:c.constraint,handle:c.handle};c.starteffect&&(d.starteffect=c.starteffect);c.reverteffect?d.reverteffect=c.reverteffect:
c.ghosting&&(d.reverteffect=function(a){a.style.top=0;a.style.left=0});c.endeffect&&(d.endeffect=c.endeffect);c.zindex&&(d.zindex=c.zindex);var e={overlap:c.overlap,containment:c.containment,tree:c.tree,hoverclass:c.hoverclass,onHover:Sortable.onHover},f={onHover:Sortable.onEmptyHover,overlap:c.overlap,containment:c.containment,hoverclass:c.hoverclass};Element.cleanWhitespace(a);c.draggables=[];c.droppables=[];if(c.dropOnEmpty||c.tree)Droppables.add(a,f),c.droppables.push(a);(c.elements||this.findElements(a,
c)||[]).each(function(b,f){var l=c.handles?$(c.handles[f]):c.handle?$(b).select("."+c.handle)[0]:b;c.draggables.push(new Draggable(b,Object.extend(d,{handle:l})));Droppables.add(b,e);c.tree&&(b.treeNode=a);c.droppables.push(b)});c.tree&&(Sortable.findTreeElements(a,c)||[]).each(function(b){Droppables.add(b,f);b.treeNode=a;c.droppables.push(b)});this.sortables[a.identify()]=c;Draggables.addObserver(new SortableObserver(a,c.onUpdate))},findElements:function(a,b){return Element.findChildren(a,b.only,
b.tree?!0:!1,b.tag)},findTreeElements:function(a,b){return Element.findChildren(a,b.only,b.tree?!0:!1,b.treeTag)},onHover:function(a,b,c){if(!(Element.isParent(b,a)||.33<c&&.66>c&&Sortable.options(b).tree))if(.5<c){if(Sortable.mark(b,"before"),b.previousSibling!=a){c=a.parentNode;a.style.visibility="hidden";b.parentNode.insertBefore(a,b);if(b.parentNode!=c)Sortable.options(c).onChange(a);Sortable.options(b.parentNode).onChange(a)}}else{Sortable.mark(b,"after");var d=b.nextSibling||null;if(d!=a){c=
a.parentNode;a.style.visibility="hidden";b.parentNode.insertBefore(a,d);if(b.parentNode!=c)Sortable.options(c).onChange(a);Sortable.options(b.parentNode).onChange(a)}}},onEmptyHover:function(a,b,c){var d=a.parentNode,e=Sortable.options(b);if(!Element.isParent(b,a)){var f=Sortable.findElements(b,{tag:e.tag,only:e.only}),g=null;if(f){var h=Element.offsetSize(b,e.overlap)*(1-c);for(c=0;c<f.length;c+=1)if(0<=h-Element.offsetSize(f[c],e.overlap))h-=Element.offsetSize(f[c],e.overlap);else{g=0<=h-Element.offsetSize(f[c],
e.overlap)/2?c+1<f.length?f[c+1]:null:f[c];break}}b.insertBefore(a,g);Sortable.options(d).onChange(a);e.onChange(a)}},unmark:function(){Sortable._marker&&Sortable._marker.hide()},mark:function(a,b){var c=Sortable.options(a.parentNode);if(!c||c.ghosting){Sortable._marker||(Sortable._marker=($("dropmarker")||Element.extend(document.createElement("DIV"))).hide().addClassName("dropmarker").setStyle({position:"absolute"}),document.getElementsByTagName("body").item(0).appendChild(Sortable._marker));var d=
a.cumulativeOffset();Sortable._marker.setStyle({left:d[0]+"px",top:d[1]+"px"});"after"==b&&("horizontal"==c.overlap?Sortable._marker.setStyle({left:d[0]+a.clientWidth+"px"}):Sortable._marker.setStyle({top:d[1]+a.clientHeight+"px"}));Sortable._marker.show()}},_tree:function(a,b,c){for(var d=Sortable.findElements(a,b)||[],e=0;e<d.length;++e){var f=d[e].id.match(b.format);f&&(f={id:encodeURIComponent(f?f[1]:null),element:a,parent:c,children:[],position:c.children.length,container:$(d[e]).down(b.treeTag)},
f.container&&this._tree(f.container,b,f),c.children.push(f))}return c},tree:function(a,b){a=$(a);var c=this.options(a),c=Object.extend({tag:c.tag,treeTag:c.treeTag,only:c.only,name:a.id,format:c.format},b||{});return Sortable._tree(a,c,{id:null,parent:null,children:[],container:a,position:0})},_constructIndex:function(a){var b="";do a.id&&(b="["+a.position+"]"+b);while(null!=(a=a.parent));return b},sequence:function(a,b){a=$(a);var c=Object.extend(this.options(a),b||{});return $(this.findElements(a,
c)||[]).map(function(a){return a.id.match(c.format)?a.id.match(c.format)[1]:""})},setSequence:function(a,b,c){a=$(a);var d=Object.extend(this.options(a),c||{}),e={};this.findElements(a,d).each(function(a){a.id.match(d.format)&&(e[a.id.match(d.format)[1]]=[a,a.parentNode]);a.parentNode.removeChild(a)});b.each(function(a){var b=e[a];b&&(b[1].appendChild(b[0]),delete e[a])})},serialize:function(a,b){a=$(a);var c=Object.extend(Sortable.options(a),b||{}),d=encodeURIComponent(b&&b.name?b.name:a.id);return c.tree?
Sortable.tree(a,b).children.map(function(a){return[d+Sortable._constructIndex(a)+"[id]="+encodeURIComponent(a.id)].concat(a.children.map(arguments.callee))}).flatten().join("&"):Sortable.sequence(a,b).map(function(a){return d+"[]="+encodeURIComponent(a)}).join("&")}};Element.isParent=function(a,b){return a.parentNode&&a!=b?a.parentNode==b?!0:Element.isParent(a.parentNode,b):!1};
Element.findChildren=function(a,b,c,d){if(!a.hasChildNodes())return null;d=d.toUpperCase();b&&(b=[b].flatten());var e=[];$A(a.childNodes).each(function(a){!a.tagName||a.tagName.toUpperCase()!=d||b&&!Element.classNames(a).detect(function(a){return b.include(a)})||e.push(a);c&&(a=Element.findChildren(a,b,c,d))&&e.push(a)});return 0<e.length?e.flatten():[]};Element.offsetSize=function(a,b){return a["offset"+("vertical"==b||"height"==b?"Height":"Width")]};if(!Control)var Control={};
Control.Slider=Class.create({initialize:function(a,b,c){var d=this;Object.isArray(a)?this.handles=a.collect(function(a){return $(a)}):this.handles=[$(a)];this.track=$(b);this.options=c||{};this.axis=this.options.axis||"horizontal";this.increment=this.options.increment||1;this.step=parseInt(this.options.step||"1");this.range=this.options.range||$R(0,1);this.value=0;this.values=this.handles.map(function(){return 0});this.spans=this.options.spans?this.options.spans.map(function(a){return $(a)}):!1;this.options.startSpan=
$(this.options.startSpan||null);this.options.endSpan=$(this.options.endSpan||null);this.restricted=this.options.restricted||!1;this.maximum=this.options.maximum||this.range.end;this.minimum=this.options.minimum||this.range.start;this.alignX=parseInt(this.options.alignX||"0");this.alignY=parseInt(this.options.alignY||"0");this.trackLength=this.maximumOffset()-this.minimumOffset();this.handleLength=this.isVertical()?0!=this.handles[0].offsetHeight?this.handles[0].offsetHeight:this.handles[0].style.height.replace(/px$/,
""):0!=this.handles[0].offsetWidth?this.handles[0].offsetWidth:this.handles[0].style.width.replace(/px$/,"");this.disabled=this.dragging=this.active=!1;this.options.disabled&&this.setDisabled();if(this.allowedValues=this.options.values?this.options.values.sortBy(Prototype.K):!1)this.minimum=this.allowedValues.min(),this.maximum=this.allowedValues.max();this.eventMouseDown=this.startDrag.bindAsEventListener(this);this.eventMouseUp=this.endDrag.bindAsEventListener(this);this.eventMouseMove=this.update.bindAsEventListener(this);
this.handles.each(function(a,b){b=d.handles.length-1-b;d.setValue(parseFloat((Object.isArray(d.options.sliderValue)?d.options.sliderValue[b]:d.options.sliderValue)||d.range.start),b);a.makePositioned().observe("mousedown",d.eventMouseDown)});this.track.observe("mousedown",this.eventMouseDown);document.observe("mouseup",this.eventMouseUp);document.observe("mousemove",this.eventMouseMove);this.initialized=!0},dispose:function(){var a=this;Event.stopObserving(this.track,"mousedown",this.eventMouseDown);
Event.stopObserving(document,"mouseup",this.eventMouseUp);Event.stopObserving(document,"mousemove",this.eventMouseMove);this.handles.each(function(b){Event.stopObserving(b,"mousedown",a.eventMouseDown)})},setDisabled:function(){this.disabled=!0},setEnabled:function(){this.disabled=!1},getNearestValue:function(a){if(this.allowedValues){if(a>=this.allowedValues.max())return this.allowedValues.max();if(a<=this.allowedValues.min())return this.allowedValues.min();var b=Math.abs(this.allowedValues[0]-a),
c=this.allowedValues[0];this.allowedValues.each(function(d){var e=Math.abs(d-a);e<=b&&(c=d,b=e)});return c}return a>this.range.end?this.range.end:a<this.range.start?this.range.start:a},setValue:function(a,b){this.active||(this.activeHandleIdx=b||0,this.activeHandle=this.handles[this.activeHandleIdx],this.updateStyles());b=b||this.activeHandleIdx||0;this.initialized&&this.restricted&&(0<b&&a<this.values[b-1]&&(a=this.values[b-1]),b<this.handles.length-1&&a>this.values[b+1]&&(a=this.values[b+1]));a=
this.getNearestValue(a);this.values[b]=a;this.value=this.values[0];this.handles[b].style[this.isVertical()?"top":"left"]=this.translateToPx(a);this.drawSpans();this.dragging&&this.event||this.updateFinished()},setValueBy:function(a,b){this.setValue(this.values[b||this.activeHandleIdx||0]+a,b||this.activeHandleIdx||0)},translateToPx:function(a){return Math.round((this.trackLength-this.handleLength)/(this.range.end-this.range.start)*(a-this.range.start))+"px"},translateToValue:function(a){return a/
(this.trackLength-this.handleLength)*(this.range.end-this.range.start)+this.range.start},getRange:function(a){var b=this.values.sortBy(Prototype.K);a=a||0;return $R(b[a],b[a+1])},minimumOffset:function(){return this.isVertical()?this.alignY:this.alignX},maximumOffset:function(){return this.isVertical()?(0!=this.track.offsetHeight?this.track.offsetHeight:this.track.style.height.replace(/px$/,""))-this.alignY:(0!=this.track.offsetWidth?this.track.offsetWidth:this.track.style.width.replace(/px$/,""))-
this.alignX},isVertical:function(){return"vertical"==this.axis},drawSpans:function(){var a=this;this.spans&&$R(0,this.spans.length-1).each(function(b){a.setSpan(a.spans[b],a.getRange(b))});this.options.startSpan&&this.setSpan(this.options.startSpan,$R(0,1<this.values.length?this.getRange(0).min():this.value));this.options.endSpan&&this.setSpan(this.options.endSpan,$R(1<this.values.length?this.getRange(this.spans.length-1).max():this.value,this.maximum))},setSpan:function(a,b){this.isVertical()?(a.style.top=
this.translateToPx(b.start),a.style.height=this.translateToPx(b.end-b.start+this.range.start)):(a.style.left=this.translateToPx(b.start),a.style.width=this.translateToPx(b.end-b.start+this.range.start))},updateStyles:function(){this.handles.each(function(a){Element.removeClassName(a,"selected")});Element.addClassName(this.activeHandle,"selected")},startDrag:function(a){if(Event.isLeftClick(a)){if(!this.disabled){this.active=!0;var b=Event.element(a),c=[Event.pointerX(a),Event.pointerY(a)];if(b==this.track)b=
this.track.cumulativeOffset(),this.event=a,this.setValue(this.translateToValue((this.isVertical()?c[1]-b[1]:c[0]-b[0])-this.handleLength/2)),b=this.activeHandle.cumulativeOffset(),this.offsetX=c[0]-b[0],this.offsetY=c[1]-b[1];else{for(;-1==this.handles.indexOf(b)&&b.parentNode;)b=b.parentNode;-1!=this.handles.indexOf(b)&&(this.activeHandle=b,this.activeHandleIdx=this.handles.indexOf(this.activeHandle),this.updateStyles(),b=this.activeHandle.cumulativeOffset(),this.offsetX=c[0]-b[0],this.offsetY=c[1]-
b[1])}}Event.stop(a)}},update:function(a){this.active&&(this.dragging||(this.dragging=!0),this.draw(a),Prototype.Browser.WebKit&&window.scrollBy(0,0),Event.stop(a))},draw:function(a){var b=[Event.pointerX(a),Event.pointerY(a)],c=this.track.cumulativeOffset();b[0]-=this.offsetX+c[0];b[1]-=this.offsetY+c[1];this.event=a;this.setValue(this.translateToValue(this.isVertical()?b[1]:b[0]));if(this.initialized&&this.options.onSlide)this.options.onSlide(1<this.values.length?this.values:this.value,this)},endDrag:function(a){this.active&&
this.dragging&&(this.finishDrag(a,!0),Event.stop(a));this.dragging=this.active=!1},finishDrag:function(a,b){this.dragging=this.active=!1;this.updateFinished()},updateFinished:function(){if(this.initialized&&this.options.onChange)this.options.onChange(1<this.values.length?this.values:this.value,this);this.event=null}});
Sound={tracks:{},_enabled:!0,template:new Template('<embed style="height:0" id="sound_#{track}_#{id}" src="#{url}" loop="false" autostart="true" hidden="true"/>'),enable:function(){Sound._enabled=!0},disable:function(){Sound._enabled=!1},play:function(a,b){if(Sound._enabled){var c=Object.extend({track:"global",url:a,replace:!1},b||{});c.replace&&this.tracks[c.track]&&($R(0,this.tracks[c.track].id).each(function(a){a=$("sound_"+c.track+"_"+a);a.Stop&&a.Stop();a.remove()}),this.tracks[c.track]=null);
this.tracks[c.track]?this.tracks[c.track].id++:this.tracks[c.track]={id:0};c.id=this.tracks[c.track].id;$$("body")[0].insert(Prototype.Browser.IE?new Element("bgsound",{id:"sound_"+c.track+"_"+c.id,src:c.url,loop:1,autostart:!0}):Sound.template.evaluate(c))}}};
Prototype.Browser.Gecko&&0<navigator.userAgent.indexOf("Win")&&(navigator.plugins&&$A(navigator.plugins).detect(function(a){return-1!=a.name.indexOf("QuickTime")})?Sound.template=new Template('<object id="sound_#{track}_#{id}" width="0" height="0" type="audio/mpeg" data="#{url}"/>'):navigator.plugins&&$A(navigator.plugins).detect(function(a){return-1!=a.name.indexOf("Windows Media")})?Sound.template=new Template('<object id="sound_#{track}_#{id}" type="application/x-mplayer2" data="#{url}"></object>'):
navigator.plugins&&$A(navigator.plugins).detect(function(a){return-1!=a.name.indexOf("RealPlayer")})?Sound.template=new Template('<embed type="audio/x-pn-realaudio-plugin" style="height:0" id="sound_#{track}_#{id}" src="#{url}" loop="false" autostart="true" hidden="true"/>'):Sound.play=function(){});
Event.simulateMouse=function(a,b,c){c=Object.extend({pointerX:0,pointerY:0,buttons:0,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1},c||{});var d=document.createEvent("MouseEvents");d.initMouseEvent(b,!0,!0,document.defaultView,c.buttons,c.pointerX,c.pointerY,c.pointerX,c.pointerY,c.ctrlKey,c.altKey,c.shiftKey,c.metaKey,0,$(a));this.mark&&Element.remove(this.mark);this.mark=document.createElement("div");this.mark.appendChild(document.createTextNode(" "));document.body.appendChild(this.mark);this.mark.style.position=
"absolute";this.mark.style.top=c.pointerY+"px";this.mark.style.left=c.pointerX+"px";this.mark.style.width="5px";this.mark.style.height="5px;";this.mark.style.borderTop="1px solid red;";this.mark.style.borderLeft="1px solid red;";this.step&&alert("["+(new Date).getTime().toString()+"] "+b+"/"+Test.Unit.inspect(c));$(a).dispatchEvent(d)};
Event.simulateKey=function(a,b,c){c=Object.extend({ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,keyCode:0,charCode:0},c||{});var d=document.createEvent("KeyEvents");d.initKeyEvent(b,!0,!0,window,c.ctrlKey,c.altKey,c.shiftKey,c.metaKey,c.keyCode,c.charCode);$(a).dispatchEvent(d)};Event.simulateKeys=function(a,b){for(var c=0;c<b.length;c++)Event.simulateKey(a,"keypress",{charCode:b.charCodeAt(c)})};var Test={Unit:{}};Test.Unit.inspect=Object.inspect;Test.Unit.Logger=Class.create();
Test.Unit.Logger.prototype={initialize:function(a){(this.log=$(a))&&this._createLogTable()},start:function(a){this.log&&(this.testName=a,this.lastLogLine=document.createElement("tr"),this.statusCell=document.createElement("td"),this.nameCell=document.createElement("td"),this.nameCell.className="nameCell",this.nameCell.appendChild(document.createTextNode(a)),this.messageCell=document.createElement("td"),this.lastLogLine.appendChild(this.statusCell),this.lastLogLine.appendChild(this.nameCell),this.lastLogLine.appendChild(this.messageCell),
this.loglines.appendChild(this.lastLogLine))},finish:function(a,b){this.log&&(this.lastLogLine.className=a,this.statusCell.innerHTML=a,this.messageCell.innerHTML=this._toHTML(b),this.addLinksToResults())},message:function(a){this.log&&(this.messageCell.innerHTML=this._toHTML(a))},summary:function(a){this.log&&(this.logsummary.innerHTML=this._toHTML(a))},_createLogTable:function(){this.log.innerHTML='<div id="logsummary"></div><table id="logtable"><thead><tr><th>Status</th><th>Test</th><th>Message</th></tr></thead><tbody id="loglines"></tbody></table>';
this.logsummary=$("logsummary");this.loglines=$("loglines")},_toHTML:function(a){return a.escapeHTML().replace(/\n/g,"<br/>")},addLinksToResults:function(){$$("tr.failed .nameCell").each(function(a){a.title="Run only this test";Event.observe(a,"click",function(){window.location.search="?tests="+a.innerHTML})});$$("tr.passed .nameCell").each(function(a){a.title="Run all tests";Event.observe(a,"click",function(){window.location.search=""})})}};Test.Unit.Runner=Class.create();
Test.Unit.Runner.prototype={initialize:function(a,b){this.options=Object.extend({testLog:"testlog"},b||{});this.options.resultsURL=this.parseResultsURLQueryParameter();this.options.tests=this.parseTestsQueryParameter();this.options.testLog&&(this.options.testLog=$(this.options.testLog)||null);if(this.options.tests){this.tests=[];for(var c=0;c<this.options.tests.length;c++)/^test/.test(this.options.tests[c])&&this.tests.push(new Test.Unit.Testcase(this.options.tests[c],a[this.options.tests[c]],a.setup,
a.teardown))}else if(this.options.test)this.tests=[new Test.Unit.Testcase(this.options.test,a[this.options.test],a.setup,a.teardown)];else for(c in this.tests=[],a)/^test/.test(c)&&this.tests.push(new Test.Unit.Testcase(this.options.context?" -> "+this.options.titles[c]:c,a[c],a.setup,a.teardown));this.currentTest=0;this.logger=new Test.Unit.Logger(this.options.testLog);setTimeout(this.runTests.bind(this),1E3)},parseResultsURLQueryParameter:function(){return window.location.search.parseQuery().resultsURL},
parseTestsQueryParameter:function(){if(window.location.search.parseQuery().tests)return window.location.search.parseQuery().tests.split(",")},getResult:function(){for(var a=!1,b=0;b<this.tests.length;b++){if(0<this.tests[b].errors)return"ERROR";0<this.tests[b].failures&&(a=!0)}return a?"FAILURE":"SUCCESS"},postResults:function(){this.options.resultsURL&&new Ajax.Request(this.options.resultsURL,{method:"get",parameters:"result="+this.getResult(),asynchronous:!1})},runTests:function(){var a=this.tests[this.currentTest];
a?(a.isWaiting||this.logger.start(a.name),a.run(),a.isWaiting?(this.logger.message("Waiting for "+a.timeToWait+"ms"),setTimeout(this.runTests.bind(this),a.timeToWait||1E3)):(this.logger.finish(a.status(),a.summary()),this.currentTest++,this.runTests())):(this.postResults(),this.logger.summary(this.summary()))},summary:function(){for(var a=0,b=0,c=0,d=0;d<this.tests.length;d++)a+=this.tests[d].assertions,b+=this.tests[d].failures,c+=this.tests[d].errors;return(this.options.context?this.options.context+
": ":"")+this.tests.length+" tests, "+a+" assertions, "+b+" failures, "+c+" errors"}};Test.Unit.Assertions=Class.create();
Test.Unit.Assertions.prototype={initialize:function(){this.errors=this.failures=this.assertions=0;this.messages=[]},summary:function(){return this.assertions+" assertions, "+this.failures+" failures, "+this.errors+" errors\n"+this.messages.join("\n")},pass:function(){this.assertions++},fail:function(a){this.failures++;this.messages.push("Failure: "+a)},info:function(a){this.messages.push("Info: "+a)},error:function(a){this.errors++;this.messages.push(a.name+": "+a.message+"("+Test.Unit.inspect(a)+
")")},status:function(){return 0<this.failures?"failed":0<this.errors?"error":"passed"},assert:function(a,b){var c=b||'assert: got "'+Test.Unit.inspect(a)+'"';try{a?this.pass():this.fail(c)}catch(d){this.error(d)}},assertEqual:function(a,b,c){c=c||"assertEqual";try{a==b?this.pass():this.fail(c+': expected "'+Test.Unit.inspect(a)+'", actual "'+Test.Unit.inspect(b)+'"')}catch(d){this.error(d)}},assertInspect:function(a,b,c){c=c||"assertInspect";try{a==b.inspect()?this.pass():this.fail(c+': expected "'+
Test.Unit.inspect(a)+'", actual "'+Test.Unit.inspect(b)+'"')}catch(d){this.error(d)}},assertEnumEqual:function(a,b,c){c=c||"assertEnumEqual";try{$A(a).length==$A(b).length&&a.zip(b).all(function(a){return a[0]==a[1]})?this.pass():this.fail(c+": expected "+Test.Unit.inspect(a)+", actual "+Test.Unit.inspect(b))}catch(d){this.error(d)}},assertNotEqual:function(a,b,c){c=c||"assertNotEqual";try{a!=b?this.pass():this.fail(c+': got "'+Test.Unit.inspect(b)+'"')}catch(d){this.error(d)}},assertIdentical:function(a,
b,c){c=c||"assertIdentical";try{a===b?this.pass():this.fail(c+': expected "'+Test.Unit.inspect(a)+'", actual "'+Test.Unit.inspect(b)+'"')}catch(d){this.error(d)}},assertNotIdentical:function(a,b,c){c=c||"assertNotIdentical";try{a!==b?this.pass():this.fail(c+': expected "'+Test.Unit.inspect(a)+'", actual "'+Test.Unit.inspect(b)+'"')}catch(d){this.error(d)}},assertNull:function(a,b){var c=b||"assertNull";try{null==a?this.pass():this.fail(c+': got "'+Test.Unit.inspect(a)+'"')}catch(d){this.error(d)}},
assertMatch:function(a,b,c){c=c||"assertMatch";var d=new RegExp(a);try{d.exec(b)?this.pass():this.fail(c+' : regex: "'+Test.Unit.inspect(a)+" did not match: "+Test.Unit.inspect(b)+'"')}catch(e){this.error(e)}},assertHidden:function(a,b){this.assertEqual("none",a.style.display,b||"assertHidden")},assertNotNull:function(a,b){this.assert(null!=a,b||"assertNotNull")},assertType:function(a,b,c){c=c||"assertType";try{b.constructor==a?this.pass():this.fail(c+': expected "'+Test.Unit.inspect(a)+'", actual "'+
b.constructor+'"')}catch(d){this.error(d)}},assertNotOfType:function(a,b,c){c=c||"assertNotOfType";try{b.constructor!=a?this.pass():this.fail(c+': expected "'+Test.Unit.inspect(a)+'", actual "'+b.constructor+'"')}catch(d){this.error(d)}},assertInstanceOf:function(a,b,c){c=c||"assertInstanceOf";try{b instanceof a?this.pass():this.fail(c+": object was not an instance of the expected type")}catch(d){this.error(d)}},assertNotInstanceOf:function(a,b,c){try{b instanceof a?this.fail((c||"assertNotInstanceOf")+
": object was an instance of the not expected type"):this.pass()}catch(d){this.error(d)}},assertRespondsTo:function(a,b,c){c=c||"assertRespondsTo";try{b[a]&&"function"==typeof b[a]?this.pass():this.fail(c+": object doesn't respond to ["+a+"]")}catch(d){this.error(d)}},assertReturnsTrue:function(a,b,c){c=c||"assertReturnsTrue";try{var d=b[a];d||(d=b["is"+a.charAt(0).toUpperCase()+a.slice(1)]);d()?this.pass():this.fail(c+": method returned false")}catch(e){this.error(e)}},assertReturnsFalse:function(a,
b,c){c=c||"assertReturnsFalse";try{var d=b[a];d||(d=b["is"+a.charAt(0).toUpperCase()+a.slice(1)]);d()?this.fail(c+": method returned true"):this.pass()}catch(e){this.error(e)}},assertRaise:function(a,b,c){c=c||"assertRaise";try{b(),this.fail(c+": exception expected but none was raised")}catch(d){null==a||d.name==a?this.pass():this.error(d)}},assertElementsMatch:function(){var a=$A(arguments),b=$A(a.shift());if(b.length!=a.length)return this.fail("assertElementsMatch: size mismatch: "+b.length+" elements, "+
a.length+" expressions"),!1;b.zip(a).all(function(a,b){var e=$(a.first()),f=a.last();if(e.match(f))return!0;this.fail("assertElementsMatch: (in index "+b+") expected "+f.inspect()+" but got "+e.inspect())}.bind(this))&&this.pass()},assertElementMatches:function(a,b){this.assertElementsMatch([a],b)},benchmark:function(a,b,c){var d=new Date;(b||1).times(a);a=new Date-d;this.info((c||"Operation")+" finished "+b+" iterations in "+a/1E3+"s");return a},_isVisible:function(a){a=$(a);if(!a.parentNode)return!0;
this.assertNotNull(a);return a.style&&"none"==Element.getStyle(a,"display")?!1:this._isVisible(a.parentNode)},assertNotVisible:function(a,b){this.assert(!this._isVisible(a),Test.Unit.inspect(a)+" was not hidden and didn't have a hidden parent either. "+b)},assertVisible:function(a,b){this.assert(this._isVisible(a),Test.Unit.inspect(a)+" was not visible. "+b)},benchmark:function(a,b,c){var d=new Date;(b||1).times(a);a=new Date-d;this.info((c||"Operation")+" finished "+b+" iterations in "+a/1E3+"s");
return a}};Test.Unit.Testcase=Class.create();
Object.extend(Object.extend(Test.Unit.Testcase.prototype,Test.Unit.Assertions.prototype),{initialize:function(a,b,c,d){Test.Unit.Assertions.prototype.initialize.bind(this)();this.name=a;"string"==typeof b?(b=b.gsub(/(\.should[^\(]+\()/,"#{0}this,"),b=b.gsub(/(\.should[^\(]+)\(this,\)/,"#{1}(this)"),this.test=function(){eval("with(this){"+b+"}")}):this.test=b||function(){};this.setup=c||function(){};this.teardown=d||function(){};this.isWaiting=!1;this.timeToWait=1E3},wait:function(a,b){this.isWaiting=
!0;this.test=b;this.timeToWait=a},run:function(){try{try{this.isWaiting||this.setup.bind(this)(),this.isWaiting=!1,this.test.bind(this)()}finally{this.isWaiting||this.teardown.bind(this)()}}catch(a){this.error(a)}}});
Test.setupBDDExtensionMethods=function(){var a=function(a,c,d){this[a].apply(this,(c||[]).concat([d]))};Test.BDDMethods={};$H({shouldEqual:"assertEqual",shouldNotEqual:"assertNotEqual",shouldEqualEnum:"assertEnumEqual",shouldBeA:"assertType",shouldNotBeA:"assertNotOfType",shouldBeAn:"assertType",shouldNotBeAn:"assertNotOfType",shouldBeNull:"assertNull",shouldNotBeNull:"assertNotNull",shouldBe:"assertReturnsTrue",shouldNotBe:"assertReturnsFalse",shouldRespondTo:"assertRespondsTo"}).each(function(b){Test.BDDMethods[b.key]=
function(){var c=$A(arguments),d=c.shift();a.apply(d,[b.value,c,this])}});[Array.prototype,String.prototype,Number.prototype,Boolean.prototype].each(function(a){Object.extend(a,Test.BDDMethods)})};
Test.context=function(a,b,c){Test.setupBDDExtensionMethods();var d={},e={};for(specName in b)switch(specName){case "setup":case "teardown":d[specName]=b[specName];break;default:var f="test"+specName.gsub(/\s+/,"-").camelize(),g=b[specName].toString().split("\n").slice(1);/^\{/.test(g[0])&&(g=g.slice(1));g.pop();g=g.map(function(a){return a.strip()});d[f]=g.join("\n");e[f]=specName}new Test.Unit.Runner(d,{titles:e,testLog:c||"testlog",context:a})};
var ImgPoolHandlerWebKit=Class.create({initialize:function(){this.pool=[];this.pool_waiting=[];this.blank_image_loaded_event=this.blank_image_loaded_event.bind(this)},get:function(){return 0==this.pool.length?$(document.createElement("IMG")):this.pool.pop()},release:function(a){a.observe("load",this.blank_image_loaded_event);this.pool_waiting.push(a);a.src="/images/blank.png"},blank_image_loaded_event:function(a){a=a.target;a.stopObserving("load",this.blank_image_loaded_event);this.pool_waiting=this.pool_waiting.without(a);
this.pool.push(a)}}),ImgPoolHandlerDummy=Class.create({get:function(){return $(document.createElement("IMG"))},release:function(a){a.src="/images/blank.png"}}),ImgPoolHandler=function(){var a=Prototype.Browser.WebKit,b=UrlHash.get("image-pools");null!=b&&(a="0"!=b);return a?new ImgPoolHandlerWebKit(arguments):new ImgPoolHandlerDummy(arguments)};
PostLoader=function(){document.on("viewer:need-more-thumbs",this.need_more_post_data.bindAsEventListener(this));document.on("viewer:perform-search",this.perform_search.bindAsEventListener(this));this.hashchange_tags=this.hashchange_tags.bind(this);UrlHash.observe("tags",this.hashchange_tags);this.cached_posts=new Hash;this.cached_pools=new Hash;this.preloading_sample_for_post_id=this.sample_preload_container=null;this.load({results_mode:"center-on-current"})};
PostLoader.prototype.need_more_post_data=function(){this.loaded_extended_results||this.load({extending:!0})};
PostLoader.prototype.preload_sample_image=function(){var a=UrlHash.get("post-id");if(this.preloading_sample_for_post_id!=a&&(this.preloading_sample_for_post_id=a,this.sample_preload_container&&(this.sample_preload_container.destroy(),this.sample_preload_container=null),null!=a)){var b=Post.get_cached_sample_urls();null!=b&&String(a)in b&&(b=b[String(a)],debug("Advance preloading sample image for post "+a),this.sample_preload_container=new PreloadContainer,this.sample_preload_container.preload(b))}};
PostLoader.prototype.server_load_pool=function(){if(null!=this.result.pool_id){if(!this.result.disable_cache){var a=this.cached_pools.get(this.result.pool_id);if(a){this.result.pool=a;this.request_finished();return}}new Ajax.Request("/pool/show.json",{parameters:{id:this.result.pool_id},method:"get",onCreate:function(a){this.current_ajax_requests.push(a.request)}.bind(this),onComplete:function(a){this.current_ajax_requests=this.current_ajax_requests.without(a.request);this.request_finished()}.bind(this),
onSuccess:function(a){-1!=this.current_ajax_requests.indexOf(a.request)&&(this.result.pool=a.responseJSON,this.cached_pools.set(this.result.pool_id,this.result.pool))}.bind(this)})}};
PostLoader.prototype.server_load_posts=function(){var a="holds:false "+this.result.tags+" limit:"+this.result.post_limit;if(!this.result.disable_cache){var b=this.cached_posts.get(a);if(b){this.result.posts=b;this.request_finished();return}}new Ajax.Request("/post.json",{parameters:{tags:a,api_version:2,filter:1,include_tags:1,include_votes:1,include_pools:1},method:"get",onCreate:function(a){this.current_ajax_requests.push(a.request)}.bind(this),onComplete:function(a){this.current_ajax_requests=
this.current_ajax_requests.without(a.request);this.request_finished()}.bind(this),onSuccess:function(b){-1!=this.current_ajax_requests.indexOf(b.request)&&(b=b.responseJSON,this.result.posts=b.posts,Post.register_resp(b),this.cached_posts.set(a,this.result.posts))}.bind(this),onFailure:function(a){var b="error "+a.status;a.responseJSON&&(b=a.responseJSON.reason);notice("Error loading posts: "+b);this.result.error=!0}.bind(this)})};
PostLoader.prototype.request_finished=function(){if(!this.current_ajax_requests.length){var a=this.result;this.result=null;if(null==a.error){var b=[];if(null!=a.posts)for(var c=0;c<a.posts.length;++c)b.push(a.posts[c].id);document.fire("viewer:displayed-pool-changed",{pool:a.pool});document.fire("viewer:searched-tags-changed",{tags:a.tags});c=!0;a.pool&&(c=!1);a.load_options.extending&&(c=!1);b.length<a.post_limit&&(debug("Received posts fewer than requested ("+b.length+" < "+a.post_limit+"), clamping"),
c=!1);UrlHash.set_deferred({tags:a.tags});document.fire("viewer:loaded-posts",{tags:a.tags,post_ids:b,pool:a.pool,extending:a.load_options.extending,can_be_extended_further:c,load_options:a.load_options})}}};
PostLoader.prototype.load=function(a){a||(a={});var b=a.disable_cache,c=a.extending,d=a.tags;null==d&&(d=UrlHash.get("tags"));if(c||null!=d||null!=UrlHash.get("post-id")){debug("PostLoader.load("+c+", "+b+")");this.preload_sample_image();this.loaded_extended_results=c;this.current_ajax_requests=[];this.result={};this.result.load_options=a;this.result.tags=d;this.result.disable_cache=b;if(null!=this.result.tags){var e=null;this.result.tags.split(" ").each(function(a){(a=a.match(/^pool:(\d+)/))&&(e=
parseInt(a[1]))});this.result.pool_id=e;a=c?1E3:100;null!=e&&(a=1E3);this.result.post_limit=a;this.current_ajax_requests.push(null);this.server_load_pool();this.server_load_posts();this.current_ajax_requests=this.current_ajax_requests.without(null)}this.request_finished()}else UrlHash.set({tags:""})};PostLoader.prototype.hashchange_tags=function(){var a=UrlHash.get("tags");a!=this.last_seen_tags&&(this.last_seen_tags=a,debug("changed tags"),this.load())};
PostLoader.prototype.perform_search=function(a){var b=a.memo.tags;this.last_seen_tags=b;a=a.memo.results_mode||"center-on-first";debug("do search: "+b);this.load({tags:b,results_mode:a})};
ThumbnailView=function(a,b){this.container=a;this.view=b;this.post_ids=[];this.post_frames=[];this.centered_post_idx=this.expanded_post_idx=null;this.last_mouse_y=this.last_mouse_x=this.centered_post_offset=0;this.allow_wrapping=this.thumb_container_shown=!0;this.thumb_preload_container=new PreloadContainer;this.unused_thumb_pool=[];this.posts_populated=[0,0];document.on("DOMMouseScroll",this.document_mouse_wheel_event.bindAsEventListener(this));document.on("mousewheel",this.document_mouse_wheel_event.bindAsEventListener(this));
document.on("viewer:displayed-image-loaded",this.displayed_image_loaded_event.bindAsEventListener(this));document.on("viewer:set-active-post",function(a){this.set_active_post([a.memo.post_id,a.memo.post_frame],a.memo.lazy,a.memo.center_thumbs)}.bindAsEventListener(this));document.on("viewer:show-next-post",function(a){this.show_next_post(a.memo.prev)}.bindAsEventListener(this));document.on("viewer:scroll",function(a){this.scroll(a.memo.left)}.bindAsEventListener(this));document.on("viewer:set-thumb-bar",
function(a){a.memo.toggle?this.show_thumb_bar(!this.thumb_container_shown):this.show_thumb_bar(a.memo.set)}.bindAsEventListener(this));document.on("viewer:loaded-posts",this.loaded_posts_event.bindAsEventListener(this));this.hashchange_post_id=this.hashchange_post_id.bind(this);UrlHash.observe("post-id",this.hashchange_post_id);UrlHash.observe("post-frame",this.hashchange_post_id);new DragElement(this.container,{ondrag:this.container_ondrag.bind(this)});Element.on(window,"resize",this.window_resize_event.bindAsEventListener(this));
this.container.on("mousemove",this.container_mousemove_event.bindAsEventListener(this));this.container.on("mouseover",this.container_mouseover_event.bindAsEventListener(this));this.container.on("mouseout",this.container_mouseout_event.bindAsEventListener(this));this.container.on("click",this.container_click_event.bindAsEventListener(this));this.container.on("dblclick",".post-thumb,.browser-thumb-hover-overlay",this.container_dblclick_event.bindAsEventListener(this));this.container.down(".browser-thumb-hover-overlay").on("click",
function(a){a.isLeftClick()&&a.preventDefault()}.bindAsEventListener(this));this.config={};-1!=navigator.userAgent.indexOf("iPad")?this.config.thumb_scale=1:-1!=navigator.userAgent.indexOf("iPhone")||-1!=navigator.userAgent.indexOf("iPod")?this.config.thumb_scale=.5:-1!=navigator.userAgent.indexOf("Android")?(this.config.thumb_scale=scale(Math.min(window.innerWidth,window.innerHeight),320,640,.5,1),debug("Unclamped thumb scale: "+this.config.thumb_scale),this.config.thumb_scale=Math.min(this.config.thumb_scale,
1),this.config.thumb_scale=Math.max(this.config.thumb_scale,.5),debug("startup, window size: "+window.innerWidth+"x"+window.innerHeight)):this.config.thumb_scale=1;debug("Thumb scale: "+this.config.thumb_scale);this.config_changed();this.thumb_container_shown=!1;this.show_thumb_bar(!0)};ThumbnailView.prototype.window_resize_event=function(a){a.stopped||this.thumb_container_shown&&this.center_on_post_for_scroll(this.centered_post_idx)};
ThumbnailView.prototype.loaded_posts_event=function(a){var b=a.memo.post_ids,c=this.post_ids,d=this.centered_post_idx;this.remove_all_posts();b=b.reject(Post.is_blacklisted);this.post_ids=[];this.post_frames=[];for(var e=0;e<b.length;++e){var f=b[e],g=Post.posts.get(f);if(0<g.frames.length)for(var h=0;h<g.frames.length;++h)this.post_ids.push(f),this.post_frames.push(h);else this.post_ids.push(f),this.post_frames.push(-1)}this.allow_wrapping=!a.memo.can_be_extended_further;this.container.down(".post-browser-no-results").show(null!=
a.memo.tags&&0==this.post_ids.length);this.container.down(".post-browser-posts").show(0!=this.post_ids.length);if(a.memo.extending){b=sort_array_by_distance(c.slice(0,d+3),d);c=null;for(e=0;e<b.length;++e)if(g=Post.posts.get(b[e]),null!=g){c=g.id;break}debug("center-on-"+c);null==c&&(this.centered_post_offset=0,c=new_post_ids[0]);e=this.post_ids.indexOf(c);this.center_on_post_for_scroll(e)}else g=a.memo.load_options.results_mode||"center-on-current",b="center-on-first"==g||"jump-to-first"==g?[this.post_ids[0],
this.post_frames[0]]:this.get_current_post_id_and_frame(),e=this.get_post_idx(b),null==e&&(e=0),this.centered_post_offset=0,this.center_on_post_for_scroll(e),"jump-to-first"!=g&&null!=this.view.wanted_post_id||this.set_active_post(b,!1,!1,!0);null==a.memo.tags&&this.show_thumb_bar(!1)};ThumbnailView.prototype.container_ondrag=function(a){this.centered_post_offset-=a.dX;this.center_on_post_for_scroll(this.centered_post_idx)};
ThumbnailView.prototype.container_mouseover_event=function(a){a=$(a.target);a.hasClassName(".post-thumb")||(a=a.up(".post-thumb"));a&&this.expand_post(a.post_idx)};ThumbnailView.prototype.container_mouseout_event=function(a){a=$(a.target);a.hasClassName(".browser-thumb-hover-overlay")||(a=a.up(".browser-thumb-hover-overlay"));a&&this.expand_post(null)};
ThumbnailView.prototype.hashchange_post_id=function(){var a=this.get_current_post_id_and_frame();if(null!=a[0]){var b=a[1];if(a[0]!=this.view.displayed_post_id||b!=this.view.displayed_post_frame)b=this.get_post_idx(a),this.centered_post_offset=0,this.center_on_post_for_scroll(b),this.set_active_post(a,!1,!1,!0)}};
ThumbnailView.prototype.get_post_idx=function(a){var b=a[0];a=a[1];var c=this.post_ids.indexOf(b);if(-1==c)return null;if(-1==a)return c;for(var d=c;d<this.post_ids.length&&this.post_ids[d]==b;){if(this.post_frames[d]==a)return d;++d}return c};
ThumbnailView.prototype.get_current_post_id_and_frame=function(){var a=UrlHash.get("post-id");if(null==a)return 0==this.post_ids.length?[null,null]:[this.post_ids[0],this.post_frames[0]];var a=parseInt(a),b=UrlHash.get("post-frame");null==b&&(b=this.view.get_default_post_frame(a));return[a,b]};ThumbnailView.prototype.container_mousemove_event=function(a){var b=a.pointerX()-document.documentElement.scrollLeft;a=a.pointerY()-document.documentElement.scrollTop;this.last_mouse_x=b;this.last_mouse_y=a};
ThumbnailView.prototype.document_mouse_wheel_event=function(a){a.stop();var b;a.wheelDelta?b=a.wheelDelta:a.detail&&(b=-a.detail);this.thumb_container_shown?document.fire("viewer:scroll",{left:0<=b}):document.fire("viewer:show-next-post",{prev:0<=b})};ThumbnailView.prototype.set_active_post=function(a,b,c,d,e){null!=a[0]&&(this.view.set_post(a[0],a[1],b,d,e),c&&(a=this.get_post_idx(a),this.centered_post_offset=0,this.center_on_post_for_scroll(a)))};
ThumbnailView.prototype.set_active_post_idx=function(a,b,c,d,e){null!=a&&this.set_active_post([this.post_ids[a],this.post_frames[a]],b,c,d,e)};
ThumbnailView.prototype.show_next_post=function(a){if(0!=this.post_ids.length){var b=this.get_post_idx([this.view.wanted_post_id,this.view.wanted_post_frame]);null==b&&(b=0);var c=a?-1:1;this.post_frames[b]!=this.view.wanted_post_frame&&1==c&&(debug("Snapped the display to the nearest frame"),1==c&&(c=0));c=b+c+this.post_ids.length;c%=this.post_ids.length;if(a&&c>b||!a&&c<b){if(!this.allow_wrapping)return;!this.thumb_container_shown&&a?notice("Continued from the end"):this.thumb_container_shown||
a||notice("Starting over from the beginning")}this.set_active_post_idx(c,!0,!0,!1,!0)}};ThumbnailView.prototype.scroll=function(a){if(this.thumb_container_shown){var b=this.centered_post_idx;0<this.centered_post_offset&&a||0>this.centered_post_offset&&!a||(b+=a?-1:1);this.centered_post_offset=0;0>b?b=this.allow_wrapping?this.post_ids.length-1:0:b>=this.post_ids.length&&(b=this.allow_wrapping?0:this.post_ids.length-1);this.center_on_post_for_scroll(b)}};
ThumbnailView.prototype.center_on_post_for_scroll=function(a){this.thumb_container_shown&&this.expand_post(null);this.center_on_post(a);this.thumb_container_shown&&(a=document.elementFromPoint(this.last_mouse_x,this.last_mouse_y),(a=$(a))&&(a=a.up(".post-thumb"))&&this.expand_post(a.post_idx))};
ThumbnailView.prototype.remove_post=function(a){if(this.posts_populated[0]==this.posts_populated[1])return!1;var b=this.container.down(".post-browser-posts");a?(--this.posts_populated[1],a=b.lastChild):(++this.posts_populated[0],a=b.firstChild);b=b.removeChild(a);this.unused_thumb_pool.push(b);return!0};ThumbnailView.prototype.remove_all_posts=function(){for(;this.remove_post(!0););};
ThumbnailView.prototype.add_post_to_display=function(a){var b=this.container.down(".post-browser-posts");if(a){a=this.posts_populated[1];if(a==this.post_ids.length)return!1;++this.posts_populated[1];a=this.create_thumb(a);b.insertBefore(a,null)}else{if(0==this.posts_populated[0])return!1;--this.posts_populated[0];a=this.posts_populated[0];a=this.create_thumb(a);b.insertBefore(a,b.firstChild)}return!0};
ThumbnailView.prototype.populate_post=function(a){if(!this.is_post_idx_shown(a))if(a==this.posts_populated[1])this.add_post_to_display(!0);else if(a==this.posts_populated[0])this.add_post_to_display(!1);else{this.remove_all_posts();var b=this.container.down(".post-browser-posts"),c=this.create_thumb(a);b.appendChild(c);this.posts_populated[0]=a;this.posts_populated[1]=a+1}};ThumbnailView.prototype.is_post_idx_shown=function(a){return a>=this.posts_populated[1]?!1:a>=this.posts_populated[0]};
ThumbnailView.prototype.get_width_adjacent_to_post=function(a,b){var c=$("p"+a);if(b){var d=c.parentNode.lastChild;return d==c?0:d.offsetLeft+d.offsetWidth-(c.offsetLeft+c.offsetWidth)}return c.offsetLeft};
ThumbnailView.prototype.center_on_post=function(a){if(!this.post_ids)debug("unexpected: center_on_post has no post_ids");else if(null!=Post.posts.get(this.post_ids[a])&&(a>3*this.post_ids.length/4&&function(){document.fire("viewer:need-more-thumbs",{view:this})}.defer(),this.centered_post_idx=a,this.thumb_container_shown)){for(;;){var b=$("p"+this.centered_post_idx);if(!b)break;var c=b.offsetWidth/2+this.centered_post_offset;if(0<=c&&c<b.offsetWidth)break;var c=this.centered_post_idx+(0<this.centered_post_offset?
1:-1),d=$("p"+c);if(null==d)break;this.centered_post_offset-=d.offsetLeft+d.offsetWidth/2-(b.offsetLeft+b.offsetWidth/2);a=this.centered_post_idx=c;break}this.populate_post(a);for(b=0;2>b;++b)for(var c=!!b,d=this.container.offsetWidth/2,d=1.25*d,e=d+500;;){var f=!1,g=this.get_width_adjacent_to_post(a,c),g=g+this.centered_post_offset*(c?-1:1);0>g&&(g=1);if(g<d){if(!this.add_post_to_display(c))break;f=!1}else if(g>e){if(this.remove_post(c),f){alert("error");break}}else break}this.preload_thumbs();a=
$("p"+a);a=this.container.offsetWidth/2-a.offsetWidth/2-a.offsetLeft;a-=this.centered_post_offset;a=Math.round(a);this.container.down(".post-browser-scroller").setStyle({left:a+"px"})}};
ThumbnailView.prototype.preload_thumbs=function(){for(var a=[],b=0;5>b;++b){var c=this.posts_populated[0]-b-1;0<=c&&a.push(c);c=this.posts_populated[1]+b;c<this.post_ids.length&&a.push(c)}this.thumb_preload_container.get_all().each(function(b){var c=b.post_idx;-1!=a.indexOf(c)?a[c]=null:this.thumb_preload_container.cancel_preload(b)}.bind(this));for(b=0;b<a.length;++b)if(c=a[b],null!=c){var d=Post.posts.get(this.post_ids[c]),e=this.post_frames[c];this.thumb_preload_container.preload(-1!=e?d.frames[e].preview_url:
d.preview_url).post_idx=c}};
ThumbnailView.prototype.expand_post=function(a){if(!Prototype.BrowserIsMobile&&this.thumb_container_shown){var b=this.post_ids[a],c=this.container.down(".browser-thumb-hover-overlay");c.hide();c.down("IMG").src="/images/blank.gif";this.expanded_post_idx=a;if(null!=a&&(b=Post.posts.get(b),"deleted"!=b.status)){var d=$("p"+a),e=this.container.down(".browser-bottom-bar").offsetHeight;c.style.bottom=e+"px";a=this.post_frames[a];var f;-1!=a?(e=b.frames[a],f=e.preview_width,e=e.preview_url):(f=b.actual_preview_width,
e=b.preview_url);d=d.cumulativeOffset().left-f/2+d.offsetWidth/2;c.style.left=d+"px";d=document.viewport.getDimensions().width-d;c.style.maxWidth=d+"px";c.href="/post/browse#"+b.id+this.view.post_frame_hash(b,a);c.down("IMG").src=e;c.show()}}};
ThumbnailView.prototype.create_thumb=function(a){var b=this.post_frames[a],c=Post.posts.get(this.post_ids[a]);if(0==this.unused_thumb_pool.length){var d=$(document.createElement("li"));d.innerHTML='<div class="inner"><a class="thumb" tabindex="-1"><img alt="" class="preview" onload="this.style.visibility = \'visible\';"></a></div>';d.className="post-thumb"}else d=this.unused_thumb_pool.pop();d.id="p"+a;d.post_idx=a;d.down("A").href="/post/browse#"+c.id+this.view.post_frame_hash(c,b);a=d.down("IMG");
b=-1!=b?c.frames[b].preview_url:c.preview_url;a.src!=b&&(a.style.visibility="hidden",a.src=b);this.set_thumb_dimensions(d);return d};
ThumbnailView.prototype.set_thumb_dimensions=function(a){var b=a.post_idx,c=this.post_frames[b],b=Post.posts.get(this.post_ids[b]);-1!=c?(b=b.frames[c],c=b.preview_width,b=b.preview_height):(c=b.actual_preview_width,b=b.actual_preview_height);var c=c*this.config.thumb_scale,b=b*this.config.thumb_scale,d=[Math.min(c,200*this.config.thumb_scale),200*this.config.thumb_scale],e=Math.round((c-d[0])/2),f=Math.max(0,d[1]-b);a=a.down(".inner");a.actual_width=d[0];a.actual_height=d[1];a.setStyle({width:d[0]+
"px",height:d[1]+"px"});a=a.down("img");a.width=c;a.height=b;a.setStyle({marginTop:f+"px",marginLeft:-e+"px"})};ThumbnailView.prototype.config_changed=function(){var a=200*this.config.thumb_scale+10;this.container.down(".post-browser-posts-container").setStyle({height:a+"px"});this.container.select("LI.post-thumb").each(this.set_thumb_dimensions.bind(this));this.center_on_post_for_scroll(this.centered_post_idx)};
ThumbnailView.prototype.container_click_event=function(a){if(!a.stopped)if($(a.target).up(".browser-thumb-hover-overlay"))this.set_active_post_idx(this.expanded_post_idx),a.preventDefault();else{var b=$(a.target).up(".post-thumb");null!=b&&(a.preventDefault(),this.set_active_post_idx(b.post_idx))}};ThumbnailView.prototype.container_dblclick_event=function(a){a.button||(a.preventDefault(),this.show_thumb_bar(!1))};
ThumbnailView.prototype.show_thumb_bar=function(a){this.thumb_container_shown!=a&&(this.thumb_container_shown=a,this.container.show(a),this.center_on_post_for_scroll(this.centered_post_idx),document.fire("viewer:thumb-bar-changed",{shown:this.thumb_container_shown,height:this.thumb_container_shown?this.container.offsetHeight:0}))};ThumbnailView.prototype.get_adjacent_post_idx_wrapped=function(a,b){return a=(a+(b?1:-1)+this.post_ids.length)%this.post_ids.length};
ThumbnailView.prototype.displayed_image_loaded_event=function(a){if(null!=this.post_ids&&(a=this.get_post_idx([a.memo.post_id,a.memo.post_frame]),null!=a)){var b=[];b.push([this.post_ids[a],this.post_frames[a]]);var c=this.get_adjacent_post_idx_wrapped(a,!0);null!=c&&b.push([this.post_ids[c],this.post_frames[c]]);c=this.get_adjacent_post_idx_wrapped(a,!1);null!=c&&b.push([this.post_ids[c],this.post_frames[c]]);this.view.preload(b)}};
function InputHandler(){TrackFocus();document.on(window.opera||Prototype.Browser.Gecko?"keypress":"keydown",this.document_keypress_event.bindAsEventListener(this))}
InputHandler.prototype.handle_keypress=function(a){var b=a.charCode;b||(b=a.keyCode);if(b==Event.KEY_ESC&&document.focusedElement&&document.focusedElement.blur&&!document.focusedElement.hasClassName("no-blur-on-escape"))return document.focusedElement.blur(),!0;var c=a.target;if("INPUT"==c.tagName||"TEXTAREA"==c.tagName)return!1;if(63==b)return debug("xxx"),document.fire("viewer:show-help"),!0;if(a.shiftKey||a.altKey||a.ctrlKey||a.metaKey)return!1;a=Prototype.Browser.WebKit?192:96;if(32==b)document.fire("viewer:set-thumb-bar",
{toggle:!0});else if(49==b)document.fire("viewer:vote",{score:1});else if(50==b)document.fire("viewer:vote",{score:2});else if(51==b)document.fire("viewer:vote",{score:3});else if(b==a)document.fire("viewer:vote",{score:0});else if(65==b||97==b)document.fire("viewer:show-next-post",{prev:!0});else if(69==b||101==b)document.fire("viewer:edit-post");else if(83==b||115==b)document.fire("viewer:show-next-post",{prev:!1});else if(70==b||102==b)document.fire("viewer:focus-tag-box");else if(86==b||118==
b)document.fire("viewer:view-large-toggle");else if(b==Event.KEY_PAGEUP)document.fire("viewer:show-next-post",{prev:!0});else if(b==Event.KEY_PAGEDOWN)document.fire("viewer:show-next-post",{prev:!1});else if(b==Event.KEY_LEFT)document.fire("viewer:scroll",{left:!0});else if(b==Event.KEY_RIGHT)document.fire("viewer:scroll",{left:!1});else return!1;return!0};InputHandler.prototype.document_keypress_event=function(a){this.handle_keypress(a)&&a.stop()};
BrowserView=function(a){this.container=a;this.current_ajax_request=this.displayed_post_frame=this.displayed_post_id=this.wanted_post_frame=this.wanted_post_id=null;this.last_preload_request=[];this.last_preload_request_active=!1;this.image_pool=new ImgPoolHandler;this.img_box=this.container.down(".image-box");this.container.down(".image-canvas");(function(a,c){if(!Prototype.BrowserIsMobile){c.large_by_default="0"===jQuery.cookie("browse_large_by_default")?!1:!0;var d=a(a(".post-info-right-edge li")[0]).css("position",
"relative"),e=a(".default_to_large_cont"),f=e.children("a"),g=f.children("span");f.click(function(){c.large_by_default=!c.large_by_default;c.large_by_default?g.show():g.hide();jQuery.cookie("browse_large_by_default",c.large_by_default?1:0);return!1});d.hover(function(){e.show()},function(){e.hide()});c.large_by_default||g.hide()}})(jQuery,this);Prototype.Browser.Opera||(this.canvas=create_canvas_2d());this.canvas&&(this.canvas.hide(),this.img_box.appendChild(this.canvas));this.zoom_level=0;this.post_ui_visible=
!0;this.update_navigator=this.update_navigator.bind(this);Event.on(window,"resize",this.window_resize_event.bindAsEventListener(this));document.on("viewer:vote",function(a){this.vote_widget&&this.vote_widget.set(a.memo.score)}.bindAsEventListener(this));TagCompletion&&TagCompletion.init();this.container.down(".image-container").on("dblclick",".image-container",function(a){a.button||(a.stop(),document.fire("viewer:set-thumb-bar",{toggle:!0}))}.bindAsEventListener(this));document.on("viewer:view-large-toggle",
function(a){this.toggle_view_large_image()}.bindAsEventListener(this));this.container.down(".post-info").on("click",".toggle-zoom",function(a){a.stop();this.toggle_view_large_image(!0)}.bindAsEventListener(this));this.container.down(".parent-post").down("A").on("click",this.parent_post_click_event.bindAsEventListener(this));this.container.down(".child-posts").down("A").on("click",this.child_posts_click_event.bindAsEventListener(this));this.container.down(".post-frames").on("click",".post-frame-link",
function(a,c){a.stop();document.fire("viewer:set-active-post",{post_id:this.displayed_post_id,post_frame:c.post_frame,center_thumbs:!0})}.bind(this));this.thumb_bar_height=0;document.on("viewer:thumb-bar-changed",function(a){this.thumb_bar_height=a.memo.height;this.update_image_window_size();this.set_post_ui(a.memo.shown);this.scale_and_position_image(!0)}.bindAsEventListener(this));$(document.body).pickClassName("is-member","not-member",User.is_member_or_higher());$(document.body).pickClassName("is-moderator",
"not-moderator",User.is_mod_or_higher());this.container.down(".post-tags").on("click",".post-tag",function(a,c){a.stop();document.fire("viewer:perform-search",{tags:c.tag_name})}.bind(this));this.container.down(".post-approve").on("click",function(a){a.stop();confirm("Approve this post?")&&Post.approve(this.displayed_post_id,!1)}.bindAsEventListener(this));this.container.down(".post-unflag").on("click",function(a){a.stop();confirm("Unflag this post?")&&Post.unflag(this.displayed_post_id)}.bindAsEventListener(this));
this.container.down(".post-delete").on("click",function(a){a.stop();a=Post.posts.get(this.displayed_post_id);var c="";a.flag_detail&&(c=a.flag_detail.reason);(a=prompt("Reason:",c))&&""!=a&&Post.approve(this.displayed_post_id,a)}.bindAsEventListener(this));this.container.down(".post-undelete").on("click",function(a){a.stop();confirm("Undelete this post?")&&Post.undelete(this.displayed_post_id)}.bindAsEventListener(this));this.container.down(".flag-button").on("click",function(a){a.stop();Post.flag(this.displayed_post_id)}.bindAsEventListener(this));
this.container.down(".activate-post").on("click",function(a){a.stop();var c=this.displayed_post_id;confirm("Activate this post?")&&Post.update_batch([{id:c,is_held:!1}],function(){Post.posts.get(c).is_held?notice("Couldn't activate post"):notice("Activated post")}.bind(this))}.bindAsEventListener(this));this.container.down(".reparent-post").on("click",function(a){a.stop();if(confirm("Make this post the parent?")){a=this.displayed_post_id;var c=Post.posts.get(a);null!=c&&Post.reparent_post(a,c.parent_id,
!1)}}.bindAsEventListener(this));this.container.down(".pool-info").on("click",".remove-pool-from-post",function(a,c){a.stop();var d=c.up(".pool-info"),e=Pool.pools.get(d.pool_id).name.replace(/_/g," ");confirm("Remove this post from pool #"+d.pool_id+": "+e+"?")&&Pool.remove_post(d.post_id,d.pool_id)}.bind(this));a=this.container.down(".post-edit");a.down("FORM").on("submit",function(a){a.stop();this.edit_save()}.bindAsEventListener(this));this.container.down(".show-tag-edit").on("click",function(a){a.stop();
this.edit_show(!0)}.bindAsEventListener(this));this.container.down(".edit-save").on("click",function(a){a.stop();this.edit_save()}.bindAsEventListener(this));this.container.down(".edit-cancel").on("click",function(a){a.stop();this.edit_show(!1)}.bindAsEventListener(this));this.edit_post_area_changed=this.edit_post_area_changed.bind(this);a.down(".edit-tags").on("paste",function(a){this.edit_post_area_changed.defer()}.bindAsEventListener(this));a.down(".edit-tags").on("keydown",function(a){this.edit_post_area_changed.defer()}.bindAsEventListener(this));
new TagCompletionBox(a.down(".edit-tags"));this.container.down(".post-edit").on("keydown",function(a){a.keyCode==Event.KEY_ESC?this.edit_show(!1):a.keyCode==Event.KEY_RETURN&&(a.stop(),this.edit_save())}.bindAsEventListener(this));document.on("viewer:edit-post",function(a){document.fire("viewer:set-thumb-bar",{set:!0});this.edit_show(!0)}.bindAsEventListener(this));document.on("posts:update",function(a){null!=a.memo.post_ids.get(this.displayed_post_id)&&this.set_post_info()}.bindAsEventListener(this));
this.vote_widget=new Vote(jQuery(this.container.down(".vote-container"),null));this.vote_widget.initShortcut();this.blacklist_override_post_id=null;this.container.down(".show-blacklisted").on("click",function(a){a.preventDefault()}.bindAsEventListener(this));this.container.down(".show-blacklisted").on("dblclick",function(a){a.stop();this.blacklist_override_post_id=this.displayed_post_id;a=Post.posts.get(this.displayed_post_id);this.set_main_image(a,this.displayed_post_frame)}.bindAsEventListener(this));
this.img_box.on("viewer:center-on",function(a){this.center_image_on(a.memo.x,a.memo.y)}.bindAsEventListener(this));this.navigator=new Navigator(this.container.down(".image-navigator"),this.img_box);this.container.on("swipe:horizontal",function(a){document.fire("viewer:show-next-post",{prev:a.memo.right})}.bindAsEventListener(this));Prototype.BrowserIsMobile&&(this.create_voting_popup(),this.image_swipe=new SwipeHandler(this.container.down(".image-container")));this.container.down(".edit-frames-button").on("click",
function(a){a.stop();this.show_frame_editor()}.bindAsEventListener(this));this.frame_editor=new FrameEditor(this.container.down(".frame-editor"),this.img_box,this.container.down(".frame-editor-popup"),{onClose:function(){this.hide_frame_editor()}.bind(this)});null==this.image_swipe&&(this.image_dragger=new WindowDragElementAbsolute(this.img_box,this.update_navigator))};
BrowserView.prototype.create_voting_popup=function(){var a=this.container.down(".vote-popup-container");a.show();this.popup_vote_widget=new Vote(jQuery(a),null);this.popup_vote_widget.initShortcut();var b=this.container.down(".vote-popup-flash"),c=this.container.down(".vote-popup-expand");c.show();var d=null;this.popup_vote_dragger=new DragElement(c,{ondown:function(c){c.latest_event.stop();b.hide();b.removeClassName("flash-star");this.popup_vote_widget.set_mouseover(null);d=null;a.removeClassName("vote-popup-hidden")}.bind(this),
onup:function(c){c.cancelling&&(debug("cancelling drag"),d=null);this.popup_vote_widget.set_mouseover(d);c=this.popup_vote_widget.activate_item(d);if(null!=c){for(var f=0;4>f;++f)b.removeClassName("star-"+f);b.addClassName("star-"+c);b.show();c=this.image_window_size;b.setStyle({left:c.width/2-b.offsetWidth/2+"px",top:c.height/2-b.offsetHeight/2+"px"});b.addClassName("flash-star")}a.addClassName("vote-popup-hidden");d=null}.bind(this),ondrag:function(a){d=document.elementFromPoint(a.x,a.y);this.popup_vote_widget.set_mouseover(d)}.bind(this)})};
BrowserView.prototype.set_post_ui=function(a){Prototype.BrowserIsMobile&&(a=!1);this.container.down(".post-info").show(a&&null!=this.displayed_post_id);a!=this.post_ui_visible&&(this.post_ui_visible=a,this.navigator&&this.navigator.set_autohide(!a),this.post_ui_visible||this.edit_show(!1))};BrowserView.prototype.image_loaded_event=function(a){this.img.fully_loaded=!0;document.fire("viewer:displayed-image-loaded",{post_id:this.displayed_post_id,post_frame:this.displayed_post_frame});this.update_canvas()};
BrowserView.prototype.post_frame_list_includes=function(a,b,c){return null!=a.find(function(a){return a[0]==b&&a[1]==c})};
BrowserView.prototype.preload=function(a){var b=this.last_preload_request;this.last_preload_request=a;if(this.post_frame_list_includes(b,this.wanted_post_id,this.wanted_post_frame)){this.last_preload_request_active=!0;for(var b=new PreloadContainer,c=0;c<a.length;++c){var d=a[c][1],e=Post.posts.get(a[c][0]);-1!=d?b.preload(e.frames[d].url):b.preload(e.sample_url)}this.preload_container&&this.preload_container.destroy();this.preload_container=b}else this.last_preload_request_active=!1};
BrowserView.prototype.load_post_id_data=function(a){debug("load needed");null==this.current_ajax_request&&new Ajax.Request("/post.json",{parameters:{tags:"id:"+a,api_version:2,filter:1,include_tags:"1",include_votes:"1",include_pools:1},method:"get",onCreate:function(a){this.current_ajax_request=a.request}.bind(this),onSuccess:function(b){this.current_ajax_request==b.request&&(b=b.responseJSON,(this.success=0<b.posts.length)?Post.register_resp(b):notice("Post #"+a+" doesn't exist"))}.bind(this),onComplete:function(b){this.current_ajax_request==
b.request&&(this.current_ajax_request=null);b.request.success()&&this.success||a!=this.wanted_post_id?this.set_post(this.wanted_post_id,this.wanted_post_frame):null==this.displayed_post_id&&document.fire("viewer:set-thumb-bar",{set:!0})}.bind(this),onFailure:function(a){notice("Error "+a.status+" loading post")}.bind(this)})};
BrowserView.prototype.set_viewing_larger_version=function(a,b){this.viewing_larger_version=a;var c=Post.posts.get(this.displayed_post_id),c=null!=c&&c.jpeg_url!=c.sample_url,d=b||!this.large_by_default?a:!a;this.container.down(".zoom-icon-none").show(!c);this.container.down(".zoom-icon-in").show(c&&!d);this.container.down(".zoom-icon-out").show(c&&d);Prototype.BrowserIsMobile&&this.image_dragger&&this.image_dragger.set_disabled(!a);this.frame_editor&&(this.frame_editor.set_drag_to_create(!a),this.frame_editor.set_show_corner_drag(!a))};
BrowserView.prototype.set_main_image=function(a,b,c){null!=this.img&&(this.img.stopObserving(),this.img.parentNode.removeChild(this.img),this.image_pool.release(this.img),this.img=null);var d=Post.is_blacklisted(a.id)&&a.id!=this.blacklist_override_post_id;this.container.down(".blacklisted-message").show(d);d||(this.img=this.image_pool.get(),this.img.className="main-image",this.canvas&&this.canvas.hide(),this.img.show(),this.img.setStyle({pointerEvents:"none"}),this.img.on("load",this.image_loaded_event.bindAsEventListener(this)),
!c&&this.large_by_default&&(this.viewing_larger_version=!0),this.img.fully_loaded=!1,-1!=b&&b<a.frames.length?(b=a.frames[b],this.img.src=b.url,this.img_box.original_width=b.width,this.img_box.original_height=b.height,this.img_box.show()):this.viewing_larger_version&&a.jpeg_url?(this.img.src=a.jpeg_url,this.img_box.original_width=a.jpeg_width,this.img_box.original_height=a.jpeg_height,this.img_box.show()):!this.viewing_larger_version&&a.sample_url?(this.img.src=a.sample_url,this.img_box.original_width=
a.sample_width,this.img_box.original_height=a.sample_height,this.img_box.show()):this.img_box.hide(),this.container.down(".image-box").appendChild(this.img),this.viewing_larger_version&&(this.navigator.set_image(a.preview_url,a.actual_preview_width,a.actual_preview_height),this.navigator.set_autohide(!this.post_ui_visible)),this.navigator.enable(this.viewing_larger_version),this.scale_and_position_image())};
BrowserView.prototype.set_post=function(a,b,c,d,e){if(null==a)throw"post_id must not be null";this.cancel_lazily_load();this.wanted_post_id=a;this.wanted_post_frame=b;this.wanted_post_no_hash_change=d;this.wanted_post_replace_history=e;if(a!=this.displayed_post_id||b!=this.displayed_post_frame){var f=this.last_preload_request_active&&this.post_frame_list_includes(this.last_preload_request,a,b);c&&!f?this.lazy_load_timer=window.setTimeout(function(){this.lazy_load_timer=null;this.set_post(this.wanted_post_id,
this.wanted_post_frame,!1,this.wanted_post_no_hash_change,this.wanted_post_replace_history)}.bind(this),500):(this.hide_frame_editor(),c=Post.posts.get(a),null==c?(null==this.displayed_post_id&&this.container.down(".post-info").hide(),this.load_post_id_data(a)):(null==b&&(this.wanted_post_frame=b=this.get_default_post_frame(a)),-1!=b&&c.frames.length<=b&&(b=-1),this.displayed_post_id=a,this.displayed_post_frame=b,d||(d=this.get_post_frame_hash(c,b),UrlHash.set_deferred({"post-id":a,"post-frame":d},
e)),this.set_viewing_larger_version(!1),this.set_main_image(c,b),this.vote_widget&&(this.vote_widget.post_id&&(Post.votes.set(this.vote_widget.post_id,this.vote_widget.data.vote),Post.posts.get(this.vote_widget.post_id).score=this.vote_widget.data.score),this.vote_widget.post_id=c.id,this.vote_widget.updateWidget(Post.votes.get(c.id),c.score)),this.popup_vote_widget&&(this.popup_vote_widget.post_id=c.id,this.popup_vote_widget.updateWidget(Post.votes.get(c.id),c.score)),document.fire("viewer:displayed-post-changed",
{post_id:a,post_frame:b}),this.set_post_info(),this.edit_show(!1)))}};BrowserView.prototype.post_frame_hash=function(a,b){return 0==a.frames.length?"":"-"+(-1==b?"F":b)};BrowserView.prototype.get_default_post_frame=function(a){a=Post.posts.get(a);return null==a?null:0<a.frames.length?0:-1};BrowserView.prototype.get_post_frame_hash=function(a,b){return b==(0<a.frames.length?0:-1)?null:b};
BrowserView.prototype.set_post_info=function(){var a=Post.posts.get(this.displayed_post_id);if(a){this.container.down(".post-id").setTextContent(a.id);this.container.down(".post-id-link").href="/post/show/"+a.id;this.container.down(".posted-by").show();this.container.down(".posted-at").setTextContent(time_ago_in_words(new Date(1E3*a.created_at)));for(var b=this.container.down(".pool-info");b.firstChild;)b.removeChild(b.firstChild);a.pool_posts&&a.pool_posts.each(function(c){var d=c[1];c=d.pool_id;
var e=Pool.pools.get(c),f=e.name.replace(/_/g," "),d=d.sequence;d.match(/^[0-9]/)&&(d="#"+d);var g='<div class="pool-info">Post ${sequence} in <a class="pool-link" href="/post/browse#/pool:${pool_id}">${desc}</a> (<a target="_blank" href="/pool/show/${pool_id}">pool page</a>)';Pool.can_edit_pool(e)&&(g+='<span class="advanced-editing"> (<a href="#" class="remove-pool-from-post">remove</a>)</div></span>');e=g.subst({sequence:d,pool_id:c,desc:f.escapeHTML()}).createElement();e.post_id=a.id;e.pool_id=
c;b.appendChild(e)}.bind(this));null!=a.creator_id?(this.container.down(".posted-by").down("A").href="/user/show/"+a.creator_id,this.container.down(".posted-by").down("A").setTextContent(a.author)):(this.container.down(".posted-by").down("A").href="#",this.container.down(".posted-by").down("A").setTextContent("Anonymous"));this.container.down(".post-dimensions").setTextContent(a.width+"x"+a.height);this.container.down(".post-source").show(""!=a.source);if(""!=a.source){var c=a.source,d=null,e=a.source.match(/^http:\/\/.*pixiv\.net\/(img\d+\/)?img\/(\w+)\/(\d+)(_.+)?\.\w+$/);
e?(c="pixiv #"+e[3]+" ("+e[2]+")",d="http://www.pixiv.net/member_illust.php?mode=medium&illust_id="+e[3]):"http://"==a.source.substr(0,7)&&(c=c.substr(7),"www."==c.substr(0,4)&&(c=c.substr(4)),20<c.length&&(c=c.substr(0,20)+"..."),d=a.source);e=this.container.down(".post-source");e.down("A").show(null!=d);e.down("SPAN").show(null==d);d?(e.down("A").href=d,e.down("A").setTextContent(c)):e.down("SPAN").setTextContent(c)}if(0<a.frames.length){this.container.down(".post-frames").removeClassName("no-frames");
for(d=this.container.down(".post-frame-list");d.firstChild;)d.removeChild(d.firstChild);for(e=-1;e<a.frames.length;++e){var c=-1==e?"main":e+1,f=document.createElement("a");f.href="/post/browse#"+a.id+this.post_frame_hash(a,e);f.className="post-frame-link";this.displayed_post_frame==e&&(f.className+=" current-post-frame");f.setTextContent(c);f.post_frame=e;d.appendChild(f)}}else this.container.down(".post-frames").addClassName("no-frames");this.container.down(".post-rating").setTextContent({s:"Safe",
q:"Questionable",e:"Explicit"}[a.rating]);this.container.down(".post-score").setTextContent(a.score);this.container.down(".post-hidden").show(!a.is_shown_in_index);this.container.down(".post-info").show(this.post_ui_visible);c=function(a){return(a=a.match(/.*\.([^.]+)/))?a[1]:""};e=a.sample_url!=a.file_url;d=a.jpeg_url!=a.file_url;f=null!=a.file_url&&!e;this.container.down(".download-links").show(f||e||d);this.container.down(".download-image").show(f);f&&(this.container.down(".download-image").href=
a.file_url,this.container.down(".download-image-desc").setTextContent(number_to_human_size(a.file_size)+" "+c(a.file_url.toUpperCase())));this.container.down(".download-jpeg").show(e);e&&(this.container.down(".download-jpeg").href=d?a.jpeg_url:a.file_url,e=number_to_human_size(d?a.jpeg_file_size:a.file_size)+" JPG",this.container.down(".download-jpeg-desc").setTextContent(e));this.container.down(".download-png").show(d);d&&(this.container.down(".download-png").href=a.file_url,c=number_to_human_size(a.file_size)+
" "+c(a.file_url.toUpperCase()),this.container.down(".download-png-desc").setTextContent(c));c=this.container.down(".parent-post");c.show(null!=a.parent_id);a.parent_id&&(c.down("A").href="/post/browse#"+a.parent_id);c=this.container.down(".child-posts");c.show(a.has_children);a.has_children&&(c.down("A").href="/post/browse#/parent:"+a.id);for(var g=this.container.down(".post-tags");g.firstChild;)g.removeChild(g.firstChild);Post.get_post_tags_with_type(a).each(function(a){var b=a[0],c=a[1];a=$(document.createElement("SPAN",
""));a=$(a);a.className="tag-type-"+c;var d=document.createTextNode(" ");a.appendChild(d);c=jQuery("<a>",{text:b,href:"/post/browse#/"+b,"class":"post-tag tag-type-"+c});c.html(c.html().replace(/_/g,"_<wbr>"));c=c[0];c.tag_name=b;a.appendChild(c);g.appendChild(a)});this.container.down(".flag-button").show("active"==a.status);this.container.down(".post-approve").show("flagged"==a.status||"pending"==a.status);this.container.down(".post-delete").show("deleted"!=a.status);this.container.down(".post-undelete").show("deleted"==
a.status);c=this.container.down(".flagged-info");c.show("flagged"==a.status);"flagged"==a.status&&a.flag_detail&&(d=c.down(".by"),c.down(".flagged-by-box").show(null!=a.flag_detail.user_id),null!=a.flag_detail.user_id&&(d.setTextContent(a.flag_detail.flagged_by),d.href="/user/show/"+a.flag_detail.user_id),d=c.down(".reason"),d.setTextContent(a.flag_detail.reason));d=a.flag_detail&&a.flag_detail.user_id==User.get_current_user_id();d=c&&(User.is_mod_or_higher()||d);c.down(".post-unflag").show(d);this.container.down(".status-pending").show("pending"==
a.status);this.container.down(".pending-reason-box").show(a.flag_detail&&a.flag_detail.reason);a.flag_detail&&this.container.down(".pending-reason").setTextContent(a.flag_detail.reason);c=this.container.down(".status-deleted");c.show("deleted"==a.status);"deleted"==a.status&&(d=c.down(".by-container"),d.show(null!=a.flag_detail.flagged_by),d=d.down(".by"),d.setTextContent(a.flag_detail.flagged_by),d.href="/user/show/"+a.flag_detail.user_id,d=c.down(".reason"),d.setTextContent(a.flag_detail.reason));
this.container.down(".status-held").show(a.is_held);c=User.get_current_user_id()==a.creator_id||User.is_mod_or_higher();this.container.down(".activate-post").show(c)}};
BrowserView.prototype.edit_show=function(a){var b=Post.posts.get(this.displayed_post_id);b||(a=!1);User.is_member_or_higher()||(a=!1);this.edit_shown=a;this.container.down(".post-tags-box").show(!a);this.container.down(".post-edit").show(a);a?(this.select_edit_box(".post-edit-main"),a=Post.get_post_tags_with_type(b).pluck(0),a=a.join(" ")+" ",this.container.down(".edit-tags").old_value=a,this.container.down(".edit-tags").value=a,this.container.down(".edit-source").value=b.source,this.container.down(".edit-parent").value=
b.parent_id,this.container.down(".edit-shown-in-index").checked=b.is_shown_in_index,a=new Hash({s:".edit-safe",q:".edit-questionable",e:".edit-explicit"}),this.container.down(a.get(b.rating)).checked=!0,this.edit_post_area_changed(),this.container.down(".edit-tags").focus()):this.frame_editor.discard()};BrowserView.prototype.edit_post_area_changed=function(){var a=this.container.down(".post-edit").down(".edit-tags");a.style.height="0px";a.style.height=a.scrollHeight+"px"};
BrowserView.prototype.edit_save=function(){var a=function(){notice("Post saved");this.displayed_post_id==b&&this.edit_show(!1)}.bind(this),b=this.displayed_post_id;if(this.frame_editor&&this.frame_editor.is_opened())this.frame_editor.save(a);else{this.container.down(".edit-tags").blur();var c="s";(new Hash({s:".edit-safe",q:".edit-questionable",e:".edit-explicit"})).each(function(a){this.container.down(a[1]).checked&&(c=a[0])}.bind(this));Post.update_batch([{id:b,tags:this.container.down(".edit-tags").value,
old_tags:this.container.down(".edit-tags").old_value,source:this.container.down(".edit-source").value,parent_id:this.container.down(".edit-parent").value,is_shown_in_index:this.container.down(".edit-shown-in-index").checked?1:0,rating:c}],a)}};BrowserView.prototype.window_resize_event=function(a){a.stopped||(this.update_image_window_size(),this.scale_and_position_image(!0))};
BrowserView.prototype.toggle_view_large_image=function(a){var b=Post.posts.get(this.displayed_post_id);null!=b&&null!=this.img&&b.jpeg_url!=b.sample_url&&(this.set_viewing_larger_version(!this.viewing_larger_version,a),this.set_main_image(b,null,a))};BrowserView.prototype.update_image_window_size=function(){this.image_window_size=getWindowSize();this.image_window_size.height-=this.thumb_bar_height;this.image_window_size.height=Math.max(this.image_window_size.height,0);this.update_navigator()};
BrowserView.prototype.scale_and_position_image=function(a){var b=this.img_box;if(this.img){var c=b.original_width,b=b.original_height;if(Post.posts.get(this.displayed_post_id)){var d=this.image_window_size,e=1;this.viewing_larger_version||(e=d.width/c,b*e>d.height&&(e=d.height/b));e*=Math.pow(.9,this.zoom_level);this.displayed_image_width=Math.round(c*e);this.displayed_image_height=Math.round(b*e);this.img.width=this.displayed_image_width;this.img.height=this.displayed_image_height;this.update_canvas();
this.frame_editor&&this.frame_editor.set_image_dimensions(this.displayed_image_width,this.displayed_image_height);a&&this.viewing_larger_version||(a=.5,this.viewing_larger_version&&(a=this.image_window_size.height/2,a/=this.displayed_image_height),this.center_image_on(.5,a))}else debug("unexpected: displayed post "+this.displayed_post_id+" unknown")}};
BrowserView.prototype.update_navigator=function(){if(this.navigator&&this.img){var a=-this.img_box.offsetTop;x=-this.img_box.offsetLeft+this.image_window_size.width/2;y=a+this.image_window_size.height/2;this.navigator.image_position_changed(x/this.displayed_image_width,y/this.displayed_image_height,this.image_window_size.height/this.displayed_image_height,this.image_window_size.width/this.displayed_image_width)}};
BrowserView.prototype.update_canvas=function(){if(!this.img.fully_loaded)return debug("image incomplete; can't render to canvas"),!1;if(this.canvas&&(this.canvas.rendered_url!=this.img.src||this.canvas.width!=this.displayed_image_width||this.canvas.height!=this.displayed_image_height))return this.canvas.rendered_url=this.img.src,this.canvas.width=this.displayed_image_width,this.canvas.height=this.displayed_image_height,this.canvas.getContext("2d").drawImage(this.img,0,0,this.displayed_image_width,
this.displayed_image_height),this.canvas.show(),this.img.hide(),!0};BrowserView.prototype.center_image_on=function(a,b){var c=b*this.displayed_image_height,d=a*this.displayed_image_width-this.image_window_size.width/2,d=Math.round(d),c=c-this.image_window_size.height/2,c=Math.round(c);this.img_box.setStyle({left:-d+"px",top:-c+"px"});this.update_navigator()};
BrowserView.prototype.cancel_lazily_load=function(){null!=this.lazy_load_timer&&(window.clearTimeout(this.lazy_load_timer),this.lazy_load_timer=null)};
WindowTitleHandler=function(){this.searched_tags="";this.pool=this.post_frame=this.post_id=null;document.on("viewer:searched-tags-changed",function(a){this.searched_tags=a.memo.tags||"";this.update()}.bindAsEventListener(this));document.on("viewer:displayed-post-changed",function(a){this.post_frame=this.post_id=a.memo.post_id;this.update()}.bindAsEventListener(this));document.on("viewer:displayed-pool-changed",function(a){this.pool=a.memo.pool;this.update()}.bindAsEventListener(this));this.update()};
WindowTitleHandler.prototype.update=function(){var a=Post.posts.get(this.post_id);if(this.pool){var b=this.pool.name.replace(/_/g," ");a&&a.pool_posts&&(a=a.pool_posts.get(this.pool.id))&&(a=a.sequence,b+=" ",a.match(/^[0-9]/)&&(b+="#"),b+=a)}else b="/"+this.searched_tags.replace(/_/g," ");document.title=b+" - Browse"};BrowserView.prototype.parent_post_click_event=function(a){a.stop();a=Post.posts.get(this.displayed_post_id);null!=a&&null!=a.parent_id&&this.set_post(a.parent_id)};
BrowserView.prototype.child_posts_click_event=function(a){a.stop();document.fire("viewer:perform-search",{tags:"parent:"+this.displayed_post_id,results_mode:"center-on-current"})};BrowserView.prototype.select_edit_box=function(a){this.shown_edit_container&&this.shown_edit_container.hide();this.shown_edit_container=this.container.down(a);this.shown_edit_container.show()};
BrowserView.prototype.show_frame_editor=function(){this.select_edit_box(".frame-editor");var a=null;-1!=this.displayed_post_frame&&(a=this.displayed_post_frame,document.fire("viewer:set-active-post",{post_id:this.displayed_post_id,post_frame:-1}));this.frame_editor.open(this.displayed_post_id);this.container.down(".post-frames").hide();null!=a&&this.frame_editor.focus(a)};BrowserView.prototype.hide_frame_editor=function(){this.frame_editor.discard();this.container.down(".post-frames").show()};
var Navigator=function(a,b){this.container=a;this.target=b;this.autohide=this.hovering=!1;this.img=this.container.down(".image-navigator-img");this.container.show();this.handlers=[];this.handlers.push(this.container.on("mousedown",this.mousedown_event.bindAsEventListener(this)));this.handlers.push(this.container.on("mouseover",this.mouseover_event.bindAsEventListener(this)));this.handlers.push(this.container.on("mouseout",this.mouseout_event.bindAsEventListener(this)));this.dragger=new DragElement(this.container,
{snap_pixels:0,onenddrag:this.enddrag.bind(this),ondrag:this.ondrag.bind(this)})};Navigator.prototype.set_image=function(a,b,c){this.img.src=a;this.img.width=b;this.img.height=c};Navigator.prototype.enable=function(a){this.container.show(a)};Navigator.prototype.mouseover_event=function(a){a.relatedTarget&&a.relatedTarget.isParentNode(this.container)||(debug("over "+a.target.className+", "+this.container.className+", "+a.target.isParentNode(this.container)),this.hovering=!0,this.update_visibility())};
Navigator.prototype.mouseout_event=function(a){a.relatedTarget&&a.relatedTarget.isParentNode(this.container)||(debug("out "+a.target.className),this.hovering=!1,this.update_visibility())};Navigator.prototype.mousedown_event=function(a){var b=a.pointerX();a=a.pointerY();b=this.get_normalized_coords(b,a);this.center_on_position(b)};Navigator.prototype.enddrag=function(a){this.locked_to_x=this.shift_lock_anchor=null;this.update_visibility()};
Navigator.prototype.ondrag=function(a){var b=this.get_normalized_coords(a.x,a.y);a.latest_event.shiftKey!=(null!=this.shift_lock_anchor)&&(a.latest_event.shiftKey?this.shift_lock_anchor=[b[0],b[1]]:this.locked_to_x=this.shift_lock_anchor=null);this.center_on_position(b)};
Navigator.prototype.image_position_changed=function(a,b,c,d){this.container.down(".navigator-cursor").setStyle({top:this.img.height*(b-c/2)+"px",left:this.img.width*(a-d/2)+"px",width:this.img.width*d+"px",height:this.img.height*c+"px"})};Navigator.prototype.get_normalized_coords=function(a,b){var c=this.img.cumulativeOffset();a-=c.left;b-=c.top;a/=this.img.width;b/=this.img.height;return[a,b]};
Navigator.prototype.center_on_position=function(a){if(this.shift_lock_anchor){if(null==this.locked_to_x){var b=Math.abs(a[0]-this.shift_lock_anchor[0]),c=Math.abs(a[1]-this.shift_lock_anchor[1]);if(.1<b||.1<c)this.locked_to_x=b>c}null!=this.locked_to_x&&(this.locked_to_x?a[1]=this.shift_lock_anchor[1]:a[0]=this.shift_lock_anchor[0])}a[0]=Math.max(0,Math.min(a[0],1));a[1]=Math.max(0,Math.min(a[1],1));this.target.fire("viewer:center-on",{x:a[0],y:a[1]})};
Navigator.prototype.set_autohide=function(a){this.autohide=a;this.update_visibility()};Navigator.prototype.update_visibility=function(){this.container.down(".image-navigator-box").style.visibility=!this.autohide||this.hovering||this.dragger.dragging?"visible":"hidden"};Navigator.prototype.destroy=function(){this.dragger.destroy();this.handlers.each(function(a){a.stop()});this.dragger=this.handlers=null;this.container.hide()};var DANBOORU_VERSION={major:1,minor:13,build:0};
function notice(a,b){if(b){var c=$("static_notice");if(c){c.update(a);c.show();return}}start_notice_timer();$("notice").update(a);$("notice-container").show()}
function number_to_human_size(a,b){null==b&&(b=1);a=Number(a);text=1==a.toFixed(0)?"1 Byte":1024>a?a.toFixed(0)+" Bytes":1048576>a?(a/1024).toFixed(b)+" KB":1073741824>a?(a/1048576).toFixed(b)+" MB":1099511627776>a?(a/1073741824).toFixed(b)+" GB":(a/1099511627776).toFixed(b)+" TB";return text=text.gsub(/([0-9]\.\d*?)0+ /,"#{1} ").gsub(/\. /," ")}
function time_ago_in_words(a,b){null==b&&(b=new Date);a=a.valueOf();b=b.valueOf();distance_in_seconds=Math.abs((b-a)/1E3).round();distance_in_minutes=(distance_in_seconds/60).round();if(1>=distance_in_minutes)return"1 minute";if(44>=distance_in_minutes)return distance_in_minutes+" minutes";if(89>=distance_in_minutes)return"1 hour";if(1439>=distance_in_minutes){var c=distance_in_minutes/60,c=(c-.5).round();return c+" hours"}return 2879>=distance_in_minutes?"1 day":43199>=distance_in_minutes?(c=distance_in_minutes/
1440,c=(c-.5).round(),c+" days"):86399>=distance_in_minutes?"1 month":525959>=distance_in_minutes?(c=distance_in_minutes/43200,c=(c-.5).round(),c+" months"):(distance_in_minutes/525960).toFixed(1)+" years"}scale=function(a,b,c,d,e){return(a-b)*(e-d)/(c-b)+d};clamp=function(a,b,c){return Math.max(Math.min(a,c),b)};var ClearNoticeTimer;
function start_notice_timer(){ClearNoticeTimer&&window.clearTimeout(ClearNoticeTimer);ClearNoticeTimer=window.setTimeout(function(){$("notice-container").hide()},5E3)}var ClipRange=Class.create({initialize:function(a,b){if(a>b)throw"paramError";this.min=a;this.max=b},clip:function(a){return a<this.min?this.min:a>this.max?this.max:a}});Object.extend(Element,{appendChildBase:Element.appendChild,appendChild:function(a){this.appendChildBase(a);return a}});
Object.extend(Element.Methods,{showBase:Element.show,show:function(a,b){return b||null==b?$(a).showBase():$(a).hide()},setClassName:function(a,b,c){return c?$(a).addClassName(b):$(a).removeClassName(b)},pickClassName:function(a,b,c,d){$(a).setClassName(b,d);$(a).setClassName(c,!d)},isParentNode:function(a,b){for(;a;){if(a==b)return!0;a=a.parentNode}return!1},setTextContent:function(a,b){null!=a.innerText?a.innerText=b:a.textContent=b;return a},recursivelyVisible:function(a){for(;a!=document.documentElement;){if(!a.visible())return!1;
a=a.parentNode}return!0}});Element.addMethods();var KeysDown=new Hash;document.observe("blur",function(a){KeysDown=new Hash});
function OnKeyCharCode(a,b,c){window.opera||(c||(c=document),c.observe("keyup",function(b){b.keyCode==a&&KeysDown.set(KeysDown[b.keyCode],!1)}),c.observe("keypress",function(c){if(c.charCode==a&&!(c.shiftKey||c.altKey||c.ctrlKey||c.metaKey||KeysDown.get(KeysDown[c.keyCode]))){KeysDown.set(KeysDown[c.keyCode],!0);var e=c.target;"INPUT"!=e.tagName&&"TEXTAREA"!=e.tagName&&(b(c),c.stop(),c.preventDefault())}}))}
function OnKey(a,b,c,d){b||(b={});var e=b.Element;e||(e=document);if(e!=document||!window.opera||b.AlwaysAllowOpera)e.observe("keyup",function(b){b.keyCode==a&&(KeysDown[b.keyCode]=!1,d&&d(b))}),e.observe("keydown",function(d){if(d.keyCode==a&&!d.metaKey&&d.shiftKey==!!b.shiftKey&&d.altKey==!!b.altKey&&d.ctrlKey==!!b.ctrlKey&&(b.allowRepeat||!KeysDown[d.keyCode])){KeysDown[d.keyCode]=!0;var e=d.target;if(b.AllowTextAreaFields||"TEXTAREA"!=e.tagName)if(b.AllowInputFields||"INPUT"!=e.tagName)if(!c||
c(d))d.stop(),d.preventDefault()}})}function InitTextAreas(){$$("TEXTAREA").each(function(a){var b=a.up("FORM");b&&!a.set_login_handler&&(a.set_login_handler=!0,OnKey(13,{ctrlKey:!0,AllowInputFields:!0,AllowTextAreaFields:!0,Element:a},function(a){$(b).simulate_submit()}))})}function InitAdvancedEditing(){"1"==Cookie.get("show_advanced_editing")&&$(document.documentElement).removeClassName("hide-advanced-editing")}
Element.addMethods("FORM",{simulate_submit:function(a){a=$(a);if(document.createEvent){var b=document.createEvent("HTMLEvents");b.initEvent("submit",!0,!0);a.dispatchEvent(b);b.stopped||a.submit()}else a.fireEvent("onsubmit")&&a.submit()}});Element.addMethods({simulate_anchor_click:function(a,b){a=$(a);document.dispatchEvent?a.dispatchEvent(b)&&!b.stopped&&(window.location.href=a.href):a.fireEvent("onclick",b)&&(window.location.href=a.href)}});
clone_event=function(a){if(document.dispatchEvent){var b=document.createEvent("MouseEvent");b.initMouseEvent(a.type,a.canBubble,a.cancelable,a.view,a.detail,a.screenX,a.screenY,a.clientX,a.clientY,a.ctrlKey,a.altKey,a.shiftKey,a.metaKey,a.button,a.relatedTarget)}else b=document.createEventObject(a);return Event.extend(b)};
Object.extend(String.prototype,{subst:function(a){var b=this,c;for(c in a){var d=new RegExp("\\${"+c+"}","g"),e=a[c];null==e&&(e="");b=b.replace(d,e)}return b},createElement:function(){var a=document.createElement("div");a.innerHTML=this;return a.removeChild(a.firstChild)}});function createElement(a,b,c){a=$(document.createElement(a));a.className=b;a.innerHTML=c;return a}Ajax.Request.prototype.successBase=Ajax.Request.prototype.success;Ajax.Request.prototype.success=function(){try{if(null==this.transport.getAllResponseHeaders())return!1}catch(a){return!1}return this.successBase()};
Ajax.Responders.register({onException:function(a,b){var c="";a.url&&(c+="AJAX URL: "+a.url+"\n");try{var d=a.parameters;for(key in d){var e=d[key],f=e.length;1024<e.length&&(e=e.slice(0,1024)+"...");c+="Parameter ("+f+"): "+key+"="+e+"\n"}}catch(g){c+="Couldn't get response parameters: "+g+"\n"}try{e=a.transport.responseText,f=e.length,1024<e.length&&(e=e.slice(0,1024)+"..."),c+="Response ("+f+"): ->"+e+"<-\n"}catch(g){c+="Couldn't get response text: "+g+"\n"}ReportError(null,null,null,b,c);(function(){throw b;
}).defer()}});Prototype.Browser.Gecko&&(Function.prototype.bindAsEventListener=function(){var a=this,b=$A(arguments),c=b.shift();return function(d){try{return a.apply(c,[d||window.event].concat(b))}catch(e){(function(){throw e;}).defer()}}});window.onerror=function(a,b,c){ReportError(a,b,c,null)};sort_array_by_distance=function(a,b){var c=[];c.push(a[b]);for(var d=1;;++d){var e=c.length;0<=b-d&&c.push(a[b-d]);b+d<a.length&&c.push(a[b+d]);if(e==c.length)break}return c};
distance_squared=function(a,b,c,d){return Math.pow(a-c,2)+Math.pow(b-d,2)};getWindowSize=function(){var a={};null!=window.innerWidth?(a.width=window.innerWidth,a.height=window.innerHeight):(a.width=document.documentElement.clientWidth,a.height=document.documentElement.clientHeight);return a};create_canvas_2d=function(){var a=document.createElement("canvas");return a.getContext&&a.getContext("2d")?a:null};Prototype.Browser.AndroidWebKit=-1!=navigator.userAgent.indexOf("Android")&&-1!=navigator.userAgent.indexOf("WebKit");
Prototype.BrowserFeatures.Touchscreen=function(){return window.Touch||-1!=navigator.userAgent.indexOf("Mobile Safari/")||-1!=navigator.userAgent.indexOf("Mobile/")?!0:!1}();Prototype.BrowserIsMobile=function(){var a=navigator.userAgent;return!!(a.match(/Android/i)||a.match(/BlackBerry/i)||a.match(/iPhone|iPad|iPod/i)||a.match(/Opera Mini/i)||a.match(/IEMobile/i))}();
DragElement=function(a,b){$(document.body).addClassName("not-dragging");this.options=b||{};this.options.condition||(this.options.condition=function(){return!0});null==this.options.snap_pixels&&(this.options.snap_pixels=10);this.ignore_mouse_events_until=null;this.mousemove_event=this.mousemove_event.bindAsEventListener(this);this.mousedown_event=this.mousedown_event.bindAsEventListener(this);this.dragstart_event=this.dragstart_event.bindAsEventListener(this);this.mouseup_event=this.mouseup_event.bindAsEventListener(this);
this.click_event=this.click_event.bindAsEventListener(this);this.selectstart_event=this.selectstart_event.bindAsEventListener(this);this.touchmove_event=this.touchmove_event.bindAsEventListener(this);this.touchstart_event=this.touchstart_event.bindAsEventListener(this);this.touchend_event=this.touchend_event.bindAsEventListener(this);this.move_timer_update=this.move_timer_update.bind(this);this.element=a;this.dragging=!1;this.drag_handlers=[];this.handlers=[];b.no_mouse||(this.handlers.push(a.on("mousedown",
this.mousedown_event)),this.handlers.push(a.on("dragstart",this.dragstart_event)));b.no_touch||(this.handlers.push(a.on("touchstart",this.touchstart_event)),this.handlers.push(a.on("touchmove",this.touchmove_event)));Prototype.Browser.WebKit||this.handlers.push(a.on("click",this.click_event))};DragElement.prototype.destroy=function(){this.stop_dragging(null,!0);this.handlers.each(function(a){a.stop()});this.handlers=[]};
DragElement.prototype.move_timer_update=function(){this.move_timer=null;if(this.options.ondrag&&null!=this.last_event_params){var a=this.last_event_params;this.last_event_params=null;var b=a.x,c=a.y,d=b-this.anchor_x,e=c-this.anchor_y,f=b-this.last_x,g=c-this.last_y;this.last_x=b;this.last_y=c;if(this.options.ondrag)this.options.ondrag({dragger:this,x:b,y:c,aX:d,aY:e,dX:f,dY:g,latest_event:a.event})}};
DragElement.prototype.mousemove_event=function(a){a.stop();var b=window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft,c=window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop,b=a.pointerX()-b,c=a.pointerY()-c;this.handle_move_event(a,b,c)};
DragElement.prototype.touchmove_event=function(a){for(var b=null,c=0;c<a.changedTouches.length;++c){var d=a.changedTouches[c];if(d.identifier==this.dragging_touch_identifier){b=d;break}}null!=b&&(a.preventDefault(),!window.navigator.standalone&&b.pageY>window.innerHeight-10?(debug("Dragged off the bottom"),this.stop_dragging(a,!0)):this.handle_move_event(a,b.pageX,b.pageY))};
DragElement.prototype.handle_move_event=function(a,b,c){if(this.dragging){if(!this.dragged){var d=this.options.snap_pixels;if(Math.pow(b-this.anchor_x,2)+Math.pow(c-this.anchor_y,2)<d*d)return}if(!this.dragged){if(this.options.onstartdrag&&this.options.onstartdrag({handler:this,latest_event:a})){this.dragging=!1;return}this.dragged=!0;$(document.body).addClassName(this.overriden_drag_class||"dragging");$(document.body).removeClassName("not-dragging")}this.last_event_params={x:b,y:c,event:a};this.dragging_by_touch&&
Prototype.Browser.AndroidWebKit?null==this.move_timer&&(this.move_timer=window.setTimeout(this.move_timer_update,10)):this.move_timer_update()}};
DragElement.prototype.mousedown_event=function(a){if(a.isLeftClick()){if(null!=this.ignore_mouse_events_until){if((new Date).valueOf()<this.ignore_mouse_events_until)return;this.ignore_mouse_events_until=null}var b=window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft,c=window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop,b=a.pointerX()-b,c=a.pointerY()-c;this.start_dragging(a,!1,b,c,0)}};
DragElement.prototype.touchstart_event=function(a){for(var b=null,c=0;c<a.changedTouches.length;++c){var d=a.changedTouches[c];if(d.target.isParentNode(this.element)){b=d;break}}null!=b&&this.start_dragging(a,!0,b.pageX,b.pageY,b.identifier)};
DragElement.prototype.start_dragging=function(a,b,c,d,e){if(!(null!=this.dragging_touch_identifier||this.options.condition&&!1===this.options.condition())&&(this.drag_handlers.push(document.on("selectstart",this.selectstart_event)),this.drag_handlers.push(Element.on(window,"pagehide",this.pagehide_event.bindAsEventListener(this))),b?(this.drag_handlers.push(document.on("touchend",this.touchend_event)),this.drag_handlers.push(document.on("touchcancel",this.touchend_event)),this.drag_handlers.push(document.on("touchmove",
this.touchmove_event))):(this.drag_handlers.push(document.on("mouseup",this.mouseup_event)),this.drag_handlers.push(document.on("mousemove",this.mousemove_event))),this.dragging=!0,this.dragged=!1,this.dragging_by_touch=b,this.dragging_touch_identifier=e,this.anchor_x=c,this.anchor_y=d,this.last_x=this.anchor_x,this.last_y=this.anchor_y,this.options.ondown))this.options.ondown({dragger:this,x:c,y:d,latest_event:a})};DragElement.prototype.pagehide_event=function(a){this.stop_dragging(a,!0)};
DragElement.prototype.touchend_event=function(a){for(var b=0;b<a.changedTouches.length;++b)if(a.changedTouches[b].identifier==this.dragging_touch_identifier){this.stop_dragging(a,"touchcancel"==a.type);this.ignore_mouse_events_until=(new Date).valueOf()+500;break}};DragElement.prototype.mouseup_event=function(a){a.isLeftClick()&&this.stop_dragging(a,!1)};
DragElement.prototype.stop_dragging=function(a,b){if(this.dragging&&(this.dragging=!1,$(document.body).removeClassName(this.overriden_drag_class||"dragging"),$(document.body).addClassName("not-dragging"),this.options.onenddrag))this.options.onenddrag(this);this.drag_handlers.each(function(a){a.stop()});this.drag_handlers=[];this.dragging_touch_identifier=null;if(this.options.onup)this.options.onup({dragger:this,latest_event:a,cancelling:b})};
DragElement.prototype.click_event=function(a){this.dragged&&a.stop();this.dragged=!1};DragElement.prototype.dragstart_event=function(a){a.preventDefault()};DragElement.prototype.selectstart_event=function(a){"INPUT"!=a.target.tagName&&a.stop()};WindowDragElement=function(a,b){this.element=a;var c=this.startdrag.bind(this),d=b.startdrag||!1;this.dragger=new DragElement(a,jQuery.extend({},b||{},{no_touch:!0,ondrag:this.ondrag.bind(this),onstartdrag:function(){c();d&&d()}}))};
WindowDragElement.prototype.startdrag=function(){this.scroll_anchor_x=window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft;this.scroll_anchor_y=window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop};WindowDragElement.prototype.ondrag=function(a){scrollTo(this.scroll_anchor_x-a.aX,this.scroll_anchor_y-a.aY)};
WindowDragElementAbsolute=function(a,b){this.element=a;this.ondrag_callback=b;this.disabled=!1;this.dragger=new DragElement(a,{ondrag:this.ondrag.bind(this),onstartdrag:this.startdrag.bind(this)})};WindowDragElementAbsolute.prototype.set_disabled=function(a){this.disabled=a};WindowDragElementAbsolute.prototype.startdrag=function(){if(this.disabled)return!0;this.scroll_anchor_x=this.element.offsetLeft;this.scroll_anchor_y=this.element.offsetTop;return!1};
WindowDragElementAbsolute.prototype.ondrag=function(a){var b=this.scroll_anchor_x+a.aX;a=this.scroll_anchor_y+a.aY;var c=getWindowSize(),d=Math.min(100,this.element.offsetWidth),b=Math.max(b,d-this.element.offsetWidth),b=Math.min(b,c.width-d),d=Math.min(100,this.element.offsetHeight);a=Math.max(a,d-this.element.offsetHeight);a=Math.min(a,c.height-d);this.element.setStyle({left:b+"px",top:a+"px"});if(this.ondrag_callback)this.ondrag_callback()};WindowDragElementAbsolute.prototype.destroy=function(){this.dragger.destroy()};
function TrackFocus(){document.focusedElement=null;document.addEventListener&&document.addEventListener("focus",function(a){document.focusedElement=a.target}.bindAsEventListener(this),!0);document.observe("focusin",function(a){document.focusedElement=a.srcElement}.bindAsEventListener(this))}
function FormatError(a,b,c,d,e){a=""+("Error: "+a+"\n");null!=e&&(a+=e);a+="UA: "+window.navigator.userAgent+"\n";a+="URL: "+window.location.href+"\n";e=document.cookie;e=e.replace(/(pass_hash)=[0-9a-f]{40}/,"$1=(removed)");try{a+="Cookies: "+decodeURIComponent(e)+"\n"}catch(m){a+="Cookies (couldn't decode): "+e+"\n"}if("localStorage"in window){e=[];try{for(g in localStorage)e.push(e)}catch(m){e="sample_urls sample_url_fifo tag_data tag_data_version recent_tags tag_data_format".split(" ")}for(var f=
0;f<e.length;++f){var g=e[f];try{if(g in localStorage){var h=localStorage[g],l=h.length;512<h.length&&(h=h.slice(0,512));a+="localStorage."+g+" (size: "+l+"): "+h+"\n"}}catch(m){a+="(ignored errors retrieving localStorage for "+g+": "+m+")\n"}}}d&&d.stack&&(a+="\n"+d.stack+"\n");b&&(a+="File: "+b,null!=c&&(a+=" line "+c+"\n"));return a}var reported_error=!1;
function ReportError(a,b,c,d,e){if(!navigator.userAgent.match(/.*MSIE [67]/)&&!reported_error&&(reported_error=!0,-1==document.cookie.indexOf("reported_error=1"))){var f=new Date;f.setTime(f.getTime()+36E5);document.cookie="reported_error=1; path=/; expires="+f.toGMTString();a=FormatError(d?d.message:a,b,c,d,e);try{new Ajax.Request("/user/error.json",{parameters:{report:a}})}catch(g){alert("Error: "+g)}}}
function LocalStorageDisabled(){if(!("localStorage"in window))return"unsupported";for(var a=!1;;)try{localStorage.x=1;if(1!=localStorage.x)throw"disabled";delete localStorage.x;return null}catch(b){if(a)return-1!=navigator.userAgent.indexOf("Gecko/")&&-1!=b.message.indexOf("Security error")?"ff-disabled":"error";a=!0;try{localStorage.clear()}catch(c){}}}!("URL"in window)&&"webkitURL"in window&&(window.URL=window.webkitURL);
"createObjectURL"in window&&!("URL"in window)&&(window.URL={createObjectURL:function(a){return window.createObjectURL(a)},revokeObjectURL:function(a){window.revokeObjectURL(a)}});-1!=navigator.userAgent.indexOf("AppleWebKit/")&&(document.documentElement.className+=" webkit");var CropDraggable=Class.create();
Object.extend(Object.extend(CropDraggable.prototype,Draggable.prototype),{initialize:function(a,b){this.options=Object.extend({drawMethod:function(){}},b||{});this.handle=this.element=$(a);this.delta=this.currentDelta();this.dragging=!1;this.eventMouseDown=this.initDrag.bindAsEventListener(this);Event.observe(this.handle,"mousedown",this.eventMouseDown);Draggables.register(this)},draw:function(a){var b=Position.cumulativeOffset(this.element),c=this.currentDelta();b[0]-=c[0];b[1]-=c[1];c=[0,1].map(function(c){return a[c]-
b[c]-this.offset[c]}.bind(this));this.options.drawMethod(c)}});var Cropper={};Cropper.Img=Class.create();
Cropper.Img.prototype={initialize:function(a,b){this.options=Object.extend({ratioDim:{x:0,y:0},minWidth:0,minHeight:0,displayOnInit:!1,onEndCrop:Prototype.emptyFunction,captureKeys:!0,onloadCoords:null,maxWidth:0,maxHeight:0},b||{});this.img=$(a);this.clickCoords={x:0,y:0};this.resizing=this.dragging=!1;this.isWebKit=/Konqueror|Safari|KHTML/.test(navigator.userAgent);this.isIE=/MSIE/.test(navigator.userAgent);this.isOpera8=/Opera\s[1-8]/.test(navigator.userAgent);this.ratioY=this.ratioX=0;this.attached=
!1;this.fixedWidth=0<this.options.maxWidth&&this.options.minWidth>=this.options.maxWidth;this.fixedHeight=0<this.options.maxHeight&&this.options.minHeight>=this.options.maxHeight;if("undefined"!=typeof this.img){if(0<this.options.ratioDim.x&&0<this.options.ratioDim.y){var c=this.getGCD(this.options.ratioDim.x,this.options.ratioDim.y);this.ratioX=this.options.ratioDim.x/c;this.ratioY=this.options.ratioDim.y/c}this.subInitialize();if(this.img.complete||this.isWebKit)this.onLoad();else Event.observe(this.img,
"load",this.onLoad.bindAsEventListener(this))}},getGCD:function(a,b){return 0==b?a:this.getGCD(b,a%b)},onLoad:function(){var a=this.img.parentNode,b="";this.isOpera8&&(b=" opera8");this.imgWrap=Builder.node("div",{"class":"imgCrop_wrap"+b});this.north=Builder.node("div",{"class":"imgCrop_overlay imgCrop_north"},[Builder.node("span")]);this.east=Builder.node("div",{"class":"imgCrop_overlay imgCrop_east"},[Builder.node("span")]);this.south=Builder.node("div",{"class":"imgCrop_overlay imgCrop_south"},
[Builder.node("span")]);this.west=Builder.node("div",{"class":"imgCrop_overlay imgCrop_west"},[Builder.node("span")]);this.dragArea=Builder.node("div",{"class":"imgCrop_dragArea"},[this.north,this.east,this.south,this.west]);this.handleN=Builder.node("div",{"class":"imgCrop_handle imgCrop_handleN"});this.handleNE=Builder.node("div",{"class":"imgCrop_handle imgCrop_handleNE"});this.handleE=Builder.node("div",{"class":"imgCrop_handle imgCrop_handleE"});this.handleSE=Builder.node("div",{"class":"imgCrop_handle imgCrop_handleSE"});
this.handleS=Builder.node("div",{"class":"imgCrop_handle imgCrop_handleS"});this.handleSW=Builder.node("div",{"class":"imgCrop_handle imgCrop_handleSW"});this.handleW=Builder.node("div",{"class":"imgCrop_handle imgCrop_handleW"});this.handleNW=Builder.node("div",{"class":"imgCrop_handle imgCrop_handleNW"});this.selArea=Builder.node("div",{"class":"imgCrop_selArea"},[Builder.node("div",{"class":"imgCrop_marqueeHoriz imgCrop_marqueeNorth"},[Builder.node("span")]),Builder.node("div",{"class":"imgCrop_marqueeVert imgCrop_marqueeEast"},
[Builder.node("span")]),Builder.node("div",{"class":"imgCrop_marqueeHoriz imgCrop_marqueeSouth"},[Builder.node("span")]),Builder.node("div",{"class":"imgCrop_marqueeVert imgCrop_marqueeWest"},[Builder.node("span")]),this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW,Builder.node("div",{"class":"imgCrop_clickArea"})]);this.imgWrap.appendChild(this.img);this.imgWrap.appendChild(this.dragArea);this.dragArea.appendChild(this.selArea);this.dragArea.appendChild(Builder.node("div",
{"class":"imgCrop_clickArea"}));a.appendChild(this.imgWrap);this.startDragBind=this.startDrag.bindAsEventListener(this);Event.observe(this.dragArea,"mousedown",this.startDragBind);this.onDragBind=this.onDrag.bindAsEventListener(this);Event.observe(document,"mousemove",this.onDragBind);this.endCropBind=this.endCrop.bindAsEventListener(this);Event.observe(document,"mouseup",this.endCropBind);this.resizeBind=this.startResize.bindAsEventListener(this);this.handles=[this.handleN,this.handleNE,this.handleE,
this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW];this.registerHandles(!0);this.options.captureKeys&&(this.keysBind=this.handleKeys.bindAsEventListener(this),Event.observe(document,"keypress",this.keysBind));new CropDraggable(this.selArea,{drawMethod:this.moveArea.bindAsEventListener(this)});this.setParams()},registerHandles:function(a){for(var b=0;b<this.handles.length;b++){var c=$(this.handles[b]);if(a){var d=!1;if(this.fixedWidth&&this.fixedHeight)d=!0;else if(this.fixedWidth||
this.fixedHeight){var e=c.className.match(/([S|N][E|W])$/),f=c.className.match(/(E|W)$/),g=c.className.match(/(N|S)$/);e?d=!0:this.fixedWidth&&f?d=!0:this.fixedHeight&&g&&(d=!0)}d?c.hide():Event.observe(c,"mousedown",this.resizeBind)}else c.show(),Event.stopObserving(c,"mousedown",this.resizeBind)}},setParams:function(){this.imgW=this.img.width;this.imgH=this.img.height;$(this.north).setStyle({height:0});$(this.east).setStyle({width:0,height:0});$(this.south).setStyle({height:0});$(this.west).setStyle({width:0,
height:0});$(this.imgWrap).setStyle({width:this.imgW+"px",height:this.imgH+"px"});$(this.selArea).hide();var a={x1:0,y1:0,x2:0,y2:0},b=!1;null!=this.options.onloadCoords?(a=this.cloneCoords(this.options.onloadCoords),b=!0):0<this.options.ratioDim.x&&0<this.options.ratioDim.y&&(a.x1=Math.ceil((this.imgW-this.options.ratioDim.x)/2),a.y1=Math.ceil((this.imgH-this.options.ratioDim.y)/2),a.x2=a.x1+this.options.ratioDim.x,a.y2=a.y1+this.options.ratioDim.y,b=!0);this.setAreaCoords(a,!1,!1,1);this.options.displayOnInit&&
b&&(this.selArea.show(),this.drawArea(),this.endCrop());this.attached=!0},remove:function(){this.attached&&(this.attached=!1,this.imgWrap.parentNode.insertBefore(this.img,this.imgWrap),this.imgWrap.parentNode.removeChild(this.imgWrap),Event.stopObserving(this.dragArea,"mousedown",this.startDragBind),Event.stopObserving(document,"mousemove",this.onDragBind),Event.stopObserving(document,"mouseup",this.endCropBind),this.registerHandles(!1),this.options.captureKeys&&Event.stopObserving(document,"keypress",
this.keysBind))},reset:function(){if(this.attached)this.setParams();else this.onLoad();this.endCrop()},handleKeys:function(a){var b=0,c=0;if(!this.dragging&&!a.altKey){switch(a.keyCode){case 37:b=-1;break;case 38:c=-1;break;case 39:b=1;break;case 40:c=1}if(0!=b||0!=c)a.shiftKey&&(b*=10,c*=10),this.moveArea([this.areaCoords.x1+b,this.areaCoords.y1+c]),Event.stop(a)}},calcW:function(){return this.areaCoords.x2-this.areaCoords.x1},calcH:function(){return this.areaCoords.y2-this.areaCoords.y1},moveArea:function(a){this.setAreaCoords({x1:a[0],
y1:a[1],x2:a[0]+this.calcW(),y2:a[1]+this.calcH()},!0,!1);this.drawArea()},cloneCoords:function(a){return{x1:a.x1,y1:a.y1,x2:a.x2,y2:a.y2}},setAreaCoords:function(a,b,c,d,e){if(b)c=a.x2-a.x1,d=a.y2-a.y1,0>a.x1&&(a.x1=0,a.x2=c),0>a.y1&&(a.y1=0,a.y2=d),a.x2>this.imgW&&(a.x2=this.imgW,a.x1=this.imgW-c),a.y2>this.imgH&&(a.y2=this.imgH,a.y1=this.imgH-d);else if(0>a.x1&&(a.x1=0),0>a.y1&&(a.y1=0),a.x2>this.imgW&&(a.x2=this.imgW),a.y2>this.imgH&&(a.y2=this.imgH),null!=d&&(0<this.ratioX?this.applyRatio(a,
{x:this.ratioX,y:this.ratioY},d,e):c&&this.applyRatio(a,{x:1,y:1},d,e),b=[this.options.minWidth,this.options.minHeight],e=[this.options.maxWidth,this.options.maxHeight],0<b[0]||0<b[1]||0<e[0]||0<e[1])){var f={a1:a.x1,a2:a.x2};a={a1:a.y1,a2:a.y2};var g={min:0,max:this.imgW},h={min:0,max:this.imgH};0==b[0]&&0==b[1]||!c||(0<b[0]?b[1]=b[0]:0<b[1]&&(b[0]=b[1]));0==e[0]&&0==e[0]||!c||(0<e[0]&&e[0]<=e[1]?e[1]=e[0]:0<e[1]&&e[1]<=e[0]&&(e[0]=e[1]));0<b[0]&&this.applyDimRestriction(f,b[0],d.x,g,"min");1<b[1]&&
this.applyDimRestriction(a,b[1],d.y,h,"min");0<e[0]&&this.applyDimRestriction(f,e[0],d.x,g,"max");1<e[1]&&this.applyDimRestriction(a,e[1],d.y,h,"max");a={x1:f.a1,y1:a.a1,x2:f.a2,y2:a.a2}}this.areaCoords=a},applyDimRestriction:function(a,b,c,d,e){if("min"==e?a.a2-a.a1<b:a.a2-a.a1>b)1==c?a.a2=a.a1+b:a.a1=a.a2-b,a.a1<d.min?(a.a1=d.min,a.a2=b):a.a2>d.max&&(a.a1=d.max-b,a.a2=d.max)},applyRatio:function(a,b,c,d){"N"==d||"S"==d?(b=this.applyRatioToAxis({a1:a.y1,b1:a.x1,a2:a.y2,b2:a.x2},{a:b.y,b:b.x},{a:c.y,
b:c.x},{min:0,max:this.imgW}),a.x1=b.b1,a.y1=b.a1,a.x2=b.b2,a.y2=b.a2):(b=this.applyRatioToAxis({a1:a.x1,b1:a.y1,a2:a.x2,b2:a.y2},{a:b.x,b:b.y},{a:c.x,b:c.y},{min:0,max:this.imgH}),a.x1=b.a1,a.y1=b.b1,a.x2=b.a2,a.y2=b.b2)},applyRatioToAxis:function(a,b,c,d){a=Object.extend(a,{});var e=Math.floor((a.a2-a.a1)*b.b/b.a),f=null;1==c.b?(e=a.b1+e,e>d.max&&(e=d.max,f=e-a.b1),a.b2=e):(e=a.b2-e,e<d.min&&(e=d.min,f=e+a.b2),a.b1=e);null!=f&&(b=Math.floor(f*b.a/b.b),1==c.a?a.a2=a.a1+b:a.a1=a.a1=a.a2-b);return a},
drawArea:function(){var a=this.calcW(),b=this.calcH(),c=[this.areaCoords.x1+"px",this.areaCoords.y1+"px",a+"px",b+"px",this.areaCoords.x2+"px",this.areaCoords.y2+"px",this.img.width-this.areaCoords.x2+"px",this.img.height-this.areaCoords.y2+"px"],d=this.selArea.style;d.left=c[0];d.top=c[1];d.width=c[2];d.height=c[3];a=Math.ceil((a-6)/2)+"px";b=Math.ceil((b-6)/2)+"px";this.handleN.style.left=a;this.handleE.style.top=b;this.handleS.style.left=a;this.handleW.style.top=b;this.north.style.height=c[1];
b=this.east.style;b.top=c[1];b.height=c[3];b.left=c[4];b.width=c[6];b=this.south.style;b.top=c[5];b.height=c[7];b=this.west.style;b.top=c[1];b.height=c[3];b.width=c[0];this.subDrawArea();this.forceReRender()},forceReRender:function(){if(this.isIE||this.isWebKit){var a=document.createTextNode(" "),b,c,d;if(this.isIE)fixEl=this.selArea;else if(this.isWebKit){fixEl=document.getElementsByClassName("imgCrop_marqueeSouth",this.imgWrap)[0];b=Builder.node("div","");b.style.visibility="hidden";var e=["SE",
"S","SW"];for(d=0;d<e.length;d++)c=document.getElementsByClassName("imgCrop_handle"+e[d],this.selArea)[0],c.childNodes.length&&c.removeChild(c.childNodes[0]),c.appendChild(b)}fixEl.appendChild(a);fixEl.removeChild(a)}},startResize:function(a){this.startCoords=this.cloneCoords(this.areaCoords);this.resizing=!0;this.resizeHandle=Event.element(a).classNames().toString().replace(/([^N|NE|E|SE|S|SW|W|NW])+/,"");Event.stop(a)},startDrag:function(a){this.selArea.show();this.clickCoords=this.getCurPos(a);
this.setAreaCoords({x1:this.clickCoords.x,y1:this.clickCoords.y,x2:this.clickCoords.x,y2:this.clickCoords.y},!1,!1,null);this.dragging=!0;this.onDrag(a);Event.stop(a)},getCurPos:function(a){for(var b=this.imgWrap,c=Position.cumulativeOffset(b);"BODY"!=b.nodeName;)c[1]-=b.scrollTop||0,c[0]-=b.scrollLeft||0,b=b.parentNode;return curPos={x:Event.pointerX(a)-c[0],y:Event.pointerY(a)-c[1]}},onDrag:function(a){if(this.dragging||this.resizing){var b=null,c=this.getCurPos(a),d=this.cloneCoords(this.areaCoords),
e={x:1,y:1};this.dragging?(c.x<this.clickCoords.x&&(e.x=-1),c.y<this.clickCoords.y&&(e.y=-1),this.transformCoords(c.x,this.clickCoords.x,d,"x"),this.transformCoords(c.y,this.clickCoords.y,d,"y")):this.resizing&&(b=this.resizeHandle,b.match(/E/)?(this.transformCoords(c.x,this.startCoords.x1,d,"x"),c.x<this.startCoords.x1&&(e.x=-1)):b.match(/W/)&&(this.transformCoords(c.x,this.startCoords.x2,d,"x"),c.x<this.startCoords.x2&&(e.x=-1)),b.match(/N/)?(this.transformCoords(c.y,this.startCoords.y2,d,"y"),
c.y<this.startCoords.y2&&(e.y=-1)):b.match(/S/)&&(this.transformCoords(c.y,this.startCoords.y1,d,"y"),c.y<this.startCoords.y1&&(e.y=-1)));this.setAreaCoords(d,!1,a.shiftKey,e,b);this.drawArea();Event.stop(a)}},transformCoords:function(a,b,c,d){var e=[a,b];a>b&&e.reverse();c[d+"1"]=e[0];c[d+"2"]=e[1]},endCrop:function(){this.resizing=this.dragging=!1;this.options.onEndCrop(this.areaCoords,{width:this.calcW(),height:this.calcH()})},subInitialize:function(){},subDrawArea:function(){}};
Cropper.ImgWithPreview=Class.create();
Object.extend(Object.extend(Cropper.ImgWithPreview.prototype,Cropper.Img.prototype),{subInitialize:function(){this.hasPreviewImg=!1;"undefined"!=typeof this.options.previewWrap&&(this.previewWrap=$(this.options.previewWrap),this.previewImg=this.img.cloneNode(!1),this.previewImg.id="imgCrop_"+this.previewImg.id,this.previewWrap.hide(),this.hasPreviewImg=this.options.displayOnInit=!0,this.previewWrap.addClassName("imgCrop_previewWrap"),this.options.resizePreview||this.previewWrap.setStyle({width:this.options.minWidth+
"px",height:this.options.minHeight+"px"}),this.previewWrap.appendChild(this.previewImg))},subDrawArea:function(){if(this.hasPreviewImg){var a=this.calcW(),b=this.calcH();if(0==a||0==b)this.previewWrap.hide();else{var c;if(this.options.resizePreview){c=this.options.resizePreview({x:a,y:b});var d=this.previewWrap.style;d.width=c.x+"px";d.height=c.y+"px"}else c={x:this.options.minWidth,y:this.options.minHeight};var d=Math.ceil(this.imgH/b*c.y)+"px",e="-"+Math.ceil(this.areaCoords.x1/(a/c.x))+"px",b=
"-"+Math.ceil(this.areaCoords.y1/(b/c.y))+"px",f=this.previewImg.style;f.width=Math.ceil(this.imgW/a*c.x)+"px";f.height=d;f.left=e;f.top=b;this.previewWrap.show()}}}});DebugWindow=function(){this.shown=!1;this.log_data=[];this.hooks=[];this.counter=0;this.update=this.update.bind(this);this.hashchange_debug=this.hashchange_debug.bind(this);UrlHash.observe("debug",this.hashchange_debug);this.hashchange_debug();this.log("*** Started")};
DebugWindow.prototype.create_container=function(){if(!this.container){var a=document.createElement("DIV"),a=$(a);a.className="debug-box";a.setStyle({position:"fixed",top:"0px",right:"0px",height:"25%",backgroundColor:"#000",fontSize:"100%"});document.body.appendChild(a);this.container=a;this.shown_debug=""}};DebugWindow.prototype.destroy_container=function(){this.container&&(document.body.removeChild(this.container),this.container=null)};
DebugWindow.prototype.log=function(a){window.console&&window.console.log&&console.log(a);++this.counter;this.log_data.push(this.counter+": "+a);10<this.log_data.length&&(this.log_data=this.log_data.slice(1,11));this.shown&&this.update.defer()};DebugWindow.prototype.hashchange_debug=function(){var a=UrlHash.get("debug");null==a&&(a="0");a="1"==a;a!=this.shown&&((this.shown=a)?this.create_container():this.destroy_container(),this.update())};DebugWindow.prototype.add_hook=function(a){this.hooks.push(a)};
DebugWindow.prototype.update=function(){if(this.container){for(var a="",b=0;b<this.hooks.length;++b)a+=(0,this.hooks[b])()+"<br>";a+=this.log_data.join("<br>");a!=this.shown_debug&&(this.shown_debug=a,this.container.update(a))}};NewDebug=function(){var a=new DebugWindow,b=a.log.bind(a);b.handler=a;return b};
History={last_click:-1,checked:[],dragging:!1,init:function(){$("history").observe("mousedown",function(a){a.shiftKey||(History.last_click=-1);History.mouse_is_down();a.stopPropagation();a.preventDefault()},!0);History.update()},add_change:function(a,b,c,d,e){History.checked.push({id:a,ids:d,group_by_type:b,group_by_id:c,user_id:e,on:!1,row:$("r"+a)});$("r"+a).observe("mousedown",function(b){History.mousedown(a,b);!0});$("r"+a).observe("mouseover",function(b){History.mouseover(a,b);!0});$("r"+a).down(".id")&&
$("r"+a).down(".id").observe("click",function(b){History.id_click(a)});$("r"+a).down(".author").observe("click",function(b){History.author_click(a)});$("r"+a).down(".change").observe("click",function(b){History.change_click(a)})},update:function(){for(i=0;i<History.checked.length;++i){var a=History.checked[i].row;History.checked[i].on?a.addClassName("selected"):a.removeClassName("selected")}0<History.count_selected()?($("undo").removeClassName("footer-disabled"),$("redo").removeClassName("footer-disabled")):
($("undo").addClassName("footer-disabled"),$("redo").addClassName("footer-disabled"))},id_click:function(a,b){a=History.get_row_by_id(a);$("search").value=History.checked[a].group_by_type.toLowerCase()+":"+History.checked[a].group_by_id},author_click:function(a,b){a=History.get_row_by_id(a);$("search").value="user:"+History.checked[a].user_id},change_click:function(a,b){a=History.get_row_by_id(a);$("search").value="change:"+History.checked[a].id},count_selected:function(){for(i=ret=0;i<History.checked.length;++i)History.checked[i].on&&
++ret;return ret},get_first_selected_row:function(){for(i=0;i<History.checked.length;++i)if(History.checked[i].on)return i;return null},get_row_by_id:function(a){for(i=0;i<History.checked.length;++i)if(History.checked[i].id==a)return i;return-1},set:function(a,b,c){for(i=a;;){History.checked[i].on=c;if(i==b)break;i+=b>a?1:-1}},doc_mouseup:function(a){History.dragging=!1;document.stopObserving("mouseup",History.doc_mouseup)},mouse_is_down:function(){History.dragging=!0;document.observe("mouseup",History.doc_mouseup)},
mousedown:function(a,b){if(Event.isLeftClick(b)){History.mouse_is_down();var c=History.get_row_by_id(a);if(-1!=c){var d,e;-1!=History.last_click&&b.shiftKey?(d=History.last_click,e=c):(d=e=History.last_click=c,History.checked[c].on=!History.checked[c].on);c=History.checked[d].on;b.ctrlKey||History.set(0,History.checked.length-1,!1);History.set(d,e,c);History.update();b.stopPropagation();b.preventDefault()}}},mouseover:function(a,b){var c=History.get_row_by_id(a);-1!=c&&(-1==History.last_click&&(History.last_click=
c),History.dragging&&(History.set(0,History.checked.length-1,!1),first=History.last_click,this_click=last=c,History.set(first,last,!0),History.update()))},undo:function(a){if(0!=History.count_selected()){var b=[];for(i=0;i<History.checked.length;++i)History.checked[i].on&&(b=b.concat(History.checked[i].ids));a?notice("Reapplying..."):notice("Undoing...");new Ajax.Request("/history/undo.json",{parameters:{id:b.join(","),redo:a?1:0},onComplete:function(b){b=b.responseJSON;if(b.success){var d=b.errors;
0<b.successful&&d.unshift(a?"Changes reapplied.":"Changes undone.");notice(d.join("<br>"))}else notice("Error: "+b.reason)}})}}};
InlineImage={mouse_down:null,zoom_levels:[1,1.5,2,4],get_zoom:function(a){return 0<=a?InlineImage.zoom_levels[a]:1/InlineImage.zoom_levels[-a]},register:function(a,b){var c=$(a);b.html_id=a;c.inline_image=b;b.initted=!1;b.expanded=!1;b.toggled_from=null;b.current=-1;b.zoom_level=0;var d="";if(1<b.images.length)for(var e=0;e<b.images.length;++e){var f=b.html_id+"-"+e,g=b.images[e].description.escapeHTML();""==g&&(g="#"+(e+1));d+="<a href='#' id='"+f+"' class='select-image' onclick='InlineImage.show_image_no(\""+
b.html_id+'", '+e+"); return false;'>"+g+"</a>"}d+="<a href='#' class='select-image' onclick='InlineImage.zoom(\""+b.html_id+"\", +1); return false;'>+</a>";d+="<a href='#' class='select-image' onclick='InlineImage.zoom(\""+b.html_id+"\", -1); return false;'>-</a>";d+="<a href='#' id='"+(b.html_id+"-zoom")+"' class='select-image' onclick='InlineImage.zoom(\""+b.html_id+"\", 0); return false;'>100%</a>";d+="<a href='#' class='select-image' onclick='InlineImage.close(\""+b.html_id+"\"); return false;'>Close</a>";
d+="<a href='/inline/edit/"+b.id+"' class='edit-link'>Image&nbsp;#"+b.id+"</a>";c.down(".expanded-image-ui").innerHTML=d;c.down(".inline-thumb").observe("click",function(a){a.stop();InlineImage.expand(b.html_id)});c.observe("dblclick",function(a){a.stop()});c=c.down(".main-inline-image");1<b.images.length&&c.addClassName("clickable");c.observe("mousedown",function(a){0==a.button&&(b.toggled_from=b.current,InlineImage.show_image_no(b.html_id,(b.current+1)%b.images.length),InlineImage.mouse_down=b,
a.stop())})},init:function(){document.observe("mouseup",function(a){0==a.button&&null!=InlineImage.mouse_down&&(a.stop(),a=InlineImage.mouse_down,InlineImage.mouse_down=null,InlineImage.show_image_no(a.html_id,a.toggled_from),a.toggled_from=null)})},expand:function(a){a=$(a);var b=a.inline_image;b.expanded=!0;if(!b.initted){b.initted=!0;for(var c=b.images,d="",e=0;e<b.images.length;++e)var f=c[e],d=d+("<img src='"+(f.sample_width?f.sample_url:f.file_url)+"' id='"+(b.html_id+"-img-"+e)+"' width=undefined height=undefined style='display: none;'>");
a.down(".main-inline-image").innerHTML=d}a.down(".inline-thumb").hide();InlineImage.show_image_no(b.html_id,0);a.down(".expanded-image").show()},close:function(a){a=$(a);a.inline_image.expanded=!1;a.down(".expanded-image").hide();a.down(".inline-thumb").show()},show_image_no:function(a,b){var c=$(a).inline_image,d=c.images[b],e=InlineImage.get_zoom(c.zoom_level),f;d.sample_width?(f=d.sample_width*e,d=d.sample_height*e):(f=d.width*e,d=d.height*e);f=f.toFixed(0);d=d.toFixed(0);c.current!=b&&(e=$(c.html_id+
"-img-"+c.current))&&e.hide();if(e=$(c.html_id+"-img-"+b))e.width=f,e.height=d,e.show();c.current!=b&&((f=$(c.html_id+"-"+b))&&f.addClassName("selected-image-tab"),(f=$(c.html_id+"-"+c.current))&&f.removeClassName("selected-image-tab"),c.current=b)},zoom:function(a,b){var c=$(a).inline_image;c.zoom_level=0==b?0:c.zoom_level+b;c.zoom_level>InlineImage.zoom_levels.length-1&&(c.zoom_level=InlineImage.zoom_levels.length-1);c.zoom_level<-InlineImage.zoom_levels.length+1&&(c.zoom_level=-InlineImage.zoom_levels.length+
1);var d=c.html_id+"-zoom",e=100*InlineImage.get_zoom(c.zoom_level);$(d).update(e.toFixed(0)+"%");InlineImage.show_image_no(a,c.current)}};
var Note=Class.create({initialize:function(a,b,c){Note.debug&&console.debug("Note#initialize (id=%d)",a);this.id=a;this.is_new=b;this.document_observers=[];this.elements={box:$("note-box-"+this.id),corner:$("note-corner-"+this.id),body:$("note-body-"+this.id),image:$("image")};this.fullsize={left:this.elements.box.offsetLeft,top:this.elements.box.offsetTop,width:this.elements.box.clientWidth,height:this.elements.box.clientHeight};this.old={raw_body:c,formatted_body:this.elements.body.innerHTML};for(p in this.fullsize)this.old[p]=
this.fullsize[p];b?this.elements.box.setOpacity(.2):this.elements.box.setOpacity(.5);b&&""==c&&(this.bodyfit=!0,this.elements.body.style.height="100px");this.elements.box.observe("mousedown",this.dragStart.bindAsEventListener(this));this.elements.box.observe("mouseout",this.bodyHideTimer.bindAsEventListener(this));this.elements.box.observe("mouseover",this.bodyShow.bindAsEventListener(this));this.elements.corner.observe("mousedown",this.resizeStart.bindAsEventListener(this));this.elements.body.observe("mouseover",
this.bodyShow.bindAsEventListener(this));this.elements.body.observe("mouseout",this.bodyHideTimer.bindAsEventListener(this));this.elements.body.observe("click",this.showEditBox.bindAsEventListener(this));this.adjustScale();if(Note.drag_created){var d=this,e,f=!1;B=function(a){f?e():(f=!0,d._resize(a.pageX,a.pageY))};e=function(){jQuery(document).unbind("mousemove",B)};jQuery(document).bind("mousemove",B)}},textValue:function(){Note.debug&&console.debug("Note#textValue (id=%d)",this.id);return this.old.raw_body.strip()},
hideEditBox:function(a){Note.debug&&console.debug("Note#hideEditBox (id=%d)",this.id);a=$("edit-box");null!=a&&(a=a.noteid,$("edit-box").stopObserving(),$("note-save-"+a).stopObserving(),$("note-cancel-"+a).stopObserving(),$("note-remove-"+a).stopObserving(),$("note-history-"+a).stopObserving(),$("edit-box").remove())},showEditBox:function(a){Note.debug&&console.debug("Note#showEditBox (id=%d)",this.id);this.hideEditBox(a);a=Note.getInsertionPosition();a=""+('<div id="edit-box" style="top: '+a[0]+
"px; left: "+a[1]+'px; position: absolute; visibility: visible; z-index: 100; background: white; border: 1px solid black; padding: 12px;">')+'<form onsubmit="return false;" style="padding: 0; margin: 0;">';a+='<textarea rows="7" id="edit-box-text" style="width: 350px; margin: 2px 2px 12px 2px;">'+this.textValue()+"</textarea>";a+='<input type="submit" value="Save" name="save" id="note-save-'+this.id+'">';a+='<input type="submit" value="Cancel" name="cancel" id="note-cancel-'+this.id+'">';a+='<input type="submit" value="Remove" name="remove" id="note-remove-'+
this.id+'">';a+='<input type="submit" value="History" name="history" id="note-history-'+this.id+'">';a+='<br><span style="color:gray;font-size:80%;">Markdown is used for formatting. <a href="/help/notes#markdown">More info</a></form></div>';$("note-container").insert({bottom:a});$("edit-box").noteid=this.id;$("edit-box").observe("mousedown",this.editDragStart.bindAsEventListener(this));$("note-save-"+this.id).observe("click",this.save.bindAsEventListener(this));$("note-cancel-"+this.id).observe("click",
this.cancel.bindAsEventListener(this));$("note-remove-"+this.id).observe("click",this.remove.bindAsEventListener(this));$("note-history-"+this.id).observe("click",this.history.bindAsEventListener(this));$("edit-box-text").focus();Note.active_note=this;Note.bindEditShortcuts()},bodyShow:function(a){Note.debug&&console.debug("Note#bodyShow (id=%d)",this.id);if(!this.dragging&&(this.hideTimer&&(clearTimeout(this.hideTimer),this.hideTimer=null),Note.noteShowingBody!=this)){Note.noteShowingBody&&Note.noteShowingBody.bodyHide();
Note.noteShowingBody=this;if(9<=Note.zindex)for(var b=Note.zindex=0;b<Note.all.length;++b)Note.all[b].elements.box.style.zIndex=0;this.elements.box.style.zIndex=++Note.zindex;this.elements.body.style.zIndex=10;this.elements.body.style.top="0px";this.elements.body.style.left="0px";b=document.documentElement.scrollWidth;this.elements.body.style.visibility="hidden";this.elements.body.style.display="block";if(!this.bodyfit){this.elements.body.style.height="auto";this.elements.body.style.minWidth="140px";
var c,d,e,f,g;a=this.elements.body.offsetWidth;c=this.elements.body.offsetHeight;if(1.6180339887>a/c){d=140;e=400;do g=a,f=(d+e)/2,this.elements.body.style.minWidth=f+"px",a=this.elements.body.offsetWidth,c=this.elements.body.offsetHeight,1.6180339887>a/c?d=f:e=f;while(d<e&&a>g)}else if(this.elements.body.scrollWidth<=this.elements.body.clientWidth){d=20;e=a;do f=(d+e)/2,this.elements.body.style.minWidth=f+"px",this.elements.body.offsetHeight>c?d=f:e=f;while(4<e-d);this.elements.body.offsetHeight>
c&&(this.elements.body.style.minWidth=e+"px")}Prototype.Browser.IE&&(35>this.elements.body.offsetHeight&&(this.elements.body.style.minHeight="35px"),47>this.elements.body.offsetWidth&&(this.elements.body.style.minWidth="47px"));this.bodyfit=!0}this.elements.body.style.top=this.elements.box.offsetTop+this.elements.box.clientHeight+5+"px";c=0;a=this.elements.box;do c+=a.offsetLeft;while(a=a.offsetParent);c+=this.elements.body.offsetWidth+10-b;this.elements.body.style.left=0<c?this.elements.box.offsetLeft-
c+"px":this.elements.box.offsetLeft+"px";this.elements.body.style.visibility="visible"}},bodyHideTimer:function(a){Note.debug&&console.debug("Note#bodyHideTimer (id=%d)",this.id);this.hideTimer=setTimeout(this.bodyHide.bindAsEventListener(this),250)},bodyHide:function(a){Note.debug&&console.debug("Note#bodyHide (id=%d)",this.id);this.elements.body.hide();Note.noteShowingBody==this&&(Note.noteShowingBody=null)},addDocumentObserver:function(a,b){document.observe(a,b);this.document_observers.push([a,
b])},clearDocumentObservers:function(a,b){for(var c=0;c<this.document_observers.length;++c){var d=this.document_observers[c];document.stopObserving(d[0],d[1])}this.document_observers=[]},dragStart:function(a){Note.debug&&console.debug("Note#dragStart (id=%d)",this.id);this.addDocumentObserver("mousemove",this.drag.bindAsEventListener(this));this.addDocumentObserver("mouseup",this.dragStop.bindAsEventListener(this));this.addDocumentObserver("selectstart",function(){return!1});this.cursorStartX=a.pointerX();
this.cursorStartY=a.pointerY();this.boxStartX=this.elements.box.offsetLeft;this.boxStartY=this.elements.box.offsetTop;this.boundsX=new ClipRange(5,this.elements.image.clientWidth-this.elements.box.clientWidth-5);this.boundsY=new ClipRange(5,this.elements.image.clientHeight-this.elements.box.clientHeight-5);this.dragging=!0;this.bodyHide()},dragStop:function(a){Note.debug&&console.debug("Note#dragStop (id=%d)",this.id);this.clearDocumentObservers();this.boundsY=this.boundsX=this.boxStartY=this.boxStartX=
this.cursorStartY=this.cursorStartX=null;this.dragging=!1;this.bodyShow()},ratio:function(){return this.elements.image.width/this.elements.image.getAttribute("large_width")},adjustScale:function(){Note.debug&&console.debug("Note#adjustScale (id=%d)",this.id);var a=this.ratio();for(p in this.fullsize)this.elements.box.style[p]=this.fullsize[p]*a+"px"},drag:function(a){var b=this.boxStartX+a.pointerX()-this.cursorStartX,c=this.boxStartY+a.pointerY()-this.cursorStartY,b=this.boundsX.clip(b),c=this.boundsY.clip(c);
this.elements.box.style.left=b+"px";this.elements.box.style.top=c+"px";var d=this.ratio();this.fullsize.left=b/d;this.fullsize.top=c/d;a.stop()},editDragStart:function(a){Note.debug&&console.debug("Note#editDragStart (id=%d)",this.id);var b=a.element().nodeName;if("FORM"==b||"DIV"==b)this.addDocumentObserver("mousemove",this.editDrag.bindAsEventListener(this)),this.addDocumentObserver("mouseup",this.editDragStop.bindAsEventListener(this)),this.addDocumentObserver("selectstart",function(){return!1}),
this.elements.editBox=$("edit-box"),this.cursorStartX=a.pointerX(),this.cursorStartY=a.pointerY(),this.editStartX=this.elements.editBox.offsetLeft,this.editStartY=this.elements.editBox.offsetTop,this.dragging=!0},editDragStop:function(a){Note.debug&&console.debug("Note#editDragStop (id=%d)",this.id);this.clearDocumentObservers();this.editStartY=this.editStartX=this.cursorStartY=this.cursorStartX=null;this.dragging=!1},editDrag:function(a){var b=this.editStartX+a.pointerX()-this.cursorStartX,c=this.editStartY+
a.pointerY()-this.cursorStartY;this.elements.editBox.style.left=b+"px";this.elements.editBox.style.top=c+"px";a.stop()},_resize:function(a,b){Note.debug&&console.debug("Note#_resize (id=%d)",this.id);this.cursorStartX=a;this.cursorStartY=b;this.boxStartWidth=this.elements.box.clientWidth;this.boxStartHeight=this.elements.box.clientHeight;this.boxStartX=this.elements.box.offsetLeft;this.boxStartY=this.elements.box.offsetTop;this.boundsX=new ClipRange(10,this.elements.image.clientWidth-this.boxStartX-
5);this.boundsY=new ClipRange(10,this.elements.image.clientHeight-this.boxStartY-5);this.dragging=!0;this.clearDocumentObservers();this.addDocumentObserver("mousemove",this.resize.bindAsEventListener(this));this.addDocumentObserver("mouseup",this.resizeStop.bindAsEventListener(this));this.bodyHide()},resizeStart:function(a){a.stop();this._resize(a.pointerX(),a.pointerY())},resizeStop:function(a){Note.debug&&console.debug("Note#resizeStop (id=%d)",this.id);this.clearDocumentObservers();this.boundsY=
this.boundsX=this.boxStartY=this.boxStartX=this.boxStartHeight=this.boxStartWidth=this.boxCursorStartY=this.boxCursorStartX=null;this.dragging=!1;a.stop();Note.drag_created&&(this.old.width=this.fullsize.width,this.old.height=this.fullsize.height,Note.drag_created=!1,this.showEditBox({}))},resize:function(a){Note.debug&&console.debug("Note#resize (id=%d)",this.id);var b=this.boxStartWidth+a.pointerX()-this.cursorStartX,c=this.boxStartHeight+a.pointerY()-this.cursorStartY,b=this.boundsX.clip(b),c=
this.boundsY.clip(c);this.elements.box.style.width=b+"px";this.elements.box.style.height=c+"px";var d=this.ratio();this.fullsize.width=b/d;this.fullsize.height=c/d;a.stop()},save:function(a){Note.debug&&console.debug("Note#save (id=%d)",this.id);for(p in this.fullsize)this.old[p]=this.fullsize[p];this.old.raw_body=$("edit-box-text").value;this.old.formatted_body=this.textValue();this.elements.body.update(this.textValue());this.hideEditBox(a);this.bodyHide();this.bodyfit=!1;var b={id:this.id,"note[x]":this.old.left,
"note[y]":this.old.top,"note[width]":this.old.width,"note[height]":this.old.height,"note[body]":this.old.raw_body};this.is_new&&(b["note[post_id]"]=Note.post_id);notice("Saving note...");new Ajax.Request("/note/update.json",{parameters:b,onComplete:function(a){a=a.responseJSON;if(a.success){notice("Note saved");var b=Note.find(a.old_id);0>a.old_id&&(b.is_new=!1,b.id=a.new_id,b.elements.box.id="note-box-"+b.id,b.elements.body.id="note-body-"+b.id,b.elements.corner.id="note-corner-"+b.id);b.elements.body.innerHTML=
a.formatted_body;b.elements.box.setOpacity(.5);b.elements.box.removeClassName("unsaved")}else notice("Error: "+a.reason),b.elements.box.addClassName("unsaved")}});a.stop&&a.stop();Note.unbindEditShortcuts()},cancel:function(a){Note.debug&&console.debug("Note#cancel (id=%d)",this.id);this.hideEditBox(a);this.bodyHide();var b=this.ratio();for(p in this.fullsize)this.fullsize[p]=this.old[p],this.elements.box.style[p]=this.fullsize[p]*b+"px";this.elements.body.innerHTML=this.old.formatted_body;a.stop&&
a.stop();Note.unbindEditShortcuts()},removeCleanup:function(){Note.debug&&console.debug("Note#removeCleanup (id=%d)",this.id);this.elements.box.remove();this.elements.body.remove();var a=[];for(i=0;i<Note.all.length;++i)Note.all[i].id!=this.id&&a.push(Note.all[i]);Note.all=a;Note.updateNoteCount()},remove:function(a){Note.debug&&console.debug("Note#remove (id=%d)",this.id);this.hideEditBox(a);this.bodyHide();this_note=this;this.is_new?(this.removeCleanup(),notice("Note removed")):(notice("Removing note..."),
new Ajax.Request("/note/update.json",{parameters:{id:this.id,"note[is_active]":"0"},onComplete:function(a){a=a.responseJSON;a.success?(notice("Note removed"),this_note.removeCleanup()):notice("Error: "+a.reason)}}));a.stop()},history:function(a){Note.debug&&console.debug("Note#history (id=%d)",this.id);this.hideEditBox(a);this.is_new?notice("This note has no history"):location.href="/history?search=notes:"+this.id;a.stop()}});
Object.extend(Note,{zindex:0,counter:-1,all:[],display:!0,debug:!1,drag_created:!1,active_note:null,create_click_x:0,create_click_y:0,ctrlEnterSave:function(a){13==a.keyCode&&a.ctrlKey&&Note.active_note.save({})},escapeCancel:function(a){27==a.keyCode&&Note.active_note.cancel({})},bindEditShortcuts:function(){jQuery(document).bind("keydown",Note.ctrlEnterSave);jQuery(document).bind("keydown",Note.escapeCancel)},unbindEditShortcuts:function(){jQuery(document).unbind("keydown",Note.ctrlEnterSave);jQuery(document).unbind("keydown",
Note.escapeCancel)},show:function(){Note.debug&&console.debug("Note.show");$("note-container").show()},hide:function(){Note.debug&&console.debug("Note.hide");$("note-container").hide()},find:function(a){Note.debug&&console.debug("Note.find");for(var b=0;b<Note.all.size();++b)if(Note.all[b].id==a)return Note.all[b];return null},toggle:function(){Note.debug&&console.debug("Note.toggle");Note.display?(Note.hide(),Note.display=!1):(Note.show(),Note.display=!0)},updateNoteCount:function(){Note.debug&&
console.debug("Note.updateNoteCount");if(0<Note.all.length){var a;a=1==Note.all.length?"note":"notes";$("note-count").innerHTML='This post has <a href="/note/history?post_id='+Note.post_id+'">'+Note.all.length+" "+a+"</a>"}else $("note-count").innerHTML=""},dragCreate:function(a){Note.debug&&console.debug("Note.toggleCreateEv");Note.drag_created=!0;Note.create_click_x=a.pageX;Note.create_click_y=a.pageY;Note.create()},create:function(){Note.debug&&console.debug("Note.create");Note.show();var a=Note.getInsertionPosition(),
b=a[1],c=this.drag_created?"10":"150",d="note-box-"+Note.counter,a=""+('<div class="note-box unsaved" style="width: '+c+"px; height: "+c+"px; ")+("top: "+a[0]+"px; "),a=a+("left: "+b+'px;" ')+('id="'+d+'">'),a=a+('<div class="note-corner" id="note-corner-'+Note.counter+'"></div>'),a=a+"</div>",a=a+('<div class="note-body" title="Click to edit" id="note-body-'+Note.counter+'"></div>');$("note-container").insert({bottom:a});b=new Note(Note.counter,!0,"");Note.all.push(b);--Note.counter},getInsertionPosition:function(){Note.debug&&
console.debug("Note.getInsertionPosition");if(Note.drag_created){var a=$("image").width,b=parseInt(jQuery("#image").attr("large_width"))/a,c=jQuery("#image").offset(),d=Note.create_click_x-c.left,c=Note.create_click_y-c.top,e=Math.ceil(20/b),d=d*b-10,c=c*b-10;d<e?d=e:d>a*b&&(d=a*b-e);a=parseInt(jQuery("#image").attr("large_height"));c<e?c=e:c>a*b&&(c=a*b-e);return[c,d]}b=$("image").cumulativeScrollOffset()[0];e=$("image").cumulativeScrollOffset()[1];d=$("image").positionedOffset()[0];a=$("image").positionedOffset()[1];
$("image");c=a+$("image").height;e=e>a?e:a+20;e>c&&(e=a+20);return[e,b>d?b:d]},toggleCreateNotice:function(){var a=jQuery("#note_create_notice");a.is(":visible")?a.hide():a.fadeIn(200)}});
Pool={pools:new Hash,register:function(a){Pool.pools.set(a.id,a)},register_pools:function(a){null!=a&&a.each(function(a){Pool.register(a)})},register_pool_posts:function(a,b){a.each(function(a){var b=Post.posts.get(a.post_id);b&&(b.pool_posts||(b.pool_posts=new Hash),b.pool_posts.set(a.pool_id,a))})},can_edit_pool:function(a){return User.is_member_or_higher()?a.is_public||a.user_id==User.get_current_user_id():!1},add_post:function(a,b){notice("Adding to pool...");new Ajax.Request("/pool/add_post.json",
{parameters:{post_id:a,pool_id:b},onComplete:function(a){a=a.responseJSON;a.success?notice("Post added to pool"):notice("Error: "+a.reason)}})},remove_post:function(a,b){Post.make_request("/pool/remove_post.json",{post_id:a,pool_id:b},function(){notice("Post removed from pool");$("p"+a)&&$("p"+a).addClassName("deleted");$("pool"+b)&&$("pool"+b).remove()})},transfer_post:function(a,b,c,d){Post.update_batch([{id:a,tags:"-pool:"+c,old_tags:""},{id:b,tags:"pool:"+c+":"+d,old_tags:""}],function(){notice("Pool post transferred to parent");
document.location.reload()})},detach_post:function(a,b,c){Post.update_batch([{id:a,tags:"-pool:"+b,old_tags:""}],function(){notice("Post detached");if(c){var d=$("pool-detach-"+b+"-"+a);d&&d.remove()}else $("pool"+b)&&$("pool"+b).remove()})},post_pretty_sequence:function(a){return a.match(/^[0-9]+.*/)?"#"+a:'"'+a+'"'},change_sequence:function(a,b,c){new_sequence=prompt("Please enter the new page number:",c);null!=new_sequence&&(-1!=new_sequence.indexOf(" ")?notice("Invalid page number"):Post.update_batch([{id:a,
tags:"pool:"+b+":"+new_sequence,old_tags:""}],function(){notice("Post updated");var a=$("pool-seq-"+b);Object.isUndefined(a.innerText)?a.textContent=Pool.post_pretty_sequence(new_sequence):a.innerText=Pool.post_pretty_sequence(new_sequence)}))}};
var create_drag_box=function(a){var b=function(b,d){var e=$(document.createElement("div"));e.style.position="absolute";e.className="frame-box-handle "+b;e.frame_drag_cursor=b;e.style.pointerEvents="all";a.appendChild(e);for(s in d)e.style[s]=d[s];return e};b("n-resize",{top:"-5px",width:"100%",height:"10px"});b("s-resize",{bottom:"-5px",width:"100%",height:"10px"});b("w-resize",{left:"-5px",height:"100%",width:"10px"});b("e-resize",{right:"-5px",height:"100%",width:"10px"});b("nw-resize",{top:"-5px",
left:"-5px",height:"10px",width:"10px"});b("ne-resize",{top:"-5px",right:"-5px",height:"10px",width:"10px"});b("sw-resize",{bottom:"-5px",left:"-5px",height:"10px",width:"10px"});b("se-resize",{bottom:"-5px",right:"-5px",height:"10px",width:"10px"})},apply_drag=function(a,b,c,d,e){var f={move:{left:1,top:1,bottom:1,right:1},"n-resize":{top:1},"s-resize":{bottom:1},"w-resize":{left:1},"e-resize":{right:1},"nw-resize":{top:1,left:1},"ne-resize":{top:1,right:1},"sw-resize":{bottom:1,left:1},"se-resize":{bottom:1,
right:1}}[a];e={left:e.left,top:e.top,width:e.width,height:e.height};var g=e.left+e.width,h=e.top+e.height;"move"==a&&(b=clamp(b,-e.left,d.width-g),c=clamp(c,-e.top,d.height-h));null!=f.top&&(e.top+=c*f.top);null!=f.left&&(e.left+=b*f.left);null!=f.right&&(g+=b*f.right);null!=f.bottom&&(h+=c*f.bottom);"move"!=a&&(null!=f.left&&(e.left=clamp(e.left,0,g-1)),null!=f.top&&(e.top=clamp(e.top,0,h-1)),null!=f.bottom&&(h=clamp(h,e.top+1,d.height)),null!=f.right&&(g=clamp(g,e.left+1,d.width)));e.width=g-e.left;
e.height=h-e.top;return e},frame_dimensions_to_image=function(a,b,c){a={top:a.source_top,left:a.source_left,width:a.source_width,height:a.source_height};a.left*=b.width/c.width;a.top*=b.height/c.height;a.width*=b.width/c.width;a.height*=b.height/c.height;a.top=Math.round(a.top);a.left=Math.round(a.left);a.width=Math.round(a.width);a.height=Math.round(a.height);return a},frame_dimensions_from_image=function(a,b,c){a={source_top:a.top,source_left:a.left,source_width:a.width,source_height:a.height};
a.source_top/=b.height/c.height;a.source_left/=b.width/c.width;a.source_height/=b.height/c.height;a.source_width/=b.width/c.width;a.source_top=Math.round(a.source_top);a.source_left=Math.round(a.source_left);a.source_width=Math.round(a.source_width);a.source_height=Math.round(a.source_height);return a};
FrameEditor=function(a,b,c,d){this.container=a;this.popup_container=c;this.image_container=b;this.options=d;this.show_corner_drag=!0;this.image_frames=[];this.open_handlers=[];a=[".frame-editor-nw",".frame-editor-ne",".frame-editor-sw",".frame-editor-se"];this.corner_draggers=[];for(b=0;b<a.length;++b)c=a[b],d=this.popup_container.down(c),c=new CornerDragger(d,c,{onUpdate:function(){this.update_frame_in_list(this.editing_frame);this.update_image_frame(this.editing_frame)}.bind(this)}),this.corner_draggers.push(c);
d=$(document.createElement("div"));d.style.position="absolute";d.style.left="0";d.style.top="0";d.className="frame-editor-main-frame";this.image_container.appendChild(d);this.main_frame=d;this.main_frame.hide();this.container.down(".frame-editor-add").on("click",function(a){a.stop();this.add_frame()}.bindAsEventListener(this));this.container.on("click",".frame-label",function(a,b){a.stop();var c=b.up(".frame-row").frame_idx;this.focus(c)}.bind(this));this.container.on("click",".frame-delete",function(a,
b){a.stop();var c=b.up(".frame-row").frame_idx;this.delete_frame(c)}.bind(this));this.container.on("click",".frame-up",function(a,b){a.stop();var c=b.up(".frame-row").frame_idx;this.move_frame(c,c-1)}.bind(this));this.container.on("click",".frame-down",function(a,b){a.stop();var c=b.up(".frame-row").frame_idx;this.move_frame(c,c+1)}.bind(this));this.container.down("table").on("change",function(a){this.form_data_changed()}.bind(this))};
FrameEditor.prototype.move_frame=function(a,b){var c=Post.posts.get(this.post_id);b=Math.max(b,0);b=Math.min(b,c.frames_pending.length-1);if(a!=b){var d=c.frames_pending[a];c.frames_pending.splice(a,1);c.frames_pending.splice(b,0,d);this.repopulate_table();c=this.editing_frame==a?b:this.editing_frame;this.editing_frame=null;this.focus(c)}};FrameEditor.prototype.form_data_changed=function(){for(var a=Post.posts.get(this.post_id),b=0;b<a.frames_pending.length;++b)this.update_frame_from_list(b);this.update()};
FrameEditor.prototype.set_drag_to_create=function(a){this.drag_to_create=a};
FrameEditor.prototype.update_show_corner_drag=function(){var a=null!=this.post_id&&null!=this.editing_frame&&this.show_corner_drag;Prototype.Browser.WebKit?(a?(this.popup_container.style.opacity=1,this.popup_container.style.pointerEvents="",this.popup_container.style.position="static"):(this.popup_container.style.opacity=.001,this.popup_container.style.pointerEvents="none",this.popup_container.style.position="absolute",this.popup_container.style.top="0px",this.popup_container.style.right="0px"),this.popup_container.show()):
this.popup_container.show(a);for(a=0;a<this.corner_draggers.length;++a)this.corner_draggers[a].update()};FrameEditor.prototype.set_show_corner_drag=function(a){this.show_corner_drag=a;this.update_show_corner_drag()};
FrameEditor.prototype.set_image_dimensions=function(a,b){var c=this.editing_frame,d=this.post_id;this.close();this.image_dimensions={width:a,height:b};this.main_frame.style.width=this.image_dimensions.width+"px";this.main_frame.style.height=this.image_dimensions.height+"px";null!=d&&(this.open(d),this.focus(c))};
var elementArrayFromPoint=function(a,b,c){for(c=[];;){var d=document.elementFromPoint(a,b);if(d==this.main_frame||d==document.documentElement)break;d.original_display=d.style.display;d.style.display="none";c.push(d)}c.each(function(a){a.style.display=a.original_display;a.original_display=null});return c};FrameEditor.prototype.is_opened=function(){return null!=this.post_id};
FrameEditor.prototype.open=function(a){if(null==this.image_dimensions)throw"Must call set_image_dimensions before open";if(null==this.post_id){this.post_id=a;this.dragging_item=this.editing_frame=null;this.container.show();this.main_frame.show();this.update_show_corner_drag();a=Post.posts.get(this.post_id);for(var b=0;b<this.corner_draggers.length;++b)this.corner_draggers[b].set_post_id(this.post_id);this.open_handlers.push(document.on("keydown",function(a){a.keyCode==Event.KEY_ESC&&this.discard()}.bindAsEventListener(this)));
this.original_frames=Object.toJSON(a.frames_pending);this.repopulate_table();this.create_dragger();0<a.frames_pending.length&&this.focus(0);this.update()}};
FrameEditor.prototype.create_dragger=function(){this.dragger&&this.dragger.destroy();this.dragger=new DragElement(this.main_frame,{ondown:function(a){var b=Post.posts.get(this.post_id);this.image_frames.each(function(a){a.style.pointerEvents="all"});var c=elementArrayFromPoint(a.x,a.y,this.main_frame);this.image_frames.each(function(a){a.style.pointerEvents="none"});var d=null;c.each(function(a){null==d&&a.hasClassName("frame-box-handle")&&(d=a)}.bind(this));null==d&&c.each(function(a){a.hasClassName("frame-editor-frame-box")||
(a=a.up(".frame-editor-frame-box"));this.image_frames.indexOf(a)==this.editing_frame&&(d=a)}.bind(this));null==d&&(d=c[0]);c=d;c.hasClassName("frame-editor-frame-box")||(c=c.up(".frame-editor-frame-box"));if(null==c){if(!this.drag_to_create)return;this.dragging_new=!0}else this.dragging_new=!1;d.hasClassName("frame-box-handle")?this.dragging_mode=d.frame_drag_cursor:this.dragging_mode="move";c&&c.hasClassName("frame-editor-frame-box")&&(this.dragging_idx=this.image_frames.indexOf(c),this.dragging_anchor=
frame_dimensions_to_image(b.frames_pending[this.dragging_idx],this.image_dimensions,b));this.focus(this.dragging_idx);this.dragger.overriden_drag_class="move"==this.dragging_mode?null:this.dragging_mode;this.dragger.options.snap_pixels=this.dragging_new?10:0;a.latest_event.stopPropagation()}.bind(this),onup:function(a){this.dragging_anchor=this.dragging_idx=null}.bind(this),ondrag:function(a){var b=Post.posts.get(this.post_id);if(this.dragging_new){if(0<a.aX&&0<a.aY)this.dragging_mode="se-resize";
else if(0<a.aX&&0>a.aY)this.dragging_mode="ne-resize";else if(0>a.aX&&0<a.aY)this.dragging_mode="sw-resize";else if(0>a.aX&&0>a.aY)this.dragging_mode="nw-resize";else return;this.dragging_new=!1;var c=this.main_frame.cumulativeOffset();this.dragging_anchor=c={left:a.dragger.anchor_x-c.left,top:a.dragger.anchor_y-c.top,height:0,width:0};c=frame_dimensions_from_image(c,this.image_dimensions,b);this.dragging_idx=this.add_frame(c);b.frames_pending[this.editing_frame]=c}null!=this.dragging_idx&&(c=apply_drag(this.dragging_mode,
a.aX,a.aY,this.image_dimensions,this.dragging_anchor),c=frame_dimensions_from_image(c,this.image_dimensions,b),b.frames_pending[this.editing_frame]=c,this.update_frame_in_list(this.editing_frame),this.update_image_frame(this.editing_frame))}.bind(this)})};
FrameEditor.prototype.repopulate_table=function(){for(var a=Post.posts.get(this.post_id),b=this.container.down(".frame-list").down("TBODY");b.firstChild;)b.removeChild(b.firstChild);this.image_frames.each(function(a){a.parentNode.removeChild(a)}.bind(this));this.image_frames=[];for(b=0;b<a.frames_pending.length;++b)this.add_frame_to_list(b),this.create_image_frame(),this.update_image_frame(b)};
FrameEditor.prototype.update=function(){this.update_show_corner_drag();if(null!=this.image_dimensions){var a=Post.posts.get(this.post_id);if(null!=a)for(var b=0;b<a.frames_pending.length;++b)this.update_image_frame(b)}};FrameEditor.prototype.discard=function(){if(null!=this.post_id){var a=this.original_frames,b=this.post_id;this.close();Post.posts.get(b).frames_pending=a.evalJSON()}};
FrameEditor.prototype.get_current_frames_spec=function(){var a=[];Post.posts.get(this.post_id).frames_pending.each(function(b){a.push(b.source_left+"x"+b.source_top+","+b.source_width+"x"+b.source_height)}.bind(this));return a.join(";")};FrameEditor.prototype.changed=function(){var a=Post.posts.get(this.post_id);return this.get_current_frames_spec()!=a.frames_pending_string};
FrameEditor.prototype.save=function(a){if(null==this.post_id)a&&a();else{var b=this.post_id,c=Post.posts.get(b),d=this.get_current_frames_spec();d==c.frames_pending_string?a&&a():Post.update_batch([{id:b,frames_pending_string:d}],function(c){this.post_id==b&&(c=Post.posts.get(b),this.original_frames=Object.toJSON(c.frames_pending),this.update());a&&a()}.bind(this))}};
FrameEditor.prototype.create_image_frame=function(){var a=$(document.createElement("div"));a.className="frame-editor-frame-box";a.style.pointerEvents="none";this.main_frame.appendChild(a);this.image_frames.push(a);create_drag_box(a)};
FrameEditor.prototype.update_image_frame=function(a){var b=Post.posts.get(this.post_id),c=b.frames_pending[a];if(a==this.editing_frame)for(var d=0;d<this.corner_draggers.length;++d)this.corner_draggers[d].update();b=frame_dimensions_to_image(c,this.image_dimensions,b);c=this.image_frames[a];c.style.left=b.left+"px";c.style.top=b.top+"px";c.style.width=b.width+"px";c.style.height=b.height+"px";a==this.editing_frame?c.addClassName("focused-frame-box"):c.removeClassName("focused-frame-box")};
FrameEditor.prototype.add_frame_to_list=function(a){var b=this.container.down(".frame-list").down("TBODY"),c=$(document.createElement("TR"));c.className="frame-row frame-"+a;c.frame_idx=a;b.appendChild(c);b="<td><span class='frame-label'>Frame "+a+"</span></td><td><input class='frame-left frame-dims' size=4></td><td><input class='frame-top frame-dims' size=4></td>";b+="<td><input class='frame-width frame-dims' size=4></td>";b+="<td><input class='frame-height frame-dims' size=4></td>";b+="<td><a class='frame-delete frame-button-box' href='#'>X</a></td>";
b+="<td><a class='frame-up frame-button-box' href='#'>\u21e1</a></td>";b+="<td><a class='frame-down frame-button-box' href='#'>\u21e3</a></td>";c.innerHTML=b;this.update_frame_in_list(a)};
FrameEditor.prototype.update_frame_in_list=function(a){var b=Post.posts.get(this.post_id).frames_pending[a];a=this.container.down(".frame-list").down("TBODY").down(".frame-"+a);a.down(".frame-left").value=b.source_left;a.down(".frame-top").value=b.source_top;a.down(".frame-width").value=b.source_width;a.down(".frame-height").value=b.source_height};
FrameEditor.prototype.update_frame_from_list=function(a){var b=Post.posts.get(this.post_id).frames_pending[a];a=this.container.down(".frame-list").down("TBODY").down(".frame-"+a);b.source_left=a.down(".frame-left").value;b.source_top=a.down(".frame-top").value;b.source_width=a.down(".frame-width").value;b.source_height=a.down(".frame-height").value};
FrameEditor.prototype.add_frame=function(a){var b=Post.posts.get(this.post_id);null==a&&(a={source_top:1*b.height/4,source_left:1*b.width/4,source_width:b.width/2,source_height:b.height/2});b.frames_pending.push(a);this.add_frame_to_list(b.frames_pending.length-1);this.create_image_frame();this.update_image_frame(b.frames_pending.length-1);this.focus(b.frames_pending.length-1);return b.frames_pending.length-1};
FrameEditor.prototype.delete_frame=function(a){var b=Post.posts.get(this.post_id),c=null;this.editing_frame==a&&(c=this.editing_frame,this.focus(null),a==b.frames_pending.length-1&&--c,0>c&&(c=null));b.frames_pending.splice(a,1);this.repopulate_table();this.focus(c)};
FrameEditor.prototype.focus=function(a){if(this.editing_frame!=a){if(null!=this.editing_frame){var b=this.container.down(".frame-"+this.editing_frame);b.removeClassName("frame-focused")}this.editing_frame=a;null!=this.editing_frame&&(b=this.container.down(".frame-"+this.editing_frame),b.addClassName("frame-focused"));for(a=0;a<this.corner_draggers.length;++a)this.corner_draggers[a].set_post_frame(this.editing_frame);this.update()}};
FrameEditor.prototype.close=function(){if(null!=this.post_id){this.editing_frame=this.post_id=null;for(var a=0;a<this.corner_draggers.length;++a)this.corner_draggers[a].set_post_id(null);this.keydown_handler&&(this.open_handlers.each(function(a){a.stop()}),this.open_handlers=[]);this.dragger&&this.dragger.destroy();this.dragger=null;this.container.hide();this.main_frame.hide();this.update_show_corner_drag();for(a=this.container.down(".frame-list").down("TBODY");a.firstChild;)a.removeChild(a.firstChild);
this.original_frames=null;this.update();if(this.options.onClose)this.options.onClose(this)}};
CornerDragger=function(a,b,c){this.container=a;this.part=b;this.options=c;a=a.down(".frame-editor-popup-div");c=$(document.createElement("div"));c.className="frame-editor-frame-box";create_drag_box(c);a.appendChild(c);this.dragger=new DragElement(a,{snap_pixels:0,ondown:function(a){var c=document.elementFromPoint(a.x,a.y);c.hasClassName("frame-box-handle")?this.dragging_mode=c.frame_drag_cursor:".frame-editor-nw"==b?this.dragging_mode="nw-resize":".frame-editor-ne"==b?this.dragging_mode="ne-resize":
".frame-editor-sw"==b?this.dragging_mode="sw-resize":".frame-editor-se"==b&&(this.dragging_mode="se-resize");c=Post.posts.get(this.post_id);this.dragging_anchor=frame_dimensions_to_image(c.frames_pending[this.post_frame],this.image_dimensions,c);this.dragger.overriden_drag_class="move"==this.dragging_mode?null:"hide-cursor";a.latest_event.stopPropagation()}.bind(this),ondrag:function(a){var b=Post.posts.get(this.post_id);a=apply_drag(this.dragging_mode,-a.aX,-a.aY,this.image_dimensions,this.dragging_anchor);
a=frame_dimensions_from_image(a,this.image_dimensions,b);b.frames_pending[this.post_frame]=a;if(this.options.onUpdate)this.options.onUpdate()}.bind(this)});this.update()};
CornerDragger.prototype.set_post_id=function(a){this.post_id=a;var b=this.post_frame=null,c=this.container.down("img");null!=a&&(a=Post.posts.get(this.post_id),this.image_dimensions={width:a.jpeg_width,height:a.jpeg_height},b=a.jpeg_url,c.width=this.image_dimensions.width,c.height=this.image_dimensions.height);c.src!=b&&(c.src=b,Prototype.Browser.WebKit&&b&&(document.documentElement.addClassName("hourglass"),function(){document.documentElement.removeClassName("hourglass")}.defer()));this.update()};
CornerDragger.prototype.set_post_frame=function(a){this.post_frame=a;this.update()};
CornerDragger.prototype.update=function(){if(null!=this.post_id&&null!=this.post_frame){var a=Post.posts.get(this.post_id),a=frame_dimensions_to_image(a.frames_pending[this.post_frame],this.image_dimensions,a),b=this.container,c=this.container.down(".frame-editor-frame-box");c.style.left=a.left+"px";c.style.top=a.top+"px";c.style.width=a.width+"px";c.style.height=a.height+"px";var c=a.top,d=a.left;if(".frame-editor-ne"==this.part||".frame-editor-se"==this.part)d+=a.width;if(".frame-editor-sw"==this.part||
".frame-editor-se"==this.part)c+=a.height;var e=b.offsetHeight/2,d=d-b.offsetWidth/2,c=c-e;if(".frame-editor-nw"==this.part||".frame-editor-sw"==this.part)d=Math.min(d,a.left+a.width/2-b.offsetWidth);if(".frame-editor-ne"==this.part||".frame-editor-se"==this.part)d=Math.max(d,a.left+a.width/2);if(".frame-editor-nw"==this.part||".frame-editor-ne"==this.part)c=Math.min(c,a.top+a.height/2-b.offsetHeight);if(".frame-editor-sw"==this.part||".frame-editor-se"==this.part)c=Math.max(c,a.top+a.height/2);a=
this.container.down(".frame-editor-popup-div");a.style.marginTop=-c+"px";a.style.marginLeft=-d+"px"}};
var PostUploadForm=function(a,b){var c="FormData"in window;"XMLHttpRequest"in window&&null!=(new XMLHttpRequest).upload&&c&&(this.form_element=a,this.cancel_element=this.form_element.down(".cancel"),this.progress=b,this.document_title=document.documentElement.down("TITLE"),this.document_title_orig=this.document_title.textContent,this.current_request=null,this.form_element.on("submit",this.form_submit_event.bindAsEventListener(this)),this.cancel_element.on("click",this.click_cancel.bindAsEventListener(this)),
document.on(window.opera||Prototype.Browser.Gecko?"keypress":"keydown",this.document_keydown_event.bindAsEventListener(this)))};PostUploadForm.prototype.set_progress=function(a){a*=100;this.progress.down(".upload-progress-bar-fill").style.width=a+"%";this.document_title.textContent=this.document_title_orig+" ("+a.toFixed(0)+"%)"};PostUploadForm.prototype.request_starting=function(){this.form_element.down(".submit").hide();this.cancel_element.show();this.progress.show();document.documentElement.addClassName("progress")};
PostUploadForm.prototype.request_ending=function(){this.form_element.down(".submit").show();this.cancel_element.hide();this.progress.hide();this.document_title.textContent=this.document_title_orig;document.documentElement.removeClassName("progress")};PostUploadForm.prototype.document_keydown_event=function(a){var b=a.charCode;b||(b=a.keyCode);b==Event.KEY_ESC&&this.cancel()};PostUploadForm.prototype.click_cancel=function(a){a.stop();this.cancel()};
PostUploadForm.prototype.form_submit_event=function(a){if(!a.stopped&&null==this.current_request){$("post-exists").hide();$("post-upload-error").hide();var b=$("post_file");if(null!=b.files&&0!=b.files.length){a.stop();this.set_progress(0);this.request_starting();a=new FormData(this.form_element);var c=function(a){var b=a.loaded;a=a.total;this.set_progress(a?b/a:1)}.bind(this);this.current_request=new Ajax.Request("/post/create.json",{contentType:null,method:"post",postBody:a,onCreate:function(a){a.request.transport.upload.onprogress=
c},onComplete:function(a){this.current_request=null;this.request_ending();if(a=a.responseJSON)if(a.success){var b=a.location;a.similar_location&&a.has_similar_hits&&(b=a.similar_location);window.location.href=b}else a.location?(b=$("post-exists-link"),b.setTextContent("post #"+a.post_id),b.href=a.location,$("post-exists").show()):($("post-upload-error").setTextContent(a.reason),$("post-upload-error").show())}.bind(this)})}}};PostUploadForm.prototype.cancel=function(){null!=this.current_request&&this.current_request.transport.abort()};
UploadSimilarSearch=function(a,b){ThumbnailUserImage&&(this.file_field=a,this.results=b,a.on("change",this.field_changed_event.bindAsEventListener(this)))};UploadSimilarSearch.prototype.field_changed_event=function(a){this.results.hide();null!=this.file_field.files&&0!=this.file_field.files.length&&(this.results.innerHTML="Searching...",this.results.show(),new ThumbnailUserImage(this.file_field.files[0],this.thumbnail_complete.bind(this)))};
UploadSimilarSearch.prototype.thumbnail_complete=function(a){if(a.success){a=a.canvas.toDataURL();var b=new FormData;b.append("url",a);new Ajax.Request("/post/similar.json",{method:"post",postBody:b,contentType:null,onComplete:function(a){this.results.innerHTML="";this.results.show();a=a.responseJSON;if(a.success)if(0<a.posts.length){var b=[];a.posts.slice(0,3).each(function(a){var c;c=User.get_use_browser()?"/post/browse#"+a.id:"/post/show/"+a.id;b.push("<a href='"+c+"'>post #"+a.id+"</a>")});var e=
b.join(", "),e="Similar posts "+("<a href='/post/similar?search_id="+a.search_id+"'>(see all)</a>")+": "+e;3<a.posts.length&&(e+=" ("+(a.posts.length-3)+" more)");this.results.innerHTML=e}else this.results.innerHTML="No similar posts found.";else this.results.innerHTML=a.reason}.bind(this)})}else this.results.innerHTML="Image load failed.",this.results.show()};
Post={posts:new Hash,tag_types:new Hash,votes:new Hash,tag_type_names:"general artist copyright character circle faults".split(" "),find_similar:function(){var a=$("post_source").name,b=$("post_file").name,c=$("edit-form").target,d=$("edit-form").action;$("post_source").name="url";$("post_file").name="file";$("edit-form").target="_blank";$("edit-form").action="http://danbooru.iqdb.hanyuu.net/";$("edit-form").submit();$("post_source").name=a;$("post_file").name=b;$("edit-form").target=c;$("edit-form").action=
d},make_request:function(a,b,c){return new Ajax.Request(a,{parameters:b,onFailure:function(a){notice("Error: "+a.responseJSON.reason)},onSuccess:function(a){a=a.responseJSON;Post.register_resp(a);for(var b=new Hash,f=0;f<a.posts.length;++f)b.set(a.posts[f].id,!0);document.fire("posts:update",{resp:a,post_ids:b});c&&c(a)}})},approve:function(a,b,c){notice("Approving post #"+a);var d={};d["ids["+a+"]"]="1";d.commit=b?"Delete":"Approve";b&&(d.reason=b);return Post.make_request("/post/moderate.json",
d,function(){notice(b?"Post deleted":"Post approved");c?c(a):($("p"+a)&&$("p"+a).removeClassName("pending"),$("pending-notice")&&$("pending-notice").hide())})},undelete:function(a,b){return Post.make_request("/post/undelete.json",{id:a},b)},applied_list:[],reset_tag_script_applied:function(){for(var a=0;a<Post.applied_list.length;++a)Post.applied_list[a].removeClassName("tag-script-applied");Post.applied_list=[]},update_batch:function(a,b){var c=a.length;TagCompletion&&a.each(function(a){null!=a.tags&&
TagCompletion.add_recent_tags_from_update(a.tags,a.old_tags)});var d=[],e=0;a.each(function(a){$H(a).each(function(a){a="post["+e+"]["+a.key+"]="+window.encodeURIComponent(a.value);d.push(a)});e++});var f=d.join("&");Post.make_request("/post/update_batch.json",f,function(a){a.posts.each(function(a){Post.update_styles(a);a=$$("#p"+a.id+" > .directlink");0<a.length&&(a[0].addClassName("tag-script-applied"),Post.applied_list.push(a[0]))});notice((1==c?"Post":"Posts")+" updated");b&&b(a.posts)})},update_styles:function(a){var b=
$("p"+a.id);b&&(a.has_children?b.addClassName("has-children"):b.removeClassName("has-children"),a.parent_id?b.addClassName("has-parent"):b.removeClassName("has-parent"))},update:function(a,b,c){notice("Updating post #"+a);b.id=a;new Ajax.Request("/post/update.json",{parameters:b,onComplete:function(b){b=b.responseJSON;if(b.success){notice("Post updated");Post.register(b.post);Post.register_tags(b.tags);Post.update_styles(b.post);var e=e=$$("#p"+a+" > .directlink");0<e.length&&(e[0].addClassName("tag-script-applied"),
Post.applied_list.push(e[0]));c&&c(b.post)}else notice("Error: "+b.reason)}})},activate_posts:function(a,b){notice("Activating "+a.length+(1==a.length?" post":" posts"));var c={};c["post_ids[]"]=a;new Ajax.Request("/post/activate.json",{parameters:c,onComplete:function(a){a=a.responseJSON;a.success?b&&b(a):notice("Error: "+a.reason)}})},activate_all_posts:function(){var a=[];Post.posts.each(function(b){$("p"+b.key)&&a.push(b.key)});Post.activate_posts(a,function(a){0==a.count?notice("No posts were activated."):
notice(a.count+(1==a.count?" post":" posts")+" activated")})},activate_post:function(a){Post.update_batch([{id:a,is_held:!1}],function(){Post.posts.get(a).is_held?notice("Couldn't activate post"):$("held-notice").remove()})},init_add_to_favs:function(a,b,c){var d=function(d){if(null==d||null!=d.memo.post_ids.get(a))d=Post.votes.get(a)||0,b.show(3>d),c.show(3<=d)};d();document.on("posts:update",d)},vote:function(a,b){3<b||(notice("Voting..."),Post.make_request("/post/vote.json",{id:a,score:b},function(a){notice("Vote saved")}))},
flag:function(a,b){var c=prompt("Why should this post be flagged for deletion?","");return c?Post.make_request("/post/flag.json",{id:a,reason:c},function(){notice("Post was flagged for deletion");if(b)b(a);else{var c=$("p"+a);c&&c.addClassName("flagged")}}):!1},unflag:function(a,b){return Post.make_request("/post/flag.json",{id:a,unflag:1},function(){notice("Post was approved");if(b)b(a);else{var c=$("p"+a);c&&c.removeClassName("flagged")}})},observe_text_area:function(a){$(a).observe("keydown",function(a){a.keyCode==
Event.KEY_RETURN&&(a.stop(),this.up("form").simulate_submit())})},get_post_tags_by_type:function(a){var b=new Hash;a.tags.each(function(a){var d=Post.tag_types.get(a);d||(d="general");var e=b.get(d);e||(e=[],b.set(d,e));e.push(a)});return b},get_post_tags_with_type:function(a){var b=Post.get_post_tags_by_type(a);a=b.keys();var c="artist circle copyright character faults general".split(" ");a=a.sort(function(a,b){var d=c.indexOf(a);-1==d&&(d=999);var h=c.indexOf(b);-1==h&&(h=999);return d-h});var d=
[];a.each(function(a){b.get(a).each(function(b){d.push([b,a])})});return d},register_resp:function(a){a.posts&&Post.register_posts(a.posts);a.tags&&Post.register_tags(a.tags);a.votes&&Post.register_votes(a.votes);a.pools&&Pool.register_pools(a.pools);a.pool_posts&&Pool.register_pool_posts(a.pool_posts,a.posts)},register:function(a){a.tags=a.tags.match(/\S+/g)||[];a.match_tags=a.tags.clone();a.match_tags.push("rating:"+a.rating.charAt(0));a.match_tags.push("status:"+a.status);this.posts.set(a.id,a)},
register_posts:function(a){a.each(function(a){Post.register(a)})},unregister_all:function(){this.posts=new Hash},register_tags:function(a,b){this.tag_types.update(a);TagCompletion&&!b&&TagCompletion.update_tag_types()},register_votes:function(a){this.votes.update(a)},blacklists:[],is_blacklisted:function(a){a=Post.posts.get(a);for(var b=Post.blacklists,c=b.length,d=0;d<c;++d){var e;a:{var f=b[d],g=f.require,h=g.length;for(e=0;e<h;++e)if(-1==a.match_tags.indexOf(g[e])){e=!1;break a}f=f.exclude;g=f.length;
for(e=0;e<g;++e)if(-1!=a.match_tags.indexOf(f[e])){e=!1;break a}e=!0}if(e)return!0}return!1},apply_blacklists:function(){Post.blacklists.each(function(a){a.hits=0});var a=0;Post.posts.each(function(b){var d=$("p"+b.key);if(d){var e=b.value,f=e.match_tags.member.bind(e.match_tags);e.blacklisted=[];e.id!=Post.blacklist_options.exclude&&Post.blacklists.each(function(a){a.require.all(f)&&!a.exclude.any(f)&&(a.hits++,Post.disabled_blacklists[a.tags]||e.blacklisted.push(a))});b=0<e.blacklisted.length;a+=
b;Post.blacklist_options.replace?b?(d.src="/images/blank.gif",b=function(a){a=a.target;a.stopObserving("load");a.stopObserving("error");a.src="/blacklisted-preview.png";a.removeClassName("javascript-hide")},d.observe("load",b),d.observe("error",b)):(d.src=e.preview_url,d.removeClassName("javascript-hide")):b?d.addClassName("javascript-hide").addClassName("blacklisted-post"):d.removeClassName("javascript-hide")}});Post.countText&&Post.countText.update(a);var b=$("blacklisted-notice");b&&b.show(0<a);
return a},current_blacklists:null,hide_inactive_blacklists:!0,disabled_blacklists:{},blacklists_update_disabled:function(){Post.blacklists.each(function(a){a.a&&(Post.disabled_blacklists[a.tags]||0==a.hits?a.a.addClassName("blacklisted-tags-disabled"):a.a.removeClassName("blacklisted-tags-disabled"))})},init_blacklisted:function(a){Post.blacklist_options=Object.extend({replace:!1,exclude:null},a);a=Post.current_blacklists?Post.current_blacklists:eval(jQuery.cookie("blacklisted_tags"));Post.blacklists=
[];a.each(function(a){var b=a.replace(/(rating:[qes])\w+/,"$1").match(/\S+/g);if(b){var c={tags:b,original_tag_string:a,require:[],exclude:[],hits:0};b.each(function(a){"-"==a.charAt(0)?c.exclude.push(a.slice(1)):c.require.push(a)});Post.blacklists.push(c)}});Post.countText=$("blacklist-count");Post.countText&&Post.countText.update("");Post.apply_blacklists();(a=$("blacklisted-sidebar"))&&a.show();var b=$("blacklisted-list");if(b){for(;b.firstChild;)b.removeChild(b.firstChild);Post.blacklists.sort(function(a,
b){return 0==a.hits&&0<b.hits?1:0<a.hits&&0==b.hits?-1:a.tags.join(" ").localeCompare(b.tags.join(" "))});inactive_blacklists_hidden=0;Post.blacklists.each(function(a){if(Post.hide_inactive_blacklists&&!a.hits)++inactive_blacklists_hidden;else{var c=b.appendChild(document.createElement("li"));c.className="blacklisted-tags";c.style.position="relative";var f=c.appendChild($(document.createElement("a")));f.style.position="absolute";f.style.left="-0.75em";f.href="#";f.update("\u2298");f.observe("click",
function(b){if(!User.run_login_onclick(b))return!1;b.stop();var c=a.original_tag_string;User.modify_blacklist([],[c],function(a){notice('Unblacklisted "'+c+'"');Post.current_blacklists=a.result;Post.init_blacklisted()})});c.appendChild(document.createTextNode("\u00bb "));f=c.appendChild(document.createElement("a"));a.a=f;f.href="#";f.className="no-focus-outline";a.hits?$(f).observe("click",function(b){Post.disabled_blacklists[a.tags]=!Post.disabled_blacklists[a.tags];Post.apply_blacklists();Post.blacklists_update_disabled();
b.stop()}):f.addClassName("blacklisted-tags-disabled");f.appendChild(document.createTextNode(a.tags.join(" ")));c.appendChild(document.createTextNode(" "));c=c.appendChild(document.createElement("span"));c.className="post-count";0<a.hits&&c.appendChild(document.createTextNode("("+a.hits+")"))}});if(Post.hide_inactive_blacklists&&0<inactive_blacklists_hidden){a=b.appendChild(document.createElement("li"));a.className="no-focus-outline";a.id="blacklisted-tag-show-all";var c=a.appendChild(document.createElement("a"));
c.href="#";c.className="no-focus-outline";$(c).observe("click",function(a){a.stop();$("blacklisted-tag-show-all").hide();Post.hide_inactive_blacklists=!1;Post.init_blacklisted()});c.appendChild(document.createTextNode("\u00bb Show all blacklists"));a.appendChild(document.createTextNode(" "))}}Post.blacklists_update_disabled()},blacklist_add_commit:function(){var a=$("add-blacklist").value;""!=a&&($("add-blacklist").value="",User.modify_blacklist(a,[],function(b){notice('Blacklisted "'+a+'"');Post.current_blacklists=
b.result;Post.init_blacklisted()}))},last_click_id:null,check_avatar_blacklist:function(a,b){if(b&&b==this.last_click_id)return!0;this.last_click_id=b;if(!Post.is_blacklisted(a))return!0;notice("This post matches one of your blacklists. Click again to open.");return!1},resize_image:function(){var a=$("image");null==a.original_width&&(a.original_width=a.width,a.original_height=a.height);var b=1;if(1==a.scale_factor||null==a.scale_factor)var c=$("right-col").clientWidth-15,d=window.innerHeight-15,
b=Math.min(b,c/a.original_width),b=Math.min(b,d/a.original_height);a.width=a.original_width*b;a.height=a.original_height*b;a.scale_factor=b;if(window.Note)for(a=0;a<window.Note.all.length;++a)window.Note.all[a].adjustScale()},get_scroll_offset_to_center:function(a){var b=document.viewport.getDimensions(),c=a.cumulativeOffset();return[c.left-(b.width-a.offsetWidth)/2,c.top-(b.height-a.offsetHeight)/2]},center_image:function(a){a||(a=$("image"));if(a){a.setStyle({paddingLeft:0,paddingTop:0});var b=
Post.get_scroll_offset_to_center(a),c=-b[0];0>c&&(c=0);a.setStyle({paddingLeft:c+"px"});c=-b[1];0>c&&(c=0);a.setStyle({paddingTop:c+"px"});var d=document.viewport.getDimensions(),c=b[0]+d.width,b=b[1]+d.height;$(document.body).setStyle({minWidth:c+"px",minHeight:b+"px"});b=Post.get_scroll_offset_to_center(a);window.scroll(b[0],b[1])}},scale_and_fit_image:function(a){a||(a=$("image"));if(a){null==a.original_width&&(a.original_width=a.width,a.original_height=a.height);var b=document.viewport.getDimensions(),
c=b.height,b=b.width/a.original_width;a.original_height*b>c&&(b=c/a.original_height);1>b&&(a.width=a.original_width*b,a.height=a.original_height*b);this.center_image(a);Post.adjust_notes()}},adjust_notes:function(){if(window.Note)for(var a=0;a<window.Note.all.length;++a)window.Note.all[a].adjustScale()},highres:function(){var a=$("image");if(!a.already_resized){a.already_resized=!0;null!=a.scale_factor&&1!=a.scale_factor&&Post.resize_image();$("resized_notice")&&$("resized_notice").hide();a.height=
a.width=0;a.src="";a.remove();a.original_height=null;a.original_width=null;var b=$("highres-show");a.height=b.getAttribute("link_height");a.width=b.getAttribute("link_width");$("note-container").insert({after:a});a.src=b.href;window.Note&&window.Note.all.invoke("adjustScale")}},set_same_user:function(a){var b=$("creator-id-css");b&&b.parentNode.removeChild(b);a=".creator-id-"+a+" .directlink { background-color: #300 !important; }";b=document.createElement("style");b.id="creator-id-css";b.type="text/css";
b.styleSheet?b.styleSheet.cssText=a:b.appendChild(document.createTextNode(a));document.getElementsByTagName("head")[0].appendChild(b)},init_post_list:function(){Post.posts.each(function(a){var b=a[1];if(a=$("p"+a[0]))if(a=a.down(".directlink"))a.observe("mouseover",function(a){Post.set_same_user(b.creator_id);return!1},!0),a.observe("mouseout",function(a){Post.set_same_user(null);return!1},!0)})},init_hover_thumb:function(a,b,c,d){Prototype.Browser.IE||(a.observe("mouseover",function(e){Post.hover_thumb_mouse_over(b,
a,c,d)}),a.observe("mouseout",function(a){a.relatedTarget!=c&&Post.hover_thumb_mouse_out(c)}),c.hover_init||(c.hover_init=!0,c.observe("mouseout",function(a){Post.hover_thumb_mouse_out(c)})))},hover_thumb_mouse_over:function(a,b,c,d){var e=Post.posts.get(a);c.hide();b=b.cumulativeOffset();c.style.width="auto";c.style.height="auto";Post.is_blacklisted(a)?c.src="/images/blacklisted-preview.png":(c.src=e.preview_url,"deleted"!=e.status&&(c.style.width=e.actual_preview_width+"px",c.style.height=e.actual_preview_height+
"px"));a=d.cumulativeOffset().top;d=a+d.getHeight()-1;b=b.top-2;b+c.getHeight()>d&&(d=d-c.getHeight()-4,d>=a&&(b=d));c.style.top=b+"px";c.show()},hover_thumb_mouse_out:function(a){a.hide()},acknowledge_new_deleted_posts:function(a){new Ajax.Request("/post/acknowledge_new_deleted_posts.json",{onComplete:function(a){a=a.responseJSON;a.success?$("posts-deleted-notice")&&$("posts-deleted-notice").hide():notice("Error: "+a.reason)}})},hover_info_pin:function(a){var b=null;null!=a&&(b=Post.posts.get(a));
Post.hover_info_pinned_post=b;Post.hover_info_update()},hover_info_mouseover:function(a){a=Post.posts.get(a);Post.hover_info_hovered_post!=a&&(Post.hover_info_hovered_post=a,Post.hover_info_update())},hover_info_mouseout:function(){null!=Post.hover_info_hovered_post&&(Post.hover_info_hovered_post=null,Post.hover_info_update())},hover_info_hovered_post:null,hover_info_displayed_post:null,hover_info_shift_held:!1,hover_info_pinned_post:null,hover_info_update:function(){var a=Post.hover_info_pinned_post;
a||(a=Post.hover_info_hovered_post,Post.hover_info_shift_held||(a=null));if(Post.hover_info_displayed_post!=a){Post.hover_info_displayed_post=a;var b=$("index-hover-info"),c=$("index-hover-overlay");if(a){b.down("#hover-dimensions").innerHTML=a.width+"x"+a.height;b.select("#hover-tags SPAN A").each(function(a){a.innerHTML=""});Post.get_post_tags_by_type(a).each(function(a){var b=$("hover-tag-"+a[0]),c=[];a[1].each(function(a){c.push(a)});b.innerHTML=c.join(" ")});"s"==a.rating?b.down("#hover-rating").innerHTML=
"s":"q"==a.rating?b.down("#hover-rating").innerHTML="q":"e"==a.rating&&(b.down("#hover-rating").innerHTML="e");b.down("#hover-post-id").innerHTML=a.id;b.down("#hover-score").innerHTML=a.score;a.is_shown_in_index?b.down("#hover-not-shown").hide():b.down("#hover-not-shown").show();b.down("#hover-is-parent").show(a.has_children);b.down("#hover-is-child").show(null!=a.parent_id);b.down("#hover-is-pending").show("pending"==a.status);b.down("#hover-is-flagged").show("flagged"==a.status);"flagged"==a.status&&
(b.down("#hover-flagged-reason").setTextContent(a.flag_detail.reason),b.down("#hover-flagged-by").setTextContent(a.flag_detail.flagged_by));b.down("#hover-file-size").innerHTML=number_to_human_size(a.file_size);b.down("#hover-author").innerHTML=a.author;b.show();b.style.left="0px";b.style.top="0px";var d=b.scrollWidth,e=b.scrollHeight,f=$("p"+a.id).down("IMG"),g=f.cumulativeOffset(),f=g[0]+f.scrollWidth/2,h=f-d/2,e=g[1]-e,l=document.viewport.getDimensions().width;0>h&&(h=0);h+d>l&&(h=l-d);b.style.left=
h+"px";b.style.top=e+"px";c.down("A").href=(User.get_use_browser()?"/post/browse#":"/post/show/")+a.id;c.down("IMG").src=a.preview_url;h=f-a.actual_preview_width/2;e=g[1];c.style.left=h+"px";c.style.top=e+"px";c.show()}else b.hide(),c.hide(),c.down("IMG").src="/images/blank.gif"}},hover_info_shift_down:function(){Post.hover_info_shift_held||(Post.hover_info_shift_held=!0,Post.hover_info_update())},hover_info_shift_up:function(){Post.hover_info_shift_held&&(Post.hover_info_shift_held=!1,Post.hover_info_update())},
hover_info_init:function(){document.observe("keydown",function(a){16==a.keyCode&&Post.hover_info_shift_down()});document.observe("keyup",function(a){16==a.keyCode&&Post.hover_info_shift_up()});document.observe("blur",function(a){Post.hover_info_shift_up()});var a=$("index-hover-overlay");Post.posts.each(function(b){var c=b[0];b=$("p"+b[1].id);null!=b&&(b.down("A").observe("mouseover",function(a){Post.hover_info_mouseover(c)}),b.down("A").observe("mouseout",function(b){b.relatedTarget&&b.relatedTarget.isParentNode(a)||
Post.hover_info_mouseout()}))});a.observe("mouseout",function(a){Post.hover_info_mouseout()})},highlight_posts_with_tag:function(a){Post.posts.each(function(b){b=b[1];var c=$("p"+b.id);c&&(a&&-1!=b.tags.indexOf(a)?c.addClassName("highlighted-post"):c.removeClassName("highlighted-post"))})},reparent_post:function(a,b,c,d){if(c)alert("The parent post has a parent, so this post can't be automatically reparented.");else{var e=[];new Ajax.Request("/post.json",{parameters:{tags:"parent:"+b},onComplete:function(c){c=
c.responseJSON;for(var g=0;g<c.length;++g){var h=c[g];if(h.id==b&&null!=h.parent_id){alert("The parent post has a parent, so this post can't be automatically reparented.");return}e.push({id:c[g].id,tags:"parent:"+a,old_tags:""})}null==d&&(d=function(){document.location.reload()});Post.update_batch(e,d)}})}},get_url_for_post_in_pool:function(a,b){return"/post/show/"+a+"?pool_id="+b},jump_to_post_in_pool:function(a,b){null==a?notice("No more posts in this pool"):window.location.href=Post.get_url_for_post_in_pool(a,
b)},InitBrowserLinks:function(){if(User.get_use_browser()){var a=function(a){return(a=a.match(/^(https?:\/\/[^\/]+)\/([a-z]+)\/([a-z]+)\/([0-9]+)([^#]*)(#.*)?$/))?{controller:a[2],action:a[3],id:a[4],hash:a[6]}:null},b=a(document.location.href),c=null;b&&"pool"==b.controller&&"show"==b.action&&(c=b.id);$$("A").each(function(b){if(!b.hasClassName("no-browser-link")&&!b.up(".no-browser-link")){var e;e=(e=b.href.match(/^(https?:\/\/[^\/]+)\/post(\/index)?\?tags=([^&]*)$/))?e[3]:null;null!=e?b.href="/post/browse#/"+
e:(e=a(b.href))&&!e.hash&&("post"==e.controller&&"show"==e.action?(e="/post/browse#"+e.id,null!=c&&(e+="/pool:"+c),b.browse_href=e,b.orig_href=b.href):"pool"==e.controller&&"show"==e.action&&(b.browse_href="/post/browse#/pool:"+e.id,b.orig_href=b.href),b.browse_href&&(b.href=b.browse_href))}})}},cached_sample_urls:null,get_cached_sample_urls:function(){if(LocalStorageDisabled())return null;2!=localStorage.sample_url_format&&Post.clear_sample_url_cache();if(null!=Post.cached_sample_urls)return Post.cached_sample_urls;
try{var a=JSON.parse(window.localStorage.sample_urls)}catch(b){return{}}return null==a?{}:Post.cached_sample_urls=a},clear_sample_url_cache:function(){"sample_urls"in localStorage&&delete window.localStorage.sample_urls;"sample_url_fifo"in localStorage&&delete window.localStorage.sample_url_fifo;localStorage.sample_url_format=2},cache_sample_urls:function(){var a=Post.get_cached_sample_urls();if(null!=a){var b=window.localStorage.sample_url_fifo||null,b=b?b.split(","):[];Post.posts.each(function(c){c=
c[1];c.sample_url&&(a[c.id]=c.sample_url);b.push(c.id)});var b=b.splice(-1E3),c={};b.each(function(a){c[a]=!0});var d=[];for(post_id in a)post_id in c||d.push(post_id);d.each(function(b){delete a[b]});Post.cached_sample_urls=a;try{window.localStorage.sample_urls=JSON.stringify(a),window.localStorage.sample_url_fifo=b.join(",")}catch(e){throw Post.clear_sample_url_cache(),e;}}},prompt_to_delete:function(a,b){null==b&&(b=function(){window.location.reload()});var c=Post.posts.get(a).flag_detail,c=prompt("Reason:",
c?c.reason:"");if(!c)return!1;Post.approve(a,c,b);return!0}};
PostModeMenu={mode:"view",init:function(a){try{this.pool_id=a,this.original_style={border:$("mode-box").getStyle("border")},""==Cookie.get("mode")?(Cookie.put("mode","view"),$("mode").value="view"):$("mode").value=Cookie.get("mode")}catch(b){}this.vote_score=Cookie.get("vote");""==this.vote_score?(this.vote_score=1,Cookie.put("vote",this.vote_score)):this.vote_score==+this.vote_score;Post.posts.each(function(a){var c=a[0];a=$("p"+a[1].id);null!=a&&(a.down("A").observe("click",function(a){PostModeMenu.click(a,
c)}),a.down("A").observe("mousedown",function(a){PostModeMenu.post_mousedown(a,c)}),a.down("A").observe("mouseover",function(a){PostModeMenu.post_mouseover(a,c)}),a.down("A").observe("mouseout",function(a){PostModeMenu.post_mouseout(a,c)}),a.down("A").observe("mouseup",function(a){PostModeMenu.post_mouseup(a,c)}))});document.observe("mouseup",function(a){PostModeMenu.post_mouseup(a,null)});Event.observe(window,"pagehide",function(a){PostModeMenu.post_end_drag()});this.change()},set_vote:function(a){this.vote_score=
a;Cookie.put("vote",this.vote_score);Post.update_vote_widget("vote-menu",this.vote_score)},get_style_for_mode:function(a){return"view"==a?{background:""}:"edit"==a?{background:"#3A3"}:"rating-q"==a?{background:"#AAA"}:"rating-s"==a?{background:"#6F6"}:"rating-e"==a?{background:"#F66"}:"vote"==a?{background:"#FAA"}:"lock-rating"==a?{background:"#AA3"}:"lock-note"==a?{background:"#3AA"}:"approve"==a?{background:"#26A"}:"flag"==a?{background:"#F66"}:"add-to-pool"==a?{background:"#26A"}:"apply-tag-script"==
a?{background:"#A3A"}:"reparent-quick"==a?{background:"#CCA"}:"remove-from-pool"==a?{background:"#CCA"}:"reparent"==a?{background:"#0C0"}:"dupe"==a?{background:"#0C0"}:{background:"#AFA"}},change:function(){if($("mode")){var a=$F("mode");Cookie.put("mode",a,7);PostModeMenu.mode=a;"edit"!=a.value&&$("quick-edit").hide();"apply-tag-script"!=a.value&&($("edit-tag-script").hide(),Post.reset_tag_script_applied());"vote"==a?(Post.update_vote_widget("vote-menu",this.vote_score),$("vote-score").show()):"apply-tag-script"==
a&&($("edit-tag-script").show(),$("edit-tag-script").focus())}},click:function(a,b){var c=$("mode");if(c){if("view"==c.value)return!0;if("edit"==c.value)post_quick_edit.show(b);else if("vote"==c.value)Post.vote(b,this.vote_score);else if("rating-q"==c.value)Post.update_batch([{id:b,rating:"questionable"}]);else if("rating-s"==c.value)Post.update_batch([{id:b,rating:"safe"}]);else if("rating-e"==c.value)Post.update_batch([{id:b,rating:"explicit"}]);else if("reparent"==c.value){if(b==id)return!1;TagScript.run(b,
"parent:"+id)}else if("dupe"==c.value){if(b==id)return!1;TagScript.run(b,"duplicate parent:"+id)}else"lock-rating"==c.value?Post.update_batch([{id:b,is_rating_locked:"1"}]):"lock-note"==c.value?Post.update_batch([{id:b,is_note_locked:"1"}]):"flag"==c.value?Post.flag(b):"approve"==c.value?Post.approve(b):"add-to-pool"==c.value?Pool.add_post(b,0):"remove-from-pool"==c.value?Pool.remove_post(b,PostModeMenu.pool_id):"destroy"==c.value&&(notice("Deleting post"),Post.make_request("/post/destroy.json",{id:b,
reason:"Via post-mode"},function(){jQuery(a.target).parents("li").remove();notice("Post deleted")}));a.stopPropagation();a.preventDefault()}},dragging_from_post:null,dragging_active:!1,dragging_list:null,dragging_hash:null,post_add_to_hovered_list:function(a){var b=b=$$("#p"+a+" > .directlink");0<b.length&&(b[0].addClassName("tag-script-applied"),Post.applied_list.push(b[0]));PostModeMenu.dragging_hash.get(a)||(PostModeMenu.dragging_hash.set(a,!0),PostModeMenu.dragging_list.push(a))},post_mousedown:function(a,
b){if(0==a.button){if("reparent-quick"==PostModeMenu.mode)PostModeMenu.dragging_from_post=b,PostModeMenu.post_begin_drag();else if("apply-tag-script"==PostModeMenu.mode)Post.reset_tag_script_applied(),PostModeMenu.dragging_from_post=b,PostModeMenu.dragging_list=[],PostModeMenu.dragging_hash=new Hash,PostModeMenu.post_add_to_hovered_list(b);else return;a.preventDefault();a.stopPropagation()}},post_begin_drag:function(a){document.body.addClassName("dragging-to-post")},post_end_drag:function(){document.body.removeClassName("dragging-to-post");
PostModeMenu.dragging_from_post=null},post_mouseup:function(a,b){0==a.button&&PostModeMenu.dragging_from_post&&("reparent-quick"==PostModeMenu.mode?(b&&(notice("Updating post"),Post.update_batch([{id:PostModeMenu.dragging_from_post,parent_id:b}])),PostModeMenu.post_end_drag()):"apply-tag-script"!=PostModeMenu.mode||b||(TagScript.run(PostModeMenu.dragging_list,TagScript.TagEditArea.value),PostModeMenu.dragging_from_post=null,PostModeMenu.dragging_active=!1,PostModeMenu.dragging_list=null,PostModeMenu.dragging_hash=
null))},post_mouseover:function(a,b){var c=$("p"+b),d=PostModeMenu.get_style_for_mode(PostModeMenu.mode);c.down("span").setStyle(d);"apply-tag-script"==PostModeMenu.mode&&PostModeMenu.dragging_from_post&&(b!=PostModeMenu.dragging_from_post&&(PostModeMenu.dragging_active=!0),PostModeMenu.post_add_to_hovered_list(b))},post_mouseout:function(a,b){$("p"+b).down("span").setStyle({background:""})},apply_tag_script_to_all_posts:function(){var a=TagScript.TagEditArea.value,b=Post.posts.inject([],function(a,
b){a.push(b[0]);return a});TagScript.run(b,a)}};
TagScript={TagEditArea:null,load:function(){this.TagEditArea.value=Cookie.get("tag-script")},save:function(){Cookie.put("tag-script",this.TagEditArea.value)},init:function(a,b){this.TagEditArea=a;TagScript.load();this.TagEditArea.observe("change",function(a){TagScript.save()});this.TagEditArea.observe("focus",function(a){Post.reset_tag_script_applied()});Event.on(window,"unload",function(){TagScript.save()});document.observe("focus",function(a){TagScript.load()})},parse:function(a){return a.match(/\[.+?\]|\S+/g)},
test:function(a,b){var c=!0;b.match(/\S+/g).each(function(b){if("-"==b[0]){if(a.include(b.substr(1,100)))throw c=!1,$break;}else if(!a.include(b))throw c=!1,$break;});return c},process:function(a,b){if(b.match(/^\[if/)){var c=b.match(/\[if\s+(.+?)\s*,\s*(.+?)\]/);return TagScript.test(a,c[1])?TagScript.process(a,c[2]):a}if("[reset]"==b)return[];if("-"==b[0]&&0!=b.indexOf("-pool:"))return a.reject(function(a){return a==b.substr(1,100)});a.push(b);return a},run:function(a,b,c){Object.isArray(a)||(a=
$A([a]));var d=TagScript.parse(b)||[],e=[];a.each(function(a){var b=Post.posts.get(a),c=b.tags.join(" ");d.each(function(a){b.tags=TagScript.process(b.tags,a)});e.push({id:a,old_tags:c,tags:b.tags.join(" ")})});notice("Updating "+e.length+(1==a.length?" post":" posts"));Post.update_batch(e,c)}};
function PostQuickEdit(a){this.container=a;this.submit_event=this.submit_event.bindAsEventListener(this);this.container.down("form").observe("submit",this.submit_event);this.container.down(".cancel").observe("click",function(a){a.preventDefault();this.hide()}.bindAsEventListener(this));this.container.down("#post_tags").observe("keydown",function(a){a.keyCode==Event.KEY_ESC?(a.stop(),this.hide()):a.keyCode==Event.KEY_RETURN&&this.submit_event(a)}.bindAsEventListener(this))}
PostQuickEdit.prototype.show=function(a){Post.hover_info_pin(a);var b=Post.posts.get(a);this.post_id=a;this.old_tags=b.tags.join(" ");this.container.down("#post_tags").value=b.tags.join(" ")+" rating:"+b.rating.substr(0,1)+" ";this.container.show();this.container.down("#post_tags").focus()};PostQuickEdit.prototype.hide=function(){this.container.hide();Post.hover_info_pin(null)};
PostQuickEdit.prototype.submit_event=function(a){a.stop();this.hide();Post.update_batch([{id:this.post_id,tags:this.container.down("#post_tags").value,old_tags:this.old_tags}],function(){notice("Post updated");this.hide()}.bind(this))};
PostTagHistory={last_click:-1,checked:[],dragging:!1,init:function(){$("history").observe("mousedown",function(a){a.shiftKey||(PostTagHistory.last_click=-1);PostTagHistory.mouse_is_down();a.stopPropagation();a.preventDefault()},!0);PostTagHistory.update()},add_change:function(a,b,c){PostTagHistory.checked.push({id:a,post_id:b,user_id:c,on:!1,row:$("r"+a)});$("r"+a).observe("mousedown",function(b){PostTagHistory.mousedown(a,b);!0});$("r"+a).observe("mouseover",function(b){PostTagHistory.mouseover(a,
b);!0})},update:function(){for(i=0;i<PostTagHistory.checked.length;++i){var a=PostTagHistory.checked[i].row;PostTagHistory.checked[i].on?a.addClassName("selected"):a.removeClassName("selected")}0<PostTagHistory.count_selected()?$("undo").className="":$("undo").className="footer-disabled";1==PostTagHistory.count_selected()?(i=PostTagHistory.get_first_selected_row(),$("revert").href="post_tag_history/revert?id="+PostTagHistory.checked[i].id,$("revert").className="",$("post_id").value=PostTagHistory.checked[i].post_id,
$("user_name").value=PostTagHistory.checked[i].user_id):($("revert").href="#",$("revert").className="footer-disabled")},count_selected:function(){for(i=ret=0;i<PostTagHistory.checked.length;++i)PostTagHistory.checked[i].on&&++ret;return ret},get_first_selected_row:function(){for(i=0;i<PostTagHistory.checked.length;++i)if(PostTagHistory.checked[i].on)return i;return null},get_row_by_id:function(a){for(i=0;i<PostTagHistory.checked.length;++i)if(PostTagHistory.checked[i].id==a)return i;return null},
set:function(a,b,c){for(i=a;;){PostTagHistory.checked[i].on=c;if(i==b)break;i+=b>a?1:-1}},doc_mouseup:function(a){PostTagHistory.dragging=!1;document.stopObserving("mouseup",PostTagHistory.doc_mouseup)},mouse_is_down:function(){PostTagHistory.dragging=!0;document.observe("mouseup",PostTagHistory.doc_mouseup)},mousedown:function(a,b){if(Event.isLeftClick(b)){PostTagHistory.mouse_is_down();var c=PostTagHistory.get_row_by_id(a);if(null!=c){var d,e;-1!=PostTagHistory.last_click&&b.shiftKey?(d=PostTagHistory.last_click,
e=c):(d=e=PostTagHistory.last_click=c,PostTagHistory.checked[c].on=!PostTagHistory.checked[c].on);c=PostTagHistory.checked[d].on;b.ctrlKey||PostTagHistory.set(0,PostTagHistory.checked.length-1,!1);PostTagHistory.set(d,e,c);PostTagHistory.update();b.stopPropagation();b.preventDefault()}}},mouseover:function(a,b){var c=PostTagHistory.get_row_by_id(a);c&&(-1==PostTagHistory.last_click&&(PostTagHistory.last_click=c),PostTagHistory.dragging&&(PostTagHistory.set(0,PostTagHistory.checked.length-1,!1),first=
PostTagHistory.last_click,this_click=last=c,PostTagHistory.set(first,last,!0),PostTagHistory.update()))},undo:function(){if(0!=PostTagHistory.count_selected()){var a=[];for(i=0;i<PostTagHistory.checked.length;++i)PostTagHistory.checked[i].on&&a.push(PostTagHistory.checked[i].id);notice("Undoing...");new Ajax.Request("/post_tag_history/undo.json",{parameters:{id:a.join(",")},onComplete:function(a){a=a.responseJSON;a.success?notice("Changes undone."):notice("Error: "+a.reason)}})}}};
var _preload_image_pool=null;PreloadContainer=function(){null==_preload_image_pool&&(_preload_image_pool=new ImgPoolHandler);this.container=$(document.createElement("div"));this.container.style.display="none";document.body.appendChild(this.container);this.active_preloads=0;this.on_image_complete_event=this.on_image_complete_event.bindAsEventListener(this)};
PreloadContainer.prototype.cancel_preload=function(a){a.stopObserving();this.container.removeChild(a);_preload_image_pool.release(a);a.active&&--this.active_preloads};PreloadContainer.prototype.preload=function(a){++this.active_preloads;var b=_preload_image_pool.get();b.observe("load",this.on_image_complete_event);b.observe("error",this.on_image_complete_event);b.src=a;b.active=!0;this.container.appendChild(b);return b};PreloadContainer.prototype.get_all=function(){return this.container.childElements()};
PreloadContainer.prototype.destroy=function(){this.get_all().each(function(a){this.cancel_preload(a)}.bind(this));document.body.removeChild(this.container)};PreloadContainer.prototype.on_image_complete_event=function(a){--this.active_preloads;a.target.active=!1};
Preload={preload_list:[],preload_container:null,preload_raw_urls:[],preload_started:!1,onload_event_initialized:!1,get_default_preload_container:function(){this.preload_container||(this.preload_container=new PreloadContainer);return this.preload_container},init:function(){this.onload_event_initialized||(this.onload_event_initialized=!0,Event.observe(window,"load",function(){Preload.preload_started=!0;Preload.start_preload()}))},preload:function(a){var b=this.get_default_preload_container();Preload.init();
Preload.preload_list.push([a,b]);Preload.start_preload()},preload_raw:function(a){Preload.init();Preload.preload_raw_urls.push(a);Preload.start_preload()},create_raw_preload:function(a){return new Ajax.Request(a,{method:"get",evalJSON:!1,evalJS:!1,parameters:null})},start_preload:function(){if(Preload.preload_started){for(var a=0;a<Preload.preload_list.length;++a){var b=Preload.preload_list[a];b[1].preload(b[0])}Preload.preload_list.length=[];for(a=0;a<Preload.preload_raw_urls.length;++a)Preload.create_raw_preload(Preload.preload_raw_urls[a]);
Preload.preload_raw_urls=[]}}};ReferralBanner=function(a){if(30<User.get_current_user_level())this.container=null;else if(this.container=a)this.container.down(".close-button").on("click",function(a){a.stop();this.container.removeClassName("shown")}.bind(this))};ReferralBanner.prototype.show_referral=function(){this.container&&(this.container.show(),function(){this.container.addClassName("shown")}.bind(this).defer())};
ReferralBanner.prototype.increment_view_count=function(){var a=Cookie.get_int("viewed");++a;Cookie.put("viewed",a);return a};ReferralBanner.prototype.increment_views_and_check_referral=function(){var a=this.increment_view_count(),b=Cookie.get_int("sref"),c=(new Date).getTime()/1E3;b&&(b>c||86400<=c-b)&&(Cookie.put("sref",0),b=0,Cookie.put("vref",a-1));b||(b=Cookie.get_int("vref"),a>=b&&9999>a-b||(Cookie.put("sref",c),this.show_referral()))};
RelatedTags={user_tags:[],recent_tags:[],recent_search:{},init:function(a,b){this.user_tags=(a.match(/\S+/g)||[]).sort();this.recent_tags=(this.recent_tags=Cookie.get("recent_tags").match(/\S+/g))?this.recent_tags.sort().uniq(!0):[];null!=b&&b.match(/^http/)?this.find_artist($F("post_source")):this.build_all({})},toggle:function(a,b){b=$(b);var c=b.value.match(/\S+/g)||[],d=(a.innerText||a.textContent).replace(/ /g,"_");c.include(d)?b.value=c.without(d).join(" ")+" ":b.value=c.concat([d]).join(" ")+
" ";this.build_all(this.recent_search);return!1},build_html:function(a,b){if(null==b||0==b.size())return"";for(var c="",d=$F("post_tags").match(/\S+/g)||[],c=c+'<div class="tag-column">'+("<h6><em>"+a.replace(/_/g," ")+"</em></h6>"),e=0;e<b.size();++e){var f=b[e],c=c+('<a href="/post?tags='+encodeURIComponent(f)+'" onclick="RelatedTags.toggle(this, \'post_tags\'); return false"');d.include(f)&&(c+=' style="background: rgb(0, 111, 250); color: white;"');c+=">"+f.escapeHTML().replace(/_/g," ")+"</a><br> "}return c+
"</div>"},build_all:function(a){this.recent_search=a;var b=this.build_html("My Tags",this.user_tags)+this.build_html("Recent Tags",this.recent_tags),c=[];for(key in a)c.push(key);c.sort();for(var d=0;d<c.size();++d)b+=this.build_html(c[d],a[c[d]]);$("related").update(b)},find:function(a,b){$("related").update("<em>Fetching...</em>");a=$(a);var c=null;null==a.textLength&&(a.textLength=jQuery(a).val().length);if(0==a.selectionStart||a.selectionStart==a.textLength)c=a.value;else{var c=a.selectionStart,
d=a.selectionEnd;if(c!=d)for(;0<d&&" "!=a.value[d];)--d;for(;0<c&&" "!=a.value[c];)--c;for(" "==a.value[c]&&(c+=1);d<a.textLength&&" "!=a.value[d];)d+=1;c=a.value.slice(c,d)}c={tags:c};b&&(c.type=b);new Ajax.Request("/tag/related.json",{method:"get",parameters:c,onComplete:function(a){a=a.responseJSON;a=this.convert_related_js_response(a);this.build_all(a)}.bind(this)})},convert_related_js_response:function(a){var b={};for(k in a){var c=a[k].map(function(a){return a[0]}).sort();b[k]=c}return b},find_artist:function(a){a.match(/^http/)&&
new Ajax.Request("/artist.json",{method:"get",parameters:{url:a,limit:"10"},onComplete:function(a){a=a.responseJSON;this.build_all({Artist:a.map(function(a){return a.name})})}.bind(this)})}};
ThumbnailUserImage=function(a,b){null==ThumbnailUserImage.image_pool&&(ThumbnailUserImage.image_pool=new ImgPoolHandler);this.file=a;this.canvas=create_canvas_2d();this.image=ThumbnailUserImage.image_pool.get();this.onComplete=b;this.url=URL.createObjectURL(this.file);this.image.on("load",this.image_load_event.bindAsEventListener(this));this.image.on("abort",this.image_abort_event.bindAsEventListener(this));this.image.on("error",this.image_error_event.bindAsEventListener(this));document.documentElement.addClassName("progress");
this.image.src=this.url};ThumbnailUserImage.image_pool=null;ThumbnailUserImage.prototype.destroy=function(){document.documentElement.removeClassName("progress");this.onComplete=null;this.image.stopObserving();ThumbnailUserImage.image_pool.release(this.image);this.image=null;null!=this.url&&(URL.revokeObjectURL(this.url),this.url=null)};ThumbnailUserImage.prototype.completed=function(a){if(this.onComplete)this.onComplete(a);this.destroy()};
ThumbnailUserImage.prototype.image_load_event=function(a){a=this.image.width;var b=this.image.height;if(128<a){var c=128/a,b=b*c;a*=c}128<b&&(c=128/b,b*=c,a*=c);a=Math.round(a);b=Math.round(b);c=this.canvas;c.width=a;c.height=b;a=c.getContext("2d");a.clearRect(0,0,c.width,c.height);a.drawImage(this.image,0,0,c.width,c.height);this.check_image_contents()?this.completed({success:!0,canvas:this.canvas}):this.completed({success:!1,chromeFailure:!0})};
ThumbnailUserImage.prototype.check_image_contents=function(){for(var a=this.canvas.getContext("2d").getImageData(0,0,this.canvas.width,this.canvas.height),b=a.data,c=3,a=a.width*a.height*4;c<a;){if(0!=b[c])return!0;c+=4}return!1};ThumbnailUserImage.prototype.image_abort_event=function(a){this.completed({success:!1,aborted:!0})};ThumbnailUserImage.prototype.image_error_event=function(a){this.completed({success:!1})};"URL"in window&&null!=create_canvas_2d()||(ThumbnailUserImage=null);
SimilarWithThumbnailing=function(a){this.similar=null;this.form=a;this.force_file=null;a.on("submit",this.form_submit_event.bindAsEventListener(this))};SimilarWithThumbnailing.prototype.form_submit_event=function(a){var b=this.form.down("#file");null!=b.files&&0!=b.files.length&&(b=b.files[0],this.force_file&&this.force_file==b?this.force_file=null:(a.stop(),this.similar&&this.similar.destroy(),this.similar=new ThumbnailUserImage(b,this.complete.bind(this))))};
SimilarWithThumbnailing.prototype.complete=function(a){if(a.chromeFailure)notice("The image failed to load; submitting normally..."),this.force_file=this.file,function(){this.form.simulate_submit()}.bind(this).defer();else if(a.success){a=a.canvas.toDataURL();var b=new FormData;b.append("url",a);new Ajax.Request("/post/similar.json",{method:"post",postBody:b,contentType:null,onComplete:function(a){a=a.responseJSON;a.success?window.location.href="/post/similar?search_id="+a.search_id:notice(a.reason)}})}else a.aborted||
alert("The file couldn't be loaded.")};"FormData"in window&&ThumbnailUserImage||(SimilarWithThumbnailing=null);TagCompletionClass=function(){this.loaded=this.loading=!1;5!=localStorage.tag_data_format&&(delete localStorage.tag_data,delete localStorage.tag_data_version,delete localStorage.recent_tags,localStorage.tag_data_format=5);this.recent_tags=localStorage.recent_tags||"";this.load_data_complete_callbacks=[];this.rapid_backspaces_received=0;this.updates_deferred=!1};
TagCompletionClass.prototype.init=function(a){this.loaded||(this.most_recent_tag_data_version=a)};
TagCompletionClass.prototype.load_data=function(a){if(this.loaded)return a&&a(),null!=this.tag_data;a&&this.load_data_complete_callbacks.push(a);if(this.loading)return null!=this.tag_data;this.loading=!0;var b=function(){this.loading=!1;this.loaded=!0;this.update_tag_types();var a=this.load_data_complete_callbacks;this.load_data_complete_callbacks=[];a.each(function(a){a()}.bind(this))}.bind(this);null!=localStorage.tag_data&&(this.tag_data=localStorage.tag_data);if(null!=localStorage.tag_data&&(null==
this.most_recent_tag_data_version||localStorage.tag_data_version==this.most_recent_tag_data_version))return b(),null!=this.tag_data;a={};null!=localStorage.tag_data_version&&(a.version=localStorage.tag_data_version);new Ajax.Request("/tag/summary.json",{parameters:a,onSuccess:function(a){a=a.responseJSON;a.unchanged?this.tag_data=localStorage.tag_data:(this.tag_data=a.data,localStorage.tag_data=this.tag_data,localStorage.tag_data_version=a.version);b()}.bind(this)});return null!=this.tag_data};
TagCompletionClass.prototype.observe_tag_changes_on_submit=function(a,b,c){return a.on("submit",function(a){TagCompletion.add_recent_tags_from_update(b.value,c?c.value:null)})};var get_tag_from_string=function(a){var b=a.match(/\d+`([^`]*)`.*/);if(!b)throw"Unparsable cached tag: '"+a+"'";return b[1]},split_data=function(a,b){var c=a.split(b);if(0!=c.length){if(""!=c[c.length-1])throw"String doesn't end in separator";c.pop()}return c},join_data=function(a,b){return 0==a.length?"":a.join(b)+b};
TagCompletionClass.prototype.update_tag_types_for_list=function(a,b){var c={},d=split_data(a," "),e=0;d.each(function(a){""!=a&&(a=get_tag_from_string(a),c[a]=e,++e)});Post.tag_types.each(function(a){var e=a[0],h=a[1];a=Post.tag_type_names.indexOf(h);if(-1==a)throw"Unknown tag type "+h;e in c?(e=c[e],h=d[e].match(/\d+(`.*)/),d[e]=a+h[1]):b&&d.push(a+"`"+e+"`")});return join_data(d," ")};
TagCompletionClass.prototype.update_tag_types=function(){this.loaded&&(this.tag_data=this.update_tag_types_for_list(this.tag_data,!0),localStorage.tag_data=this.tag_data,this.recent_tags=this.update_tag_types_for_list(this.recent_tags,!1),localStorage.recent_tags=this.recent_tags)};
TagCompletionClass.prototype.create_tag_search_regex=function(a,b){var c=a.split(""),d=[],e="(([^`]*_)?";c.each(function(a){a=RegExp.escape(a);e+=a});e+=")";d.push(e);if(-1!=a.indexOf("_")){var f=a.split("_",1)[0],g=a.slice(f.length+1),f=RegExp.escape(f),g=RegExp.escape(g),e="(",e=e+("("+f+"[^`]*_"+g+")"),e=e+"|",e=e+("("+g+"[^`]*_"+f+")"),e=e+")";d.push(e)}b.top_results_only||(e="(",c.each(function(a){a=RegExp.escape(a);e+=a;e+="[^`]*"}),e+=")",d.push(e));c=d.join("|");return new RegExp("(\\d+)[^ ]*`("+
c+")[^`]*`[^ ]* ",b.global?"g":"")};TagCompletionClass.prototype.retrieve_tag_search=function(a,b,c){var d=[],e=10;null!=c.max_results&&(e=c.max_results);for(;d.length<e;){c=a.exec(b);if(!c)break;c=c[0];-1==c.indexOf(":deletethistag:")&&-1==d.indexOf(c)&&d.push(c)}return d};
TagCompletionClass.prototype.add_recent_tag=function(a){if(-1!=a.indexOf(" ")||-1!=a.indexOf("`"))throw"Invalid recent tag: "+a;this.remove_recent_tag(a);var b=Post.tag_types.get(a)||"general",c=Post.tag_type_names.indexOf(b);if(-1==c)throw"Unknown tag type: "+b;this.recent_tags=c+"`"+a+"` "+this.recent_tags;this.recent_tags.length>163840/9&&(a=this.recent_tags.indexOf(" ",16384),-1!=a&&(this.recent_tags=this.recent_tags.slice(0,a+1)));localStorage.recent_tags=this.recent_tags};
TagCompletionClass.prototype.remove_recent_tag=function(a){a=RegExp.escape(a);this.recent_tags=this.recent_tags.replace(new RegExp("\\d`"+a+"` ","g"),"");localStorage.recent_tags=this.recent_tags};TagCompletionClass.prototype.add_recent_tags_from_update=function(a,b){a=a.split(" ");null!=b&&(b=b.split(" "));a.each(function(a){-1!=a.indexOf("`")||-1!="sqe".indexOf(a)||b&&-1!=b.indexOf(a)||null==b&&-1==a.indexOf(":")&&-1==this.tag_data.indexOf("`"+a+"`")||this.add_recent_tag(a)}.bind(this))};
TagCompletionClass.prototype.reorder_search_results=function(a,b){var c=this.create_tag_search_regex(a,{top_results_only:!0,global:!1}),d=[],e=[];b.each(function(a){c.test(a)?d.push(a):e.push(a)});return d.concat(e)};
TagCompletionClass.prototype.complete_tag=function(a,b){if(null==this.tag_data)throw"Tag data isn't loaded";null==b&&(b={});if(""==a)return[[],0];var c=this.create_tag_search_regex(a,{global:!0}),d=this.retrieve_tag_search(c,this.recent_tags,{max_results:100}),e=this.retrieve_tag_search(c,this.tag_data,{max_results:100}),d=this.reorder_search_results(a,d),e=this.reorder_search_results(a,e),c=d.length,d=d.concat(e);-1!="sqe".indexOf(a)&&d.unshift("0`"+a+"` ");var d=d.slice(0,null!=b.max_results?b.max_results:
10),c=Math.min(d.length,c),f=[],g={},h=[];d.each(function(a){var b=a.match(/(\d+)`([^`]*)`(([^ ]*)`)? /);if(!b)throw ReportError("Unparsable cached tag: '"+a+"'",null,null,null,null),"Unparsable cached tag: '"+a+"'";a=b[2];var c=Post.tag_type_names[b[1]],d=b[4],d=b[4]?d.split("`"):[];g[a]=c;-1==f.indexOf(a)&&(f.push(a),h.push(d))});Post.register_tags(g,!0);return[f,c,h]};TagCompletion=!LocalStorageDisabled()&&"addEventListener"in document?new TagCompletionClass:null;
TagCompletionBox=function(a){this.input_field=a;this.update=this.update.bind(this);this.last_value=this.input_field.value;this.input_field.setAttribute("autocomplete","off");a='<div class="tag-completion-box"><ul class="color-tag-types"></ul></div>'.createElement();a.tabindex=-1;document.body.appendChild(a);this.completion_box=a;document.on("mousedown",function(a){a.target.isParentNode(this.input_field)||a.target.isParentNode(this.completion_box)||this.hide()}.bindAsEventListener(this));this.input_field.on("mousedown",
this.input_mouse.bindAsEventListener(this));this.input_field.on("mouseup",this.input_mouse.bindAsEventListener(this));this.input_field.parentNode.addEventListener("keydown",this.input_keydown.bindAsEventListener(this),!0);this.input_field.on("keypress",this.input_keypress.bindAsEventListener(this));this.completion_box.on("mouseover",".completed-tag",function(a,c){this.focus_element(c)}.bind(this));this.completion_box.on("click","li",this.click_result.bind(this));this.hide()};
TagCompletionBox.prototype.input_mouse=function(a){this.update.defer()};
TagCompletionBox.prototype.input_keydown=function(a){if(a.target==this.input_field)if(a.keyCode==Event.KEY_BACKSPACE&&(++this.rapid_backspaces_received,this.backspace_timeout&&clearTimeout(this.backspace_timeout),this.backspace_timeout=setTimeout(function(){this.rapid_backspaces_received=0}.bind(this),100),1<this.rapid_backspaces_received&&(this.updates_deferred=!0,null!=this.defer_timeout&&clearTimeout(this.defer_timeout),this.defer_timeout=setTimeout(function(){this.updates_deferred=!1;this.update()}.bind(this),
100))),this.shown)if(a.keyCode==Event.KEY_DOWN)a.stop(),this.select_next(!0);else if(a.keyCode==Event.KEY_UP)a.stop(),this.select_next(!1);else if(a.keyCode==Event.KEY_ESC)a.stop(),this.hide();else if(a.keyCode==Event.KEY_RETURN){var b=this.completion_box.down(".focused");b?(a.stop(),this.set_current_word(b.result_tag)):this.hide()}else this.update.defer();else this.update.defer()};
TagCompletionBox.prototype.focus_element=function(a){if(null==a)throw"Can't select no element";var b=this.completion_box.down(".focused");b&&b.removeClassName("focused");a&&a.addClassName("focused")};TagCompletionBox.prototype.select_next=function(a){var b=this.completion_box.down(".focused"),b=a?b.nextSiblings():b.previousSiblings(),b=Prototype.Selector.find(b,".completed-tag",0);null==b&&(b=this.completion_box.down(a?".completed-tag":".completed-tag:last-child"));this.focus_element(b)};
TagCompletionBox.prototype.show=function(){this.shown=!0;var a=this.input_field.cumulativeOffset();this.completion_box.style.top=a.top+this.input_field.offsetHeight+"px";this.completion_box.style.left=a.left+"px";this.completion_box.style.minWidth=this.input_field.offsetWidth+"px"};TagCompletionBox.prototype.hide=function(){this.shown=!1;this.current_tag=null;this.completion_box.hide()};
TagCompletionBox.prototype.click_result=function(a,b){a.stop();a.target.hasClassName("remove-recent-tag")?(TagCompletion.remove_recent_tag(b.result_tag),this.update(!0)):this.set_current_word(b.result_tag)};TagCompletionBox.prototype.get_input_word_offset=function(a){var b=a.value,c=b.lastIndexOf(" ",a.selectionStart-1);-1==c?c=0:++c;a=b.indexOf(" ",a.selectionStart);-1==a&&(a=b.length);return{start:c,end:a}};
TagCompletionBox.prototype.set_current_word=function(a){var b=this.get_input_word_offset(this.input_field),c=this.input_field.value,d=c.substr(0,b.start),b=c.substr(b.end),c=a;b.match(/^ +$/)&&(b="");""==b&&(c+=" ");this.input_field.value=d+c+b;this.input_field.selectionStart=this.input_field.selectionEnd=d.length+c.length;TagCompletion.add_recent_tag(a);this.hide()};
TagCompletionBox.prototype.update=function(a){if(!this.updates_deferred||a){if(null==TagCompletion.tag_data){var b=TagCompletion.load_data(function(){b||(this.current_tag=null,this.update())}.bind(this));if(!b)return}var c=this.get_input_word_offset(this.input_field),c=this.input_field.value.substr(c.start,c.end-c.start);if(c!=this.current_tag||a)if(this.hide(),this.last_value!=this.input_field.value||a)if(this.last_value=this.input_field.value,this.current_tag=c,this.input_field.recursivelyVisible()){var d=
TagCompletion.complete_tag(c);a=d[0];var e=d[2],d=d[1];if(0!=a.length&&(1!=a.length||a[0]!=c)){this.show();var f=this.completion_box.down("UL");for(this.completion_box.hide();f.firstChild;)f.removeChild(f.firstChild);for(var g=0;g<a.length;++g){var c=a[g],h=document.createElement("LI");h.className="completed-tag";h.setTextContent(c);f.appendChild(h);var l=e[g];if(0<l.length){var m=document.createElement("span");m.className="completed-tag-alias";m.setTextContent(l[0]);h.appendChild(m)}l=Post.tag_types.get(c);
h.className+=" tag-type-"+l;g<d&&(h.className+=" recent-tag",h.appendChild("<a class='remove-recent-tag' href='#'>X</a>'".createElement()));h.result_tag=c}this.completion_box.show();this.focus_element(this.completion_box.down(".completed-tag"))}}}};TagCompletionBox.prototype.input_keypress=function(a){this.update.defer()};null!=TagCompletion&&"addEventListener"in document||(TagCompletionBox=function(){});
function AndroidDetectWindowSize(){$("sizing-body").setStyle({overflow:"hidden"});this.padding=document.createElement("DIV");this.padding.setStyle({width:"1px",height:"5000px"});this.padding.style.visibility="hidden";this.padding.hide();document.documentElement.appendChild(this.padding);this.window_size=[0,0];this.finish=this.finish.bind(this);this.event_onresize=this.event_onresize.bindAsEventListener(this);this.finish_timer=null;this.last_window_orientation=window.orientation;window.addEventListener("resize",
this.event_onresize,!0);this.active=!1;var a=0,b=navigator.userAgent.match(/Android (\d+\.\d+)/);b&&2.2>parseFloat(b[1])&&(debug("Delaying bootstrapping due to Android version "+b[1]),a=1);this.begin.bind(this).delay(a)}AndroidDetectWindowSize.required=function(){return-1!=navigator.userAgent.indexOf("Android")};AndroidDetectWindowSize.prototype.dispatch_resize_event=function(){debug("dispatch final resize event");var a=document.createEvent("Event");a.initEvent("resize",!0,!0);document.documentElement.dispatchEvent(a)};
AndroidDetectWindowSize.prototype.begin=function(){if(!this.active){var a=this.current_window_size();this.window_size&&a[0]==this.window_size[0]&&a[1]==this.window_size[1]?debug("skipped window size detection"):(debug("begin window size detection, "+a[0]+"x"+a[1]+" at start (scroll pos "+document.documentElement.scrollHeight+")"),this.active=!0,this.padding.show(),$("sizing-body").setStyle({width:"0px",height:"0px"}),window.scrollTo(0,99999999),this.finish_timer=window.setTimeout(this.finish,0))}};
AndroidDetectWindowSize.prototype.end=function(){this.active&&(this.active=!1,null!=this.begin_timer&&window.clearTimeout(this.begin_timer),this.begin_timer=null,null!=this.finish_timer&&window.clearTimeout(this.finish_timer),this.finish_timer=null,this.padding.hide())};AndroidDetectWindowSize.prototype.current_window_size=function(){var a=[window.innerWidth,window.innerHeight];++a[1];return a};
AndroidDetectWindowSize.prototype.finish=function(){this.active&&(debug("window size detection: finish(), at "+document.body.scrollTop),0==document.body.scrollTop?(console.log("Waiting for scroll..."),this.finish_timer=window.setTimeout(this.finish,10)):(window.scrollTo(document.body.scrollLeft,document.body.scrollTop),this.end(),this.window_size=this.current_window_size(),debug("new window size: "+this.window_size[0]+"x"+this.window_size[1]),$("sizing-body").setStyle({width:this.window_size[0]+"px",
height:this.window_size[1]+"px"}),this.dispatch_resize_event()))};AndroidDetectWindowSize.prototype.event_onresize=function(a){this.last_window_orientation!=window.orientation?(a.stop(),this.last_window_orientation=window.orientation,this.active?(debug("Orientation changed while already detecting window size; restarting"),this.end()):debug("Resize received with an orientation change; beginning"),this.begin()):this.active&&(debug("stopping resize event while we're active"),a.stop())};
function EmulateDoubleClick(){this.touchstart_event=this.touchstart_event.bindAsEventListener(this);this.touchend_event=this.touchend_event.bindAsEventListener(this);this.last_click=null;window.addEventListener("touchstart",this.touchstart_event,!1);window.addEventListener("touchend",this.touchend_event,!1)}
EmulateDoubleClick.prototype.touchstart_event=function(a){var b=a.changedTouches[0],c=this.last_click;this.last_click={timeStamp:a.timeStamp,target:a.target,identifier:b.identifier,position:[b.screenX,b.screenY],clientPosition:[b.clientX,b.clientY]};null==c||1<a.touches.length||500<a.timeStamp-c.timeStamp||500<Math.pow(b.screenX-c.position[0],2)+Math.pow(b.screenY-c.position[1],2)||a.target!=c.target||(b=document.createEvent("MouseEvent"),b.initMouseEvent("dblclick",!0,!0,window,2,c.position[0],c.position[1],
c.clientPosition[0],c.clientPosition[1],!1,!1,!1,!1,0,null),this.last_click=null,a.target.dispatchEvent(b))};EmulateDoubleClick.prototype.touchend_event=function(a){if(null!=this.last_click){var b=this.last_click.identifier;if(null!=b){var c=this.last_click.position;a=a.changedTouches[0];a.identifier==b&&500<Math.pow(a.screenX-c[0],2)+Math.pow(a.screenY-c[1],2)&&(this.last_click=null)}}};
ResponsiveSingleClick=function(){this.click_event=this.click_event.bindAsEventListener(this);this.touchstart_event=this.touchstart_event.bindAsEventListener(this);this.touchend_event=this.touchend_event.bindAsEventListener(this);this.last_touch=null;window.addEventListener("touchstart",this.touchstart_event,!1);window.addEventListener("touchend",this.touchend_event,!1);window.addEventListener("click",this.click_event,!0)};
ResponsiveSingleClick.prototype.touchstart_event=function(a){null!=this.last_touch?(debug("Cancelling click (multitouch)"),this.last_touch=null):(a=a.changedTouches[0],this.last_touch=[a.screenX,a.screenY])};
ResponsiveSingleClick.prototype.touchend_event=function(a){var b=this.last_touch;if(null!=b){this.last_touch=null;var c=a.changedTouches[0],d=[c.screenX,c.screenY];if(!(50<distance_squared(d[0],d[1],b[0],b[1]))){var e=document.createEvent("MouseEvent");e.initMouseEvent("click",!0,!0,window,1,c.screenX,c.screenY,c.clientX,c.clientY,!1,!1,!1,!1,0,null);e.synthesized_click=!0;(function(){a.target.dispatchEvent(e)}).defer()}}};
ResponsiveSingleClick.prototype.click_event=function(a){a.synthesized_click||a.stop()};PreventDragScrolling=function(){Element.observe(document,"touchmove",function(a){a.preventDefault()})};
var MaintainUrlHash=function(){if(!LocalStorageDisabled()){UrlHash.observe(null,function(a,c,d){localStorage.current_hash=UrlHash.get_raw_hash()});var a=localStorage.getItem("current_hash");a&&UrlHash.set_raw_hash(a)}},SendMissingResizeEvents=function(){if(!window.navigator.standalone&&-1!=navigator.userAgent.indexOf("Version/4.0.5")){var a=window.orientation;window.addEventListener("orientationchange",function(b){a!=window.orientation&&(a=window.orientation,debug("dispatch fake resize event"),b=
document.createEvent("Event"),b.initEvent("resize",!0,!0),document.documentElement.dispatchEvent(b))},!0)}},InitializeFullScreenBrowserHandlers=function(){-1!=navigator.userAgent.indexOf("Android")&&-1!=navigator.userAgent.indexOf("WebKit")?(new ResponsiveSingleClick,new EmulateDoubleClick):-1==navigator.userAgent.indexOf("iPhone")&&-1==navigator.userAgent.indexOf("iPad")&&-1==navigator.userAgent.indexOf("iPod")||-1==navigator.userAgent.indexOf("WebKit")||(new ResponsiveSingleClick,new EmulateDoubleClick,
window.navigator.standalone&&MaintainUrlHash(),SendMissingResizeEvents());PreventDragScrolling()};SwipeHandler=function(a){this.element=a;this.dragger=new DragElement(a,{ondrag:this.ondrag.bind(this),onstartdrag:this.startdrag.bind(this)})};SwipeHandler.prototype.startdrag=function(){this.swiped_vertical=this.swiped_horizontal=!1};
SwipeHandler.prototype.ondrag=function(a){!this.swiped_horizontal&&100<Math.abs(a.aX)&&(this.element.fire("swipe:horizontal",{right:0<a.aX}),this.swiped_horizontal=!0);!this.swiped_vertical&&100<Math.abs(a.aY)&&(this.element.fire("swipe:vertical",{down:0<a.aY}),this.swiped_vertical=!0)};SwipeHandler.prototype.destroy=function(){this.dragger.destroy()};
UrlHashHandler=function(){this.observers=new Hash;this.normalize=function(a){};this.denormalize=function(a){};this.deferred_sets=[];this.deferred_replace=!1;this.current_hash=this.parse(this.get_raw_hash());this.normalize(this.current_hash);this.last_hashchange=this.current_hash.clone();this.hashchange_event=this.hashchange_event.bindAsEventListener(this);Element.observe(window,"hashchange",this.hashchange_event)};
UrlHashHandler.prototype.fire_observers=function(a,b){var c=a.keys(),c=c.concat(b.keys()),c=c.uniq(),d=[];c.each(function(c){var e=a.get(c),h=b.get(c);e!=h&&d.push(c)}.bind(this));var e=[];d.each(function(a){a=this.observers.get(a);null!=a&&(e=e.concat(a))}.bind(this));c=this.observers.get(null);null!=c&&(e=e.concat(c));e.each(function(c){c(d,a,b)})};UrlHashHandler.prototype.set_normalize=function(a,b){this.normalize=a;this.denormalize=b;this.normalize(this.current_hash);this.set_all(this.current_hash.clone())};
UrlHashHandler.prototype.hashchange_event=function(a){a=this.last_hashchange.clone();this.normalize(a);var b=this.get_raw_hash(),b=this.parse(b);this.normalize(b);this.current_hash=b.clone();this.last_hashchange=b.clone();this.fire_observers(a,b)};
UrlHashHandler.prototype.parse=function(a){null==a&&(a="");"#"==a.substr(0,1)&&(a=a.substr(1));var b=a.split("?",1)[0],c=a.substr(b.length+1),b=window.decodeURIComponent(b);a=new Hash;a.set("",b);if(""!=c)for(b=c.split("&"),c=0;c<b.length;++c){var d=b[c],e=d.split("=",1)[0];""!=e&&(d=d.substr(e.length+1),e=window.decodeURIComponent(e),d=window.decodeURIComponent(d),a.set(e,d))}return a};
UrlHashHandler.prototype.construct=function(a){var b="#",c=a.get("");null!=c&&(c=c.replace(/%/g,"%25").replace(/\?/g,"%3f"),b+=c);var d=[];a.each(function(a){var b=a[0];a=a[1];""!=b&&null!=a&&(b=window.encodeURIComponent(b),a=window.encodeURIComponent(a),d.push(b+"="+a))});0!=d.length&&(b+="?"+d.join("&"));return b};UrlHashHandler.prototype.get_raw_hash=function(){var a=window.location.href.split("#",1)[0];return window.location.href.substr(a.length)};
UrlHashHandler.prototype.set_raw_hash=function(a){a=this.parse(a);this.set_all(a)};UrlHashHandler.prototype.get=function(a){return this.current_hash.get(a)};UrlHashHandler.prototype.set=function(a,b){var c=this.current_hash.merge(a);this.normalize(c);this.set_all(c,b)};
UrlHashHandler.prototype.set_deferred=function(a,b){this.deferred_sets.push(a);b&&(this.deferred_replace=!0);var c=function(){this.deferred_set_timer=null;var a=this.current_hash;this.deferred_sets.each(function(b){a=a.merge(b)});this.normalize(a);this.set_all(a,this.deferred_replace);this.deferred_sets=[];this.hashchange_event(null);this.deferred_replace=!1}.bind(this);null==this.deferred_set_timer&&(this.deferred_set_timer=c.defer())};
UrlHashHandler.prototype.set_all=function(a,b){a=a.clone();this.normalize(a);this.current_hash=a.clone();this.denormalize(a);var c=this.construct(a);window.location.hash!=c&&(window.history&&window.history.replaceState&&window.history.pushState&&!navigator.userAgent.match("Firefox/[45].")?(c=window.location.protocol+"//"+window.location.host+window.location.pathname+c,b?window.history.replaceState({},window.title,c):window.history.pushState({},window.title,c)):window.location.hash=c);this.hashchange_event(null)};
UrlHashHandler.prototype.observe=function(a,b){var c=this.observers.get(a);null==c&&(c=[],this.observers.set(a,c));-1==c.indexOf(b)&&c.push(b)};UrlHashHandler.prototype.stopObserving=function(a,b){var c=this.observers.get(a);null!=c&&(c=c.without(b),this.observers.set(a,c))};UrlHash=new UrlHashHandler;
User={disable_samples:function(){new Ajax.Request("/user/update.json",{parameters:{"user[show_samples]":!1},onComplete:function(a){a=a.responseJSON;a.success?($("resized_notice").hide(),$("samples_disabled").show(),Post.highres()):notice("Error: "+a.reason)}})},destroy:function(a){notice("Deleting record #"+a);new Ajax.Request("/user_record/destroy.json",{parameters:{id:a},onComplete:function(a){200==a.status?notice("Record deleted"):notice("Access denied")}})},current_check:null,cancel_check:function(){current_check=
null},reset_password:function(a,b,c){new Ajax.Request("/user/reset_password.json",{parameters:{"user[name]":a,"user[email]":b},onComplete:function(a){a=a.responseJSON;c(a)}})},check:function(a,b,c,d){a={username:a};b&&(a.password=b);b=new Ajax.Request("/user/check.json",{parameters:a,onSuccess:function(a){c&&a.request!=current_check||(current_check=null,a=a.responseJSON,d(a))}});c&&(current_check=b)},create:function(a,b,c,d){a={"user[name]":a,"user[password]":b};c&&(a["user[email]"]=c);new Ajax.Request("/user/create.json",
{parameters:a,onComplete:function(a){a=a.responseJSON;d(a)}})},set_login:function(a,b,c){Cookie.put("login",a);Cookie.put("pass_hash",b);Cookie.put("user_info",c)},check_name_timer:null,last_username_in_form:null,success_func:null,messages:[],init:function(){$("login-popup-notices").select("SPAN").each(function(a){User.messages.push(a.id)});$$("FORM.need-signup").each(function(a){a.observe("submit",User.run_login_onsubmit)});$("login-popup").observe("submit",function(a){a.stop();User.form_submitted()});
$("login-popup-submit").observe("click",function(a){a.stop();User.form_submitted()});$("login-popup-cancel").observe("click",function(a){a.stop();User.close(!1)});$("login-popup-username").observe("blur",function(a){User.form_username_blur()});$("login-popup-username").observe("focus",function(a){User.form_username_focus()});$("login-popup-username").observe("keyup",function(a){User.form_username_changed(!0)});$("login-tabs").select("LI").each(function(a){a.observe("mousedown",function(a){a.stop()})});
$("login-tabs").select("LI").each(function(a){a.observe("click",function(b){b.stop();User.set_tab(a.id)})});OnKey(13,{AllowInputFields:!0,Element:$("login-popup")},function(a){a.stop();User.form_submitted()});OnKey(27,{AllowInputFields:!0,AlwaysAllowOpera:!0},function(a){if(!User.success_func)return!1;User.close(!1);return!0})},open:function(a){User.success_func&&User.close(!1);User.success_func=a;$("login-background").show();$("login-container").show();User.set_tab("tab-login")},close:function(a){if(User.success_func){$("login-background").hide();
$("login-container").hide();User.active_tab=null;User.check_name_timer=null;var b=User.success_func;success_func=User.success_func=null;a&&window.setTimeout(b,0)}},run_login_onclick:function(a){a=Event.extend(a);var b=$(a.target),c=clone_event(a);if(User.run_login(!0,function(){b.hasClassName("login-button")?(Cookie.put("notice","You have been logged in."),document.location.reload()):b.simulate_anchor_click(c)}))return!0;a.stop();return!1},run_login_onsubmit:function(a){var b=$(a.target);User.run_login(!0,
function(){b.simulate_submit()})||a.stop()},run_login:function(a,b){if(""!=Cookie.get("login"))return a||b(),!0;User.open(b);return!1},active_tab:null,set_tab:function(a){User.active_tab!=a&&(User.active_tab=a,User.check_name_timer=null,User.last_username_in_form=null,$("login-tabs").select("LI").each(function(a){a.removeClassName("selected")}),$("login-tabs").down("#"+a).addClassName("selected"),$$(".tab-header-text").each(function(a){a.hide()}),$(a+"-text").show(),"tab-login"==a?(""==$("login-popup-password").value&&
""!=$("login-popup-username").value?$("login-popup-password").focus():$("login-popup-username").focus(),User.set_state("login-blank")):"tab-reset"==a&&(User.set_state("reset-blank"),$("login-popup-username").focus()),User.form_username_changed())},message:function(a){for(var b=0,c=User.messages.length;b<c;b++)$(User.messages[b]).hide();$("login-popup-message").update(a);$("login-popup-message").show()},set_state:function(a){var b={};a.match(/^login-/)?(b["login-popup-password-box"]=!0,"login-blank"==
a?$("login-popup-submit").update("Login"):"login-user-exists"==a?$("login-popup-submit").update("Login"):"login-confirm-password"==a?(b["login-popup-password-confirm-box"]=!0,$("login-popup-submit").update("Create account")):"login-confirm-password-mismatch"==a&&$("login-popup-submit").update("Create account"),b["login-popup-"+a]=!0):a.match(/^reset-/)&&(b["login-popup-email-box"]=!0,$("login-popup-submit").update("Reset password"),b["login-popup-"+a]=!0);var c=["login-popup-email-box","login-popup-password-box",
"login-popup-password-confirm-box"].concat(User.messages);current_state=a;a=0;for(var d=c.length;a<d;a++){var e=c[a];b[e]?$(e).show():$(e).hide()}},pending_username:null,form_username_changed:function(a){var b=$("login-popup-username").value;if(b!=User.last_username_in_form)if(User.last_username_in_form=b,User.cancel_check(),User.check_name_timer&&window.clearTimeout(User.check_name_timer),User.pending_username=null,""==b)"tab-login"==User.active_tab?User.set_state("login-blank"):"tab-reset"==User.active_tab&&
User.set_state("reset-blank");else{var c=500;!a&&User.check_name_timer&&(c=0);User.check_name_timer=window.setTimeout(function(){User.check_name_timer=null;User.check(b,null,!0,function(a){a.exists&&$("login-popup-username").value==b&&($("login-popup").focused?User.pending_username=a.name:$("login-popup-username").value=a.name);"tab-login"==User.active_tab?a.exists?User.set_state("login-user-exists"):User.set_state("login-confirm-password"):"tab-reset"==User.active_tab&&(a.exists?a.no_email?User.set_state("reset-user-has-no-email"):
User.set_state("reset-user-exists"):User.set_state("reset-blank"))})},c)}},form_username_focus:function(){$("login-popup").focused=!0},form_username_blur:function(){$("login-popup").focused=!1;User.pending_username&&($("login-popup").username.value=User.pending_username,User.pending_username=null);User.form_username_changed(!1)},form_submitted:function(){User.cancel_check();User.check_name_timer&&window.clearTimeout(User.check_name_timer);var a=$("login-popup-username").value,b=$("login-popup-password").value,
c=$("login-popup-password-confirm").value,d=$("login-popup-email").value;""!=a&&("tab-login"==User.active_tab?""==b?User.message("Please enter a password."):"login-confirm-password"==current_state?b!=c?User.message("The passwords you've entered don't match."):User.create(a,b,null,function(a){"success"==a.response?(User.set_login(a.name,a.pass_hash,a.user_info),User.close(!0)):"error"==a.response&&User.message(a.errors.join("<br>"))}):User.check(a,b,!1,function(a){a.exists?"wrong-password"==a.response?
notice("Incorrect password"):(User.set_login(a.name,a.pass_hash,a.user_info),User.close(!0)):User.set_state("login-confirm-password")}):"tab-reset"==User.active_tab&&""!=d&&User.reset_password(a,d,function(a){"success"==a.result?User.set_state("reset-successful"):"unknown-user"==a.result?User.set_state("reset-unknown-user"):"wrong-email"==a.result?User.set_state("reset-user-email-incorrect"):"no-email"==a.result?User.set_state("reset-user-has-no-email"):"invalid-email"==a.result&&User.set_state("reset-user-email-invalid")}))},
modify_blacklist:function(a,b,c){new Ajax.Request("/user/modify_blacklist.json",{parameters:{"add[]":a,"remove[]":b},onComplete:function(a){a=a.responseJSON;a.success?c&&c(a):notice("Error: "+a.reason)}})},set_pool_browse_mode:function(a){new Ajax.Request("/user/update.json",{parameters:{"user[pool_browse_mode]":a},onComplete:function(a){a=a.responseJSON;a.success?window.location.reload():notice("Error: "+a.reason)}})},get_current_user_info:function(){var a=Cookie.get("user_info");return a?a.split(";"):
null},get_current_user_info_field:function(a,b){var c=User.get_current_user_info();return!c||a>=c.length?b:c[a]},get_current_user_id:function(){return parseInt(User.get_current_user_info_field(0,0))},get_current_user_level:function(){return parseInt(User.get_current_user_info_field(1,0))},get_use_browser:function(){return"1"==User.get_current_user_info_field(2,"0")},is_member_or_higher:function(){return 20<=User.get_current_user_level()},is_mod_or_higher:function(){return 40<=User.get_current_user_level()}};
VoteWidget=function(a){this.container=a;this.post_id=null;this.displayed_set=this.displayed_hover=-1;if(a.down(".vote-up"))a.down(".vote-up").on("click",function(a){a.stop();this.vote_up()}.bindAsEventListener(this));a={0:"Remove vote",1:"Good",2:"Great",3:"Favorite"};for(var b=0;3>=b;++b){var c=this.container.down(".star-"+b);c&&(c.star=b,c.desc=a[b])}this.container.on("click",".star",function(a){a.stop();this.activate_item(a.target)}.bindAsEventListener(this));this.container.on("mouseover",".star",
function(a){this.set_mouseover(a.target)}.bindAsEventListener(this));this.container.on("mouseout",".star",function(a){this.set_mouseover(a.relatedTarget)}.bindAsEventListener(this));document.on("posts:update",this.post_update_event.bindAsEventListener(this))};VoteWidget.prototype.get_star_element=function(a){return a?a.hasClassName("star")?a:a.up(".star"):null};
VoteWidget.prototype.set_mouseover=function(a){a&&(a=this.get_star_element(a));if(a)return this.set_stars(a.star),(b=this.container.down(".vote-desc"))&&b.update(a.desc),!0;this.set_stars(null);var b=this.container.down(".vote-desc");b&&b.update();return!1};VoteWidget.prototype.activate_item=function(a){a=this.get_star_element(a);if(!a)return null;this.vote(a.star);return a.star};
VoteWidget.prototype.post_update_event=function(a){var b=this.post_id;if(null!=a.memo.post_ids.get(b)){this.set_stars(this.displayed_hover);if(this.container.down("#post-score-"+b)){var c=Post.posts.get(b);c&&this.container.down("#post-score-"+b).update(c.score)}a.memo.resp.voted_by&&this.container.down("#favorited-by")&&this.container.down("#favorited-by").update(Favorite.link_to_users(a.memo.resp.voted_by["3"]))}};VoteWidget.prototype.set_post_id=function(a){Post.votes.get(a);this.post_id=a;this.set_stars(null)};
VoteWidget.prototype.init_hotkeys=function(){OnKey(192,null,function(a){this.vote(0);return!0}.bindAsEventListener(this));OnKey(49,null,function(a){this.vote(1);return!0}.bindAsEventListener(this));OnKey(50,null,function(a){this.vote(2);return!0}.bindAsEventListener(this));OnKey(51,null,function(a){this.vote(3);return!0}.bindAsEventListener(this))};VoteWidget.prototype.vote_up=function(){var a=Post.votes.get(this.post_id);return this.vote(a+1)};
VoteWidget.prototype.vote=function(a){return Post.vote(this.post_id,a)};var array_select=function(a,b,c,d){d?a.push(b):a.push(c)};
VoteWidget.prototype.set_stars=function(a){var b=Post.votes.get(this.post_id);if(this.displayed_hover!=a||this.displayed_set!=b){this.displayed_hover=a;this.displayed_set=b;for(var c=0;3>=c;++c){var d=this.container.down(".star-"+c);if(d){var e=d.className,e=e.replace(/(star-hovered|star-unhovered|star-hovered-upto|star-hovered-after|star-set|star-unset|star-set-upto|star-set-after)(\s+|$)/g," "),e=e.strip(),e=e.split(" ");null!=a&&(array_select(e,"star-hovered","star-unhovered",a==c),array_select(e,
"star-hovered-upto","star-hovered-after",a>=c));array_select(e,"star-set","star-unset",null!=b&&b==c);array_select(e,"star-set-upto","star-set-after",null!=b&&b>=c);d.className=e.join(" ")}}}};