//MooTools, <http://mootools.net>, My Object Oriented (JavaScript) Tools. Copyright (c) 2006-2009 Valerio Proietti, <http://mad4milk.net>, MIT Style License.

var MooTools={version:"1.2.3",build:"4980aa0fb74d2f6eb80bcd9f5b8e1fd6fbb8f607"};var Native=function(k){k=k||{};var a=k.name;var i=k.legacy;var b=k.protect;
var c=k.implement;var h=k.generics;var f=k.initialize;var g=k.afterImplement||function(){};var d=f||i;h=h!==false;d.constructor=Native;d.$family={name:"native"};
if(i&&f){d.prototype=i.prototype;}d.prototype.constructor=d;if(a){var e=a.toLowerCase();d.prototype.$family={name:e};Native.typize(d,e);}var j=function(n,l,o,m){if(!b||m||!n.prototype[l]){n.prototype[l]=o;}if(h){Native.genericize(n,l,b);}g.call(n,l,o);return n;};d.alias=function(n,l,p){if(typeof n=="string"){var o=this.prototype[n];if((n=o)){return j(this,l,n,p);
}}for(var m in n){this.alias(m,n[m],l);}return this;};d.implement=function(m,l,o){if(typeof m=="string"){return j(this,m,l,o);}for(var n in m){j(this,n,m[n],l);}return this;};if(c){d.implement(c);}return d;};Native.genericize=function(b,c,a){if((!a||!b[c])&&typeof b.prototype[c]=="function"){b[c]=function(){var d=Array.prototype.slice.call(arguments);
return b.prototype[c].apply(d.shift(),d);};}};Native.implement=function(d,c){for(var b=0,a=d.length;b<a;b++){d[b].implement(c);}};Native.typize=function(a,b){if(!a.type){a.type=function(c){return($type(c)===b);};}};(function(){var a={Array:Array,Date:Date,Function:Function,Number:Number,RegExp:RegExp,String:String};for(var h in a){new Native({name:h,initialize:a[h],protect:true});
}var d={"boolean":Boolean,"native":Native,object:Object};for(var c in d){Native.typize(d[c],c);}var f={Array:["concat","indexOf","join","lastIndexOf","pop","push","reverse","shift","slice","sort","splice","toString","unshift","valueOf"],String:["charAt","charCodeAt","concat","indexOf","lastIndexOf","match","replace","search","slice","split","substr","substring","toLowerCase","toUpperCase","valueOf"]};
for(var e in f){for(var b=f[e].length;b--;){Native.genericize(a[e],f[e][b],true);}}})();var Hash=new Native({name:"Hash",initialize:function(a){if($type(a)=="hash"){a=$unlink(a.getClean());}for(var b in a){this[b]=a[b];}return this;}});Hash.implement({forEach:function(b,c){for(var a in this){if(this.hasOwnProperty(a)){b.call(c,this[a],a,this);}}},getClean:function(){var b={};for(var a in this){if(this.hasOwnProperty(a)){b[a]=this[a];}}return b;},getLength:function(){var b=0;for(var a in this){if(this.hasOwnProperty(a)){b++;}}return b;}});Hash.alias("forEach","each");Array.implement({forEach:function(c,d){for(var b=0,a=this.length;b<a;b++){c.call(d,this[b],b,this);}}});Array.alias("forEach","each");
function $A(b){if(b.item){var a=b.length,c=new Array(a);while(a--){c[a]=b[a];}return c;}return Array.prototype.slice.call(b);}function $arguments(a){return function(){return arguments[a];
};}function $chk(a){return !!(a||a===0);}function $clear(a){clearTimeout(a);clearInterval(a);return null;}function $defined(a){return(a!=undefined);}function $each(c,b,d){var a=$type(c);
((a=="arguments"||a=="collection"||a=="array")?Array:Hash).each(c,b,d);}function $empty(){}function $extend(c,a){for(var b in (a||{})){c[b]=a[b];}return c;
}function $H(a){return new Hash(a);}function $lambda(a){return($type(a)=="function")?a:function(){return a;};}function $merge(){var a=Array.slice(arguments);
a.unshift({});return $mixin.apply(null,a);}function $mixin(e){for(var d=1,a=arguments.length;d<a;d++){var b=arguments[d];if($type(b)!="object"){continue;}for(var c in b){var g=b[c],f=e[c];e[c]=(f&&$type(g)=="object"&&$type(f)=="object")?$mixin(f,g):$unlink(g);}}return e;}function $pick(){for(var b=0,a=arguments.length;
b<a;b++){if(arguments[b]!=undefined){return arguments[b];}}return null;}function $random(b,a){return Math.floor(Math.random()*(a-b+1)+b);}function $splat(b){var a=$type(b);
return(a)?((a!="array"&&a!="arguments")?[b]:b):[];}var $time=Date.now||function(){return +new Date;};function $try(){for(var b=0,a=arguments.length;b<a;
b++){try{return arguments[b]();}catch(c){}}return null;}function $type(a){if(a==undefined){return false;}if(a.$family){return(a.$family.name=="number"&&!isFinite(a))?false:a.$family.name;}if(a.nodeName){switch(a.nodeType){case 1:return"element";case 3:return(/\S/).test(a.nodeValue)?"textnode":"whitespace";}}else{if(typeof a.length=="number"){if(a.callee){return"arguments";}else{if(a.item){return"collection";}}}}return typeof a;}function $unlink(c){var b;switch($type(c)){case"object":b={};for(var e in c){b[e]=$unlink(c[e]);}break;case"hash":b=new Hash(c);break;case"array":b=[];for(var d=0,a=c.length;d<a;d++){b[d]=$unlink(c[d]);}break;default:return c;}return b;}var Browser=$merge({Engine:{name:"unknown",version:0},Platform:{name:(window.orientation!=undefined)?"ipod":(navigator.platform.match(/mac|win|linux/i)||["other"])[0].toLowerCase()},Features:{xpath:!!(document.evaluate),air:!!(window.runtime),query:!!(document.querySelector)},Plugins:{},Engines:{presto:function(){return(!window.opera)?false:((arguments.callee.caller)?960:((document.getElementsByClassName)?950:925));},trident:function(){return(!window.ActiveXObject)?false:((window.XMLHttpRequest)?5:4);},webkit:function(){return(navigator.taintEnabled)?false:((Browser.Features.xpath)?((Browser.Features.query)?525:420):419);},gecko:function(){return(document.getBoxObjectFor==undefined)?false:((document.getElementsByClassName)?19:18);}}},Browser||{});Browser.Platform[Browser.Platform.name]=true;
Browser.detect=function(){for(var b in this.Engines){var a=this.Engines[b]();if(a){this.Engine={name:b,version:a};this.Engine[b]=this.Engine[b+a]=true;
break;}}return{name:b,version:a};};Browser.detect();Browser.Request=function(){return $try(function(){return new XMLHttpRequest();},function(){return new ActiveXObject("MSXML2.XMLHTTP");
});};Browser.Features.xhr=!!(Browser.Request());Browser.Plugins.Flash=(function(){var a=($try(function(){return navigator.plugins["Shockwave Flash"].description;
},function(){return new ActiveXObject("ShockwaveFlash.ShockwaveFlash").GetVariable("$version");})||"0 r0").match(/\d+/g);return{version:parseInt(a[0]||0+"."+a[1],10)||0,build:parseInt(a[2],10)||0};
})();function $exec(b){if(!b){return b;}if(window.execScript){window.execScript(b);}else{var a=document.createElement("script");a.setAttribute("type","text/javascript");
a[(Browser.Engine.webkit&&Browser.Engine.version<420)?"innerText":"text"]=b;document.head.appendChild(a);document.head.removeChild(a);}return b;}Native.UID=1;
var $uid=(Browser.Engine.trident)?function(a){return(a.uid||(a.uid=[Native.UID++]))[0];}:function(a){return a.uid||(a.uid=Native.UID++);};var Window=new Native({name:"Window",legacy:(Browser.Engine.trident)?null:window.Window,initialize:function(a){$uid(a);
if(!a.Element){a.Element=$empty;if(Browser.Engine.webkit){a.document.createElement("iframe");}a.Element.prototype=(Browser.Engine.webkit)?window["[[DOMElement.prototype]]"]:{};}a.document.window=a;return $extend(a,Window.Prototype);},afterImplement:function(b,a){window[b]=Window.Prototype[b]=a;}});Window.Prototype={$family:{name:"window"}};
new Window(window);var Document=new Native({name:"Document",legacy:(Browser.Engine.trident)?null:window.Document,initialize:function(a){$uid(a);a.head=a.getElementsByTagName("head")[0];
a.html=a.getElementsByTagName("html")[0];if(Browser.Engine.trident&&Browser.Engine.version<=4){$try(function(){a.execCommand("BackgroundImageCache",false,true);});}if(Browser.Engine.trident){a.window.attachEvent("onunload",function(){a.window.detachEvent("onunload",arguments.callee);a.head=a.html=a.window=null;});}return $extend(a,Document.Prototype);},afterImplement:function(b,a){document[b]=Document.Prototype[b]=a;}});Document.Prototype={$family:{name:"document"}};
new Document(document);Array.implement({every:function(c,d){for(var b=0,a=this.length;b<a;b++){if(!c.call(d,this[b],b,this)){return false;}}return true;
},filter:function(d,e){var c=[];for(var b=0,a=this.length;b<a;b++){if(d.call(e,this[b],b,this)){c.push(this[b]);}}return c;},clean:function(){return this.filter($defined);
},indexOf:function(c,d){var a=this.length;for(var b=(d<0)?Math.max(0,a+d):d||0;b<a;b++){if(this[b]===c){return b;}}return -1;},map:function(d,e){var c=[];
for(var b=0,a=this.length;b<a;b++){c[b]=d.call(e,this[b],b,this);}return c;},some:function(c,d){for(var b=0,a=this.length;b<a;b++){if(c.call(d,this[b],b,this)){return true;
}}return false;},associate:function(c){var d={},b=Math.min(this.length,c.length);for(var a=0;a<b;a++){d[c[a]]=this[a];}return d;},link:function(c){var a={};
for(var e=0,b=this.length;e<b;e++){for(var d in c){if(c[d](this[e])){a[d]=this[e];delete c[d];break;}}}return a;},contains:function(a,b){return this.indexOf(a,b)!=-1;
},extend:function(c){for(var b=0,a=c.length;b<a;b++){this.push(c[b]);}return this;},getLast:function(){return(this.length)?this[this.length-1]:null;},getRandom:function(){return(this.length)?this[$random(0,this.length-1)]:null;},include:function(a){if(!this.contains(a)){this.push(a);}return this;},combine:function(c){for(var b=0,a=c.length;b<a;b++){this.include(c[b]);}return this;
},erase:function(b){for(var a=this.length;a--;a){if(this[a]===b){this.splice(a,1);}}return this;},empty:function(){this.length=0;return this;},flatten:function(){var d=[];
for(var b=0,a=this.length;b<a;b++){var c=$type(this[b]);if(!c){continue;}d=d.concat((c=="array"||c=="collection"||c=="arguments")?Array.flatten(this[b]):this[b]);
}return d;},hexToRgb:function(b){if(this.length!=3){return null;}var a=this.map(function(c){if(c.length==1){c+=c;}return c.toInt(16);});return(b)?a:"rgb("+a+")";
},rgbToHex:function(d){if(this.length<3){return null;}if(this.length==4&&this[3]==0&&!d){return"transparent";}var b=[];for(var a=0;a<3;a++){var c=(this[a]-0).toString(16);
b.push((c.length==1)?"0"+c:c);}return(d)?b:"#"+b.join("");}});Function.implement({extend:function(a){for(var b in a){this[b]=a[b];}return this;},create:function(b){var a=this;
b=b||{};return function(d){var c=b.arguments;c=(c!=undefined)?$splat(c):Array.slice(arguments,(b.event)?1:0);if(b.event){c=[d||window.event].extend(c);}var e=function(){return a.apply(b.bind||null,c);};if(b.delay){return setTimeout(e,b.delay);}if(b.periodical){return setInterval(e,b.periodical);}if(b.attempt){return $try(e);
}return e();};},run:function(a,b){return this.apply(b,$splat(a));},pass:function(a,b){return this.create({bind:b,arguments:a});},bind:function(b,a){return this.create({bind:b,arguments:a});
},bindWithEvent:function(b,a){return this.create({bind:b,arguments:a,event:true});},attempt:function(a,b){return this.create({bind:b,arguments:a,attempt:true})();
},delay:function(b,c,a){return this.create({bind:c,arguments:a,delay:b})();},periodical:function(c,b,a){return this.create({bind:b,arguments:a,periodical:c})();
}});Number.implement({limit:function(b,a){return Math.min(a,Math.max(b,this));},round:function(a){a=Math.pow(10,a||0);return Math.round(this*a)/a;},times:function(b,c){for(var a=0;
a<this;a++){b.call(c,a,this);}},toFloat:function(){return parseFloat(this);},toInt:function(a){return parseInt(this,a||10);}});Number.alias("times","each");
(function(b){var a={};b.each(function(c){if(!Number[c]){a[c]=function(){return Math[c].apply(null,[this].concat($A(arguments)));};}});Number.implement(a);
})(["abs","acos","asin","atan","atan2","ceil","cos","exp","floor","log","max","min","pow","sin","sqrt","tan"]);String.implement({test:function(a,b){return((typeof a=="string")?new RegExp(a,b):a).test(this);
},contains:function(a,b){return(b)?(b+this+b).indexOf(b+a+b)>-1:this.indexOf(a)>-1;},trim:function(){return this.replace(/^\s+|\s+$/g,"");},clean:function(){return this.replace(/\s+/g," ").trim();
},camelCase:function(){return this.replace(/-\D/g,function(a){return a.charAt(1).toUpperCase();});},hyphenate:function(){return this.replace(/[A-Z]/g,function(a){return("-"+a.charAt(0).toLowerCase());});},capitalize:function(){return this.replace(/\b[a-z]/g,function(a){return a.toUpperCase();});},escapeRegExp:function(){return this.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1");},toInt:function(a){return parseInt(this,a||10);},toFloat:function(){return parseFloat(this);},hexToRgb:function(b){var a=this.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);
return(a)?a.slice(1).hexToRgb(b):null;},rgbToHex:function(b){var a=this.match(/\d{1,3}/g);return(a)?a.rgbToHex(b):null;},stripScripts:function(b){var a="";
var c=this.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi,function(){a+=arguments[1]+"\n";return"";});if(b===true){$exec(a);}else{if($type(b)=="function"){b(a,c);}}return c;},substitute:function(a,b){return this.replace(b||(/\\?\{([^{}]+)\}/g),function(d,c){if(d.charAt(0)=="\\"){return d.slice(1);}return(a[c]!=undefined)?a[c]:"";
});}});Hash.implement({has:Object.prototype.hasOwnProperty,keyOf:function(b){for(var a in this){if(this.hasOwnProperty(a)&&this[a]===b){return a;}}return null;
},hasValue:function(a){return(Hash.keyOf(this,a)!==null);},extend:function(a){Hash.each(a||{},function(c,b){Hash.set(this,b,c);},this);return this;},combine:function(a){Hash.each(a||{},function(c,b){Hash.include(this,b,c);},this);return this;},erase:function(a){if(this.hasOwnProperty(a)){delete this[a];}return this;},get:function(a){return(this.hasOwnProperty(a))?this[a]:null;},set:function(a,b){if(!this[a]||this.hasOwnProperty(a)){this[a]=b;}return this;},empty:function(){Hash.each(this,function(b,a){delete this[a];},this);
return this;},include:function(a,b){if(this[a]==undefined){this[a]=b;}return this;},map:function(b,c){var a=new Hash;Hash.each(this,function(e,d){a.set(d,b.call(c,e,d,this));},this);return a;},filter:function(b,c){var a=new Hash;Hash.each(this,function(e,d){if(b.call(c,e,d,this)){a.set(d,e);}},this);return a;},every:function(b,c){for(var a in this){if(this.hasOwnProperty(a)&&!b.call(c,this[a],a)){return false;
}}return true;},some:function(b,c){for(var a in this){if(this.hasOwnProperty(a)&&b.call(c,this[a],a)){return true;}}return false;},getKeys:function(){var a=[];
Hash.each(this,function(c,b){a.push(b);});return a;},getValues:function(){var a=[];Hash.each(this,function(b){a.push(b);});return a;},toQueryString:function(a){var b=[];
Hash.each(this,function(f,e){if(a){e=a+"["+e+"]";}var d;switch($type(f)){case"object":d=Hash.toQueryString(f,e);break;case"array":var c={};f.each(function(h,g){c[g]=h;});d=Hash.toQueryString(c,e);break;default:d=e+"="+encodeURIComponent(f);}if(f!=undefined){b.push(d);}});return b.join("&");}});Hash.alias({keyOf:"indexOf",hasValue:"contains"});
var Event=new Native({name:"Event",initialize:function(a,f){f=f||window;var k=f.document;a=a||f.event;if(a.$extended){return a;}this.$extended=true;var j=a.type;
var g=a.target||a.srcElement;while(g&&g.nodeType==3){g=g.parentNode;}if(j.test(/key/)){var b=a.which||a.keyCode;var m=Event.Keys.keyOf(b);if(j=="keydown"){var d=b-111;
if(d>0&&d<13){m="f"+d;}}m=m||String.fromCharCode(b).toLowerCase();}else{if(j.match(/(click|mouse|menu)/i)){k=(!k.compatMode||k.compatMode=="CSS1Compat")?k.html:k.body;
var i={x:a.pageX||a.clientX+k.scrollLeft,y:a.pageY||a.clientY+k.scrollTop};var c={x:(a.pageX)?a.pageX-f.pageXOffset:a.clientX,y:(a.pageY)?a.pageY-f.pageYOffset:a.clientY};
if(j.match(/DOMMouseScroll|mousewheel/)){var h=(a.wheelDelta)?a.wheelDelta/120:-(a.detail||0)/3;}var e=(a.which==3)||(a.button==2);var l=null;if(j.match(/over|out/)){switch(j){case"mouseover":l=a.relatedTarget||a.fromElement;
break;case"mouseout":l=a.relatedTarget||a.toElement;}if(!(function(){while(l&&l.nodeType==3){l=l.parentNode;}return true;}).create({attempt:Browser.Engine.gecko})()){l=false;}}}}return $extend(this,{event:a,type:j,page:i,client:c,rightClick:e,wheel:h,relatedTarget:l,target:g,code:b,key:m,shift:a.shiftKey,control:a.ctrlKey,alt:a.altKey,meta:a.metaKey});
}});Event.Keys=new Hash({enter:13,up:38,down:40,left:37,right:39,esc:27,space:32,backspace:8,tab:9,"delete":46});Event.implement({stop:function(){return this.stopPropagation().preventDefault();
},stopPropagation:function(){if(this.event.stopPropagation){this.event.stopPropagation();}else{this.event.cancelBubble=true;}return this;},preventDefault:function(){if(this.event.preventDefault){this.event.preventDefault();}else{this.event.returnValue=false;}return this;}});function Class(b){if(b instanceof Function){b={initialize:b};}var a=function(){Object.reset(this);if(a._prototyping){return this;
}this._current=$empty;var c=(this.initialize)?this.initialize.apply(this,arguments):this;delete this._current;delete this.caller;return c;}.extend(this);
a.implement(b);a.constructor=Class;a.prototype.constructor=a;return a;}Function.prototype.protect=function(){this._protected=true;return this;};Object.reset=function(a,c){if(c==null){for(var e in a){Object.reset(a,e);}return a;}delete a[c];switch($type(a[c])){case"object":var d=function(){};d.prototype=a[c];var b=new d;a[c]=Object.reset(b);break;case"array":a[c]=$unlink(a[c]);
break;}return a;};new Native({name:"Class",initialize:Class}).extend({instantiate:function(b){b._prototyping=true;var a=new b;delete b._prototyping;return a;
},wrap:function(a,b,c){if(c._origin){c=c._origin;}return function(){if(c._protected&&this._current==null){throw new Error('The method "'+b+'" cannot be called.');
}var e=this.caller,f=this._current;this.caller=f;this._current=arguments.callee;var d=c.apply(this,arguments);this._current=f;this.caller=e;return d;}.extend({_owner:a,_origin:c,_name:b});
}});Class.implement({implement:function(a,d){if($type(a)=="object"){for(var e in a){this.implement(e,a[e]);}return this;}var f=Class.Mutators[a];if(f){d=f.call(this,d);
if(d==null){return this;}}var c=this.prototype;switch($type(d)){case"function":if(d._hidden){return this;}c[a]=Class.wrap(this,a,d);break;case"object":var b=c[a];
if($type(b)=="object"){$mixin(b,d);}else{c[a]=$unlink(d);}break;case"array":c[a]=$unlink(d);break;default:c[a]=d;}return this;}});Class.Mutators={Extends:function(a){this.parent=a;
this.prototype=Class.instantiate(a);this.implement("parent",function(){var b=this.caller._name,c=this.caller._owner.parent.prototype[b];if(!c){throw new Error('The method "'+b+'" has no parent.');
}return c.apply(this,arguments);}.protect());},Implements:function(a){$splat(a).each(function(b){if(b instanceof Function){b=Class.instantiate(b);}this.implement(b);
},this);}};var Chain=new Class({$chain:[],chain:function(){this.$chain.extend(Array.flatten(arguments));return this;},callChain:function(){return(this.$chain.length)?this.$chain.shift().apply(this,arguments):false;},clearChain:function(){this.$chain.empty();return this;}});var Events=new Class({$events:{},addEvent:function(c,b,a){c=Events.removeOn(c);if(b!=$empty){this.$events[c]=this.$events[c]||[];
this.$events[c].include(b);if(a){b.internal=true;}}return this;},addEvents:function(a){for(var b in a){this.addEvent(b,a[b]);}return this;},fireEvent:function(c,b,a){c=Events.removeOn(c);
if(!this.$events||!this.$events[c]){return this;}this.$events[c].each(function(d){d.create({bind:this,delay:a,"arguments":b})();},this);return this;},removeEvent:function(b,a){b=Events.removeOn(b);
if(!this.$events[b]){return this;}if(!a.internal){this.$events[b].erase(a);}return this;},removeEvents:function(c){var d;if($type(c)=="object"){for(d in c){this.removeEvent(d,c[d]);}return this;}if(c){c=Events.removeOn(c);}for(d in this.$events){if(c&&c!=d){continue;}var b=this.$events[d];for(var a=b.length;a--;a){this.removeEvent(d,b[a]);}}return this;}});Events.removeOn=function(a){return a.replace(/^on([A-Z])/,function(b,c){return c.toLowerCase();});};var Options=new Class({setOptions:function(){this.options=$merge.run([this.options].extend(arguments));
if(!this.addEvent){return this;}for(var a in this.options){if($type(this.options[a])!="function"||!(/^on[A-Z]/).test(a)){continue;}this.addEvent(a,this.options[a]);
delete this.options[a];}return this;}});var Element=new Native({name:"Element",legacy:window.Element,initialize:function(a,b){var c=Element.Constructors.get(a);
if(c){return c(b);}if(typeof a=="string"){return document.newElement(a,b);}return document.id(a).set(b);},afterImplement:function(a,b){Element.Prototype[a]=b;
if(Array[a]){return;}Elements.implement(a,function(){var c=[],g=true;for(var e=0,d=this.length;e<d;e++){var f=this[e][a].apply(this[e],arguments);c.push(f);
if(g){g=($type(f)=="element");}}return(g)?new Elements(c):c;});}});Element.Prototype={$family:{name:"element"}};Element.Constructors=new Hash;var IFrame=new Native({name:"IFrame",generics:false,initialize:function(){var f=Array.link(arguments,{properties:Object.type,iframe:$defined});
var d=f.properties||{};var c=document.id(f.iframe);var e=d.onload||$empty;delete d.onload;d.id=d.name=$pick(d.id,d.name,c?(c.id||c.name):"IFrame_"+$time());
c=new Element(c||"iframe",d);var b=function(){var g=$try(function(){return c.contentWindow.location.host;});if(!g||g==window.location.host){var h=new Window(c.contentWindow);
new Document(c.contentWindow.document);$extend(h.Element.prototype,Element.Prototype);}e.call(c.contentWindow,c.contentWindow.document);};var a=$try(function(){return c.contentWindow;
});((a&&a.document.body)||window.frames[d.id])?b():c.addListener("load",b);return c;}});var Elements=new Native({initialize:function(f,b){b=$extend({ddup:true,cash:true},b);
f=f||[];if(b.ddup||b.cash){var g={},e=[];for(var c=0,a=f.length;c<a;c++){var d=document.id(f[c],!b.cash);if(b.ddup){if(g[d.uid]){continue;}g[d.uid]=true;
}e.push(d);}f=e;}return(b.cash)?$extend(f,this):f;}});Elements.implement({filter:function(a,b){if(!a){return this;}return new Elements(Array.filter(this,(typeof a=="string")?function(c){return c.match(a);
}:a,b));}});Document.implement({newElement:function(a,b){if(Browser.Engine.trident&&b){["name","type","checked"].each(function(c){if(!b[c]){return;}a+=" "+c+'="'+b[c]+'"';
if(c!="checked"){delete b[c];}});a="<"+a+">";}return document.id(this.createElement(a)).set(b);},newTextNode:function(a){return this.createTextNode(a);
},getDocument:function(){return this;},getWindow:function(){return this.window;},id:(function(){var a={string:function(d,c,b){d=b.getElementById(d);return(d)?a.element(d,c):null;},element:function(b,e){$uid(b);if(!e&&!b.$family&&!(/^object|embed$/i).test(b.tagName)){var c=Element.Prototype;for(var d in c){b[d]=c[d];}}return b;},object:function(c,d,b){if(c.toElement){return a.element(c.toElement(b),d);
}return null;}};a.textnode=a.whitespace=a.window=a.document=$arguments(0);return function(c,e,d){if(c&&c.$family&&c.uid){return c;}var b=$type(c);return(a[b])?a[b](c,e,d||document):null;
};})()});if(window.$==null){Window.implement({$:function(a,b){return document.id(a,b,this.document);}});}Window.implement({$$:function(a){if(arguments.length==1&&typeof a=="string"){return this.document.getElements(a);
}var f=[];var c=Array.flatten(arguments);for(var d=0,b=c.length;d<b;d++){var e=c[d];switch($type(e)){case"element":f.push(e);break;case"string":f.extend(this.document.getElements(e,true));}}return new Elements(f);},getDocument:function(){return this.document;},getWindow:function(){return this;}});Native.implement([Element,Document],{getElement:function(a,b){return document.id(this.getElements(a,true)[0]||null,b);
},getElements:function(a,d){a=a.split(",");var c=[];var b=(a.length>1);a.each(function(e){var f=this.getElementsByTagName(e.trim());(b)?c.extend(f):c=f;
},this);return new Elements(c,{ddup:b,cash:!d});}});(function(){var h={},f={};var i={input:"checked",option:"selected",textarea:(Browser.Engine.webkit&&Browser.Engine.version<420)?"innerHTML":"value"};
var c=function(l){return(f[l]||(f[l]={}));};var g=function(n,l){if(!n){return;}var m=n.uid;if(Browser.Engine.trident){if(n.clearAttributes){var q=l&&n.cloneNode(false);
n.clearAttributes();if(q){n.mergeAttributes(q);}}else{if(n.removeEvents){n.removeEvents();}}if((/object/i).test(n.tagName)){for(var o in n){if(typeof n[o]=="function"){n[o]=$empty;}}Element.dispose(n);}}if(!m){return;}h[m]=f[m]=null;};var d=function(){Hash.each(h,g);if(Browser.Engine.trident){$A(document.getElementsByTagName("object")).each(g);}if(window.CollectGarbage){CollectGarbage();}h=f=null;};var j=function(n,l,s,m,p,r){var o=n[s||l];var q=[];while(o){if(o.nodeType==1&&(!m||Element.match(o,m))){if(!p){return document.id(o,r);
}q.push(o);}o=o[l];}return(p)?new Elements(q,{ddup:false,cash:!r}):null;};var e={html:"innerHTML","class":"className","for":"htmlFor",defaultValue:"defaultValue",text:(Browser.Engine.trident||(Browser.Engine.webkit&&Browser.Engine.version<420))?"innerText":"textContent"};
var b=["compact","nowrap","ismap","declare","noshade","checked","disabled","readonly","multiple","selected","noresize","defer"];var k=["value","type","defaultValue","accessKey","cellPadding","cellSpacing","colSpan","frameBorder","maxLength","readOnly","rowSpan","tabIndex","useMap"];
b=b.associate(b);Hash.extend(e,b);Hash.extend(e,k.associate(k.map(String.toLowerCase)));var a={before:function(m,l){if(l.parentNode){l.parentNode.insertBefore(m,l);}},after:function(m,l){if(!l.parentNode){return;}var n=l.nextSibling;(n)?l.parentNode.insertBefore(m,n):l.parentNode.appendChild(m);},bottom:function(m,l){l.appendChild(m);},top:function(m,l){var n=l.firstChild;(n)?l.insertBefore(m,n):l.appendChild(m);}};a.inside=a.bottom;Hash.each(a,function(l,m){m=m.capitalize();Element.implement("inject"+m,function(n){l(this,document.id(n,true));
return this;});Element.implement("grab"+m,function(n){l(document.id(n,true),this);return this;});});Element.implement({set:function(o,m){switch($type(o)){case"object":for(var n in o){this.set(n,o[n]);}break;case"string":var l=Element.Properties.get(o);(l&&l.set)?l.set.apply(this,Array.slice(arguments,1)):this.setProperty(o,m);}return this;},get:function(m){var l=Element.Properties.get(m);
return(l&&l.get)?l.get.apply(this,Array.slice(arguments,1)):this.getProperty(m);},erase:function(m){var l=Element.Properties.get(m);(l&&l.erase)?l.erase.apply(this):this.removeProperty(m);
return this;},setProperty:function(m,n){var l=e[m];if(n==undefined){return this.removeProperty(m);}if(l&&b[m]){n=!!n;}(l)?this[l]=n:this.setAttribute(m,""+n);
return this;},setProperties:function(l){for(var m in l){this.setProperty(m,l[m]);}return this;},getProperty:function(m){var l=e[m];var n=(l)?this[l]:this.getAttribute(m,2);
return(b[m])?!!n:(l)?n:n||null;},getProperties:function(){var l=$A(arguments);return l.map(this.getProperty,this).associate(l);},removeProperty:function(m){var l=e[m];
(l)?this[l]=(l&&b[m])?false:"":this.removeAttribute(m);return this;},removeProperties:function(){Array.each(arguments,this.removeProperty,this);return this;
},hasClass:function(l){return this.className.contains(l," ");},addClass:function(l){if(!this.hasClass(l)){this.className=(this.className+" "+l).clean();
}return this;},removeClass:function(l){this.className=this.className.replace(new RegExp("(^|\\s)"+l+"(?:\\s|$)"),"$1");return this;},toggleClass:function(l){return this.hasClass(l)?this.removeClass(l):this.addClass(l);
},adopt:function(){Array.flatten(arguments).each(function(l){l=document.id(l,true);if(l){this.appendChild(l);}},this);return this;},appendText:function(m,l){return this.grab(this.getDocument().newTextNode(m),l);
},grab:function(m,l){a[l||"bottom"](document.id(m,true),this);return this;},inject:function(m,l){a[l||"bottom"](this,document.id(m,true));return this;},replaces:function(l){l=document.id(l,true);
l.parentNode.replaceChild(this,l);return this;},wraps:function(m,l){m=document.id(m,true);return this.replaces(m).grab(m,l);},getPrevious:function(l,m){return j(this,"previousSibling",null,l,false,m);
},getAllPrevious:function(l,m){return j(this,"previousSibling",null,l,true,m);},getNext:function(l,m){return j(this,"nextSibling",null,l,false,m);},getAllNext:function(l,m){return j(this,"nextSibling",null,l,true,m);
},getFirst:function(l,m){return j(this,"nextSibling","firstChild",l,false,m);},getLast:function(l,m){return j(this,"previousSibling","lastChild",l,false,m);
},getParent:function(l,m){return j(this,"parentNode",null,l,false,m);},getParents:function(l,m){return j(this,"parentNode",null,l,true,m);},getSiblings:function(l,m){return this.getParent().getChildren(l,m).erase(this);
},getChildren:function(l,m){return j(this,"nextSibling","firstChild",l,true,m);},getWindow:function(){return this.ownerDocument.window;},getDocument:function(){return this.ownerDocument;
},getElementById:function(o,n){var m=this.ownerDocument.getElementById(o);if(!m){return null;}for(var l=m.parentNode;l!=this;l=l.parentNode){if(!l){return null;
}}return document.id(m,n);},getSelected:function(){return new Elements($A(this.options).filter(function(l){return l.selected;}));},getComputedStyle:function(m){if(this.currentStyle){return this.currentStyle[m.camelCase()];
}var l=this.getDocument().defaultView.getComputedStyle(this,null);return(l)?l.getPropertyValue([m.hyphenate()]):null;},toQueryString:function(){var l=[];
this.getElements("input, select, textarea",true).each(function(m){if(!m.name||m.disabled||m.type=="submit"||m.type=="reset"||m.type=="file"){return;}var n=(m.tagName.toLowerCase()=="select")?Element.getSelected(m).map(function(o){return o.value;
}):((m.type=="radio"||m.type=="checkbox")&&!m.checked)?null:m.value;$splat(n).each(function(o){if(typeof o!="undefined"){l.push(m.name+"="+encodeURIComponent(o));}});});return l.join("&");},clone:function(o,l){o=o!==false;var r=this.cloneNode(o);var n=function(v,u){if(!l){v.removeAttribute("id");}if(Browser.Engine.trident){v.clearAttributes();
v.mergeAttributes(u);v.removeAttribute("uid");if(v.options){var w=v.options,s=u.options;for(var t=w.length;t--;){w[t].selected=s[t].selected;}}}var x=i[u.tagName.toLowerCase()];
if(x&&u[x]){v[x]=u[x];}};if(o){var p=r.getElementsByTagName("*"),q=this.getElementsByTagName("*");for(var m=p.length;m--;){n(p[m],q[m]);}}n(r,this);return document.id(r);
},destroy:function(){Element.empty(this);Element.dispose(this);g(this,true);return null;},empty:function(){$A(this.childNodes).each(function(l){Element.destroy(l);});return this;},dispose:function(){return(this.parentNode)?this.parentNode.removeChild(this):this;},hasChild:function(l){l=document.id(l,true);if(!l){return false;
}if(Browser.Engine.webkit&&Browser.Engine.version<420){return $A(this.getElementsByTagName(l.tagName)).contains(l);}return(this.contains)?(this!=l&&this.contains(l)):!!(this.compareDocumentPosition(l)&16);
},match:function(l){return(!l||(l==this)||(Element.get(this,"tag")==l));}});Native.implement([Element,Window,Document],{addListener:function(o,n){if(o=="unload"){var l=n,m=this;
n=function(){m.removeListener("unload",n);l();};}else{h[this.uid]=this;}if(this.addEventListener){this.addEventListener(o,n,false);}else{this.attachEvent("on"+o,n);}return this;},removeListener:function(m,l){if(this.removeEventListener){this.removeEventListener(m,l,false);}else{this.detachEvent("on"+m,l);}return this;
},retrieve:function(m,l){var o=c(this.uid),n=o[m];if(l!=undefined&&n==undefined){n=o[m]=l;}return $pick(n);},store:function(m,l){var n=c(this.uid);n[m]=l;
return this;},eliminate:function(l){var m=c(this.uid);delete m[l];return this;}});window.addListener("unload",d);})();Element.Properties=new Hash;Element.Properties.style={set:function(a){this.style.cssText=a;},get:function(){return this.style.cssText;},erase:function(){this.style.cssText="";}};Element.Properties.tag={get:function(){return this.tagName.toLowerCase();
}};Element.Properties.html=(function(){var c=document.createElement("div");var a={table:[1,"<table>","</table>"],select:[1,"<select>","</select>"],tbody:[2,"<table><tbody>","</tbody></table>"],tr:[3,"<table><tbody><tr>","</tr></tbody></table>"]};
a.thead=a.tfoot=a.tbody;var b={set:function(){var e=Array.flatten(arguments).join("");var f=Browser.Engine.trident&&a[this.get("tag")];if(f){var g=c;g.innerHTML=f[1]+e+f[2];
for(var d=f[0];d--;){g=g.firstChild;}this.empty().adopt(g.childNodes);}else{this.innerHTML=e;}}};b.erase=b.set;return b;})();if(Browser.Engine.webkit&&Browser.Engine.version<420){Element.Properties.text={get:function(){if(this.innerText){return this.innerText;
}var a=this.ownerDocument.newElement("div",{html:this.innerHTML}).inject(this.ownerDocument.body);var b=a.innerText;a.destroy();return b;}};}Element.Properties.events={set:function(a){this.addEvents(a);}};Native.implement([Element,Window,Document],{addEvent:function(e,g){var h=this.retrieve("events",{});h[e]=h[e]||{keys:[],values:[]};if(h[e].keys.contains(g)){return this;
}h[e].keys.push(g);var f=e,a=Element.Events.get(e),c=g,i=this;if(a){if(a.onAdd){a.onAdd.call(this,g);}if(a.condition){c=function(j){if(a.condition.call(this,j)){return g.call(this,j);
}return true;};}f=a.base||f;}var d=function(){return g.call(i);};var b=Element.NativeEvents[f];if(b){if(b==2){d=function(j){j=new Event(j,i.getWindow());
if(c.call(i,j)===false){j.stop();}};}this.addListener(f,d);}h[e].values.push(d);return this;},removeEvent:function(c,b){var a=this.retrieve("events");if(!a||!a[c]){return this;
}var f=a[c].keys.indexOf(b);if(f==-1){return this;}a[c].keys.splice(f,1);var e=a[c].values.splice(f,1)[0];var d=Element.Events.get(c);if(d){if(d.onRemove){d.onRemove.call(this,b);}c=d.base||c;}return(Element.NativeEvents[c])?this.removeListener(c,e):this;},addEvents:function(a){for(var b in a){this.addEvent(b,a[b]);}return this;
},removeEvents:function(a){var c;if($type(a)=="object"){for(c in a){this.removeEvent(c,a[c]);}return this;}var b=this.retrieve("events");if(!b){return this;
}if(!a){for(c in b){this.removeEvents(c);}this.eliminate("events");}else{if(b[a]){while(b[a].keys[0]){this.removeEvent(a,b[a].keys[0]);}b[a]=null;}}return this;
},fireEvent:function(d,b,a){var c=this.retrieve("events");if(!c||!c[d]){return this;}c[d].keys.each(function(e){e.create({bind:this,delay:a,"arguments":b})();
},this);return this;},cloneEvents:function(d,a){d=document.id(d);var c=d.retrieve("events");if(!c){return this;}if(!a){for(var b in c){this.cloneEvents(d,b);}}else{if(c[a]){c[a].keys.each(function(e){this.addEvent(a,e);},this);}}return this;}});Element.NativeEvents={click:2,dblclick:2,mouseup:2,mousedown:2,contextmenu:2,mousewheel:2,DOMMouseScroll:2,mouseover:2,mouseout:2,mousemove:2,selectstart:2,selectend:2,keydown:2,keypress:2,keyup:2,focus:2,blur:2,change:2,reset:2,select:2,submit:2,load:1,unload:1,beforeunload:2,resize:1,move:1,DOMContentLoaded:1,readystatechange:1,error:1,abort:1,scroll:1};
(function(){var a=function(b){var c=b.relatedTarget;if(c==undefined){return true;}if(c===false){return false;}return($type(this)!="document"&&c!=this&&c.prefix!="xul"&&!this.hasChild(c));
};Element.Events=new Hash({mouseenter:{base:"mouseover",condition:a},mouseleave:{base:"mouseout",condition:a},mousewheel:{base:(Browser.Engine.gecko)?"DOMMouseScroll":"mousewheel"}});
})();Element.Properties.styles={set:function(a){this.setStyles(a);}};Element.Properties.opacity={set:function(a,b){if(!b){if(a==0){if(this.style.visibility!="hidden"){this.style.visibility="hidden";}}else{if(this.style.visibility!="visible"){this.style.visibility="visible";}}}if(!this.currentStyle||!this.currentStyle.hasLayout){this.style.zoom=1;}if(Browser.Engine.trident){this.style.filter=(a==1)?"":"alpha(opacity="+a*100+")";}this.style.opacity=a;this.store("opacity",a);},get:function(){return this.retrieve("opacity",1);}};Element.implement({setOpacity:function(a){return this.set("opacity",a,true);
},getOpacity:function(){return this.get("opacity");},setStyle:function(b,a){switch(b){case"opacity":return this.set("opacity",parseFloat(a));case"float":b=(Browser.Engine.trident)?"styleFloat":"cssFloat";
}b=b.camelCase();if($type(a)!="string"){var c=(Element.Styles.get(b)||"@").split(" ");a=$splat(a).map(function(e,d){if(!c[d]){return"";}return($type(e)=="number")?c[d].replace("@",Math.round(e)):e;
}).join(" ");}else{if(a==String(Number(a))){a=Math.round(a);}}this.style[b]=a;return this;},getStyle:function(g){switch(g){case"opacity":return this.get("opacity");
case"float":g=(Browser.Engine.trident)?"styleFloat":"cssFloat";}g=g.camelCase();var a=this.style[g];if(!$chk(a)){a=[];for(var f in Element.ShortStyles){if(g!=f){continue;}for(var e in Element.ShortStyles[f]){a.push(this.getStyle(e));}return a.join(" ");}a=this.getComputedStyle(g);}if(a){a=String(a);var c=a.match(/rgba?\([\d\s,]+\)/);
if(c){a=a.replace(c[0],c[0].rgbToHex());}}if(Browser.Engine.presto||(Browser.Engine.trident&&!$chk(parseInt(a,10)))){if(g.test(/^(height|width)$/)){var b=(g=="width")?["left","right"]:["top","bottom"],d=0;
b.each(function(h){d+=this.getStyle("border-"+h+"-width").toInt()+this.getStyle("padding-"+h).toInt();},this);return this["offset"+g.capitalize()]-d+"px";
}if((Browser.Engine.presto)&&String(a).test("px")){return a;}if(g.test(/(border(.+)Width|margin|padding)/)){return"0px";}}return a;},setStyles:function(b){for(var a in b){this.setStyle(a,b[a]);}return this;},getStyles:function(){var a={};Array.flatten(arguments).each(function(b){a[b]=this.getStyle(b);},this);return a;}});Element.Styles=new Hash({left:"@px",top:"@px",bottom:"@px",right:"@px",width:"@px",height:"@px",maxWidth:"@px",maxHeight:"@px",minWidth:"@px",minHeight:"@px",backgroundColor:"rgb(@, @, @)",backgroundPosition:"@px @px",color:"rgb(@, @, @)",fontSize:"@px",letterSpacing:"@px",lineHeight:"@px",clip:"rect(@px @px @px @px)",margin:"@px @px @px @px",padding:"@px @px @px @px",border:"@px @ rgb(@, @, @) @px @ rgb(@, @, @) @px @ rgb(@, @, @)",borderWidth:"@px @px @px @px",borderStyle:"@ @ @ @",borderColor:"rgb(@, @, @) rgb(@, @, @) rgb(@, @, @) rgb(@, @, @)",zIndex:"@",zoom:"@",fontWeight:"@",textIndent:"@px",opacity:"@"});
Element.ShortStyles={margin:{},padding:{},border:{},borderWidth:{},borderStyle:{},borderColor:{}};["Top","Right","Bottom","Left"].each(function(g){var f=Element.ShortStyles;
var b=Element.Styles;["margin","padding"].each(function(h){var i=h+g;f[h][i]=b[i]="@px";});var e="border"+g;f.border[e]=b[e]="@px @ rgb(@, @, @)";var d=e+"Width",a=e+"Style",c=e+"Color";
f[e]={};f.borderWidth[d]=f[e][d]=b[d]="@px";f.borderStyle[a]=f[e][a]=b[a]="@";f.borderColor[c]=f[e][c]=b[c]="rgb(@, @, @)";});(function(){Element.implement({scrollTo:function(h,i){if(b(this)){this.getWindow().scrollTo(h,i);}else{this.scrollLeft=h;this.scrollTop=i;}return this;},getSize:function(){if(b(this)){return this.getWindow().getSize();}return{x:this.offsetWidth,y:this.offsetHeight};
},getScrollSize:function(){if(b(this)){return this.getWindow().getScrollSize();}return{x:this.scrollWidth,y:this.scrollHeight};},getScroll:function(){if(b(this)){return this.getWindow().getScroll();
}return{x:this.scrollLeft,y:this.scrollTop};},getScrolls:function(){var i=this,h={x:0,y:0};while(i&&!b(i)){h.x+=i.scrollLeft;h.y+=i.scrollTop;i=i.parentNode;}return h;},getOffsetParent:function(){var h=this;if(b(h)){return null;}if(!Browser.Engine.trident){return h.offsetParent;}while((h=h.parentNode)&&!b(h)){if(d(h,"position")!="static"){return h;
}}return null;},getOffsets:function(){if(this.getBoundingClientRect){var m=this.getBoundingClientRect(),k=document.id(this.getDocument().documentElement),i=k.getScroll(),n=(d(this,"position")=="fixed");
return{x:parseInt(m.left,10)+((n)?0:i.x)-k.clientLeft,y:parseInt(m.top,10)+((n)?0:i.y)-k.clientTop};}var j=this,h={x:0,y:0};if(b(this)){return h;}while(j&&!b(j)){h.x+=j.offsetLeft;
h.y+=j.offsetTop;if(Browser.Engine.gecko){if(!f(j)){h.x+=c(j);h.y+=g(j);}var l=j.parentNode;if(l&&d(l,"overflow")!="visible"){h.x+=c(l);h.y+=g(l);}}else{if(j!=this&&Browser.Engine.webkit){h.x+=c(j);
h.y+=g(j);}}j=j.offsetParent;}if(Browser.Engine.gecko&&!f(this)){h.x-=c(this);h.y-=g(this);}return h;},getPosition:function(k){if(b(this)){return{x:0,y:0};
}var l=this.getOffsets(),i=this.getScrolls();var h={x:l.x-i.x,y:l.y-i.y};var j=(k&&(k=document.id(k)))?k.getPosition():{x:0,y:0};return{x:h.x-j.x,y:h.y-j.y};
},getCoordinates:function(j){if(b(this)){return this.getWindow().getCoordinates();}var h=this.getPosition(j),i=this.getSize();var k={left:h.x,top:h.y,width:i.x,height:i.y};
k.right=k.left+k.width;k.bottom=k.top+k.height;return k;},computePosition:function(h){return{left:h.x-e(this,"margin-left"),top:h.y-e(this,"margin-top")};
},setPosition:function(h){return this.setStyles(this.computePosition(h));}});Native.implement([Document,Window],{getSize:function(){if(Browser.Engine.presto||Browser.Engine.webkit){var i=this.getWindow();
return{x:i.innerWidth,y:i.innerHeight};}var h=a(this);return{x:h.clientWidth,y:h.clientHeight};},getScroll:function(){var i=this.getWindow(),h=a(this);
return{x:i.pageXOffset||h.scrollLeft,y:i.pageYOffset||h.scrollTop};},getScrollSize:function(){var i=a(this),h=this.getSize();return{x:Math.max(i.scrollWidth,h.x),y:Math.max(i.scrollHeight,h.y)};
},getPosition:function(){return{x:0,y:0};},getCoordinates:function(){var h=this.getSize();return{top:0,left:0,bottom:h.y,right:h.x,height:h.y,width:h.x};
}});var d=Element.getComputedStyle;function e(h,i){return d(h,i).toInt()||0;}function f(h){return d(h,"-moz-box-sizing")=="border-box";}function g(h){return e(h,"border-top-width");
}function c(h){return e(h,"border-left-width");}function b(h){return(/^(?:body|html)$/i).test(h.tagName);}function a(h){var i=h.getDocument();return(!i.compatMode||i.compatMode=="CSS1Compat")?i.html:i.body;
}})();Element.alias("setPosition","position");Native.implement([Window,Document,Element],{getHeight:function(){return this.getSize().y;},getWidth:function(){return this.getSize().x;
},getScrollTop:function(){return this.getScroll().y;},getScrollLeft:function(){return this.getScroll().x;},getScrollHeight:function(){return this.getScrollSize().y;
},getScrollWidth:function(){return this.getScrollSize().x;},getTop:function(){return this.getPosition().y;},getLeft:function(){return this.getPosition().x;
}});Native.implement([Document,Element],{getElements:function(h,g){h=h.split(",");var c,e={};for(var d=0,b=h.length;d<b;d++){var a=h[d],f=Selectors.Utils.search(this,a,e);
if(d!=0&&f.item){f=$A(f);}c=(d==0)?f:(c.item)?$A(c).concat(f):c.concat(f);}return new Elements(c,{ddup:(h.length>1),cash:!g});}});Element.implement({match:function(b){if(!b||(b==this)){return true;
}var d=Selectors.Utils.parseTagAndID(b);var a=d[0],e=d[1];if(!Selectors.Filters.byID(this,e)||!Selectors.Filters.byTag(this,a)){return false;}var c=Selectors.Utils.parseSelector(b);
return(c)?Selectors.Utils.filter(this,c,{}):true;}});var Selectors={Cache:{nth:{},parsed:{}}};Selectors.RegExps={id:(/#([\w-]+)/),tag:(/^(\w+|\*)/),quick:(/^(\w+|\*)$/),splitter:(/\s*([+>~\s])\s*([a-zA-Z#.*:\[])/g),combined:(/\.([\w-]+)|\[(\w+)(?:([!*^$~|]?=)(["']?)([^\4]*?)\4)?\]|:([\w-]+)(?:\(["']?(.*?)?["']?\)|$)/g)};
Selectors.Utils={chk:function(b,c){if(!c){return true;}var a=$uid(b);if(!c[a]){return c[a]=true;}return false;},parseNthArgument:function(h){if(Selectors.Cache.nth[h]){return Selectors.Cache.nth[h];
}var e=h.match(/^([+-]?\d*)?([a-z]+)?([+-]?\d*)?$/);if(!e){return false;}var g=parseInt(e[1],10);var d=(g||g===0)?g:1;var f=e[2]||false;var c=parseInt(e[3],10)||0;
if(d!=0){c--;while(c<1){c+=d;}while(c>=d){c-=d;}}else{d=c;f="index";}switch(f){case"n":e={a:d,b:c,special:"n"};break;case"odd":e={a:2,b:0,special:"n"};
break;case"even":e={a:2,b:1,special:"n"};break;case"first":e={a:0,special:"index"};break;case"last":e={special:"last-child"};break;case"only":e={special:"only-child"};
break;default:e={a:(d-1),special:"index"};}return Selectors.Cache.nth[h]=e;},parseSelector:function(e){if(Selectors.Cache.parsed[e]){return Selectors.Cache.parsed[e];
}var d,h={classes:[],pseudos:[],attributes:[]};while((d=Selectors.RegExps.combined.exec(e))){var i=d[1],g=d[2],f=d[3],b=d[5],c=d[6],j=d[7];if(i){h.classes.push(i);}else{if(c){var a=Selectors.Pseudo.get(c);if(a){h.pseudos.push({parser:a,argument:j});}else{h.attributes.push({name:c,operator:"=",value:j});}}else{if(g){h.attributes.push({name:g,operator:f,value:b});
}}}}if(!h.classes.length){delete h.classes;}if(!h.attributes.length){delete h.attributes;}if(!h.pseudos.length){delete h.pseudos;}if(!h.classes&&!h.attributes&&!h.pseudos){h=null;}return Selectors.Cache.parsed[e]=h;},parseTagAndID:function(b){var a=b.match(Selectors.RegExps.tag);var c=b.match(Selectors.RegExps.id);return[(a)?a[1]:"*",(c)?c[1]:false];
},filter:function(f,c,e){var d;if(c.classes){for(d=c.classes.length;d--;d){var g=c.classes[d];if(!Selectors.Filters.byClass(f,g)){return false;}}}if(c.attributes){for(d=c.attributes.length;
d--;d){var b=c.attributes[d];if(!Selectors.Filters.byAttribute(f,b.name,b.operator,b.value)){return false;}}}if(c.pseudos){for(d=c.pseudos.length;d--;d){var a=c.pseudos[d];
if(!Selectors.Filters.byPseudo(f,a.parser,a.argument,e)){return false;}}}return true;},getByTagAndID:function(b,a,d){if(d){var c=(b.getElementById)?b.getElementById(d,true):Element.getElementById(b,d,true);
return(c&&Selectors.Filters.byTag(c,a))?[c]:[];}else{return b.getElementsByTagName(a);}},search:function(o,h,t){var b=[];var c=h.trim().replace(Selectors.RegExps.splitter,function(k,j,i){b.push(j);
return":)"+i;}).split(":)");var p,e,A;for(var z=0,v=c.length;z<v;z++){var y=c[z];if(z==0&&Selectors.RegExps.quick.test(y)){p=o.getElementsByTagName(y);
continue;}var a=b[z-1];var q=Selectors.Utils.parseTagAndID(y);var B=q[0],r=q[1];if(z==0){p=Selectors.Utils.getByTagAndID(o,B,r);}else{var d={},g=[];for(var x=0,w=p.length;
x<w;x++){g=Selectors.Getters[a](g,p[x],B,r,d);}p=g;}var f=Selectors.Utils.parseSelector(y);if(f){e=[];for(var u=0,s=p.length;u<s;u++){A=p[u];if(Selectors.Utils.filter(A,f,t)){e.push(A);}}p=e;}}return p;}};Selectors.Getters={" ":function(h,g,j,a,e){var d=Selectors.Utils.getByTagAndID(g,j,a);for(var c=0,b=d.length;c<b;c++){var f=d[c];if(Selectors.Utils.chk(f,e)){h.push(f);}}return h;},">":function(h,g,j,a,f){var c=Selectors.Utils.getByTagAndID(g,j,a);for(var e=0,d=c.length;e<d;e++){var b=c[e];if(b.parentNode==g&&Selectors.Utils.chk(b,f)){h.push(b);}}return h;},"+":function(c,b,a,e,d){while((b=b.nextSibling)){if(b.nodeType==1){if(Selectors.Utils.chk(b,d)&&Selectors.Filters.byTag(b,a)&&Selectors.Filters.byID(b,e)){c.push(b);}break;}}return c;},"~":function(c,b,a,e,d){while((b=b.nextSibling)){if(b.nodeType==1){if(!Selectors.Utils.chk(b,d)){break;}if(Selectors.Filters.byTag(b,a)&&Selectors.Filters.byID(b,e)){c.push(b);}}}return c;}};Selectors.Filters={byTag:function(b,a){return(a=="*"||(b.tagName&&b.tagName.toLowerCase()==a));},byID:function(a,b){return(!b||(a.id&&a.id==b));},byClass:function(b,a){return(b.className&&b.className.contains(a," "));},byPseudo:function(a,d,c,b){return d.call(a,c,b);},byAttribute:function(c,d,b,e){var a=Element.prototype.getProperty.call(c,d);
if(!a){return(b=="!=");}if(!b||e==undefined){return true;}switch(b){case"=":return(a==e);case"*=":return(a.contains(e));case"^=":return(a.substr(0,e.length)==e);
case"$=":return(a.substr(a.length-e.length)==e);case"!=":return(a!=e);case"~=":return a.contains(e," ");case"|=":return a.contains(e,"-");}return false;
}};Selectors.Pseudo=new Hash({checked:function(){return this.checked;},empty:function(){return !(this.innerText||this.textContent||"").length;},not:function(a){return !Element.match(this,a);
},contains:function(a){return(this.innerText||this.textContent||"").contains(a);},"first-child":function(){return Selectors.Pseudo.index.call(this,0);},"last-child":function(){var a=this;
while((a=a.nextSibling)){if(a.nodeType==1){return false;}}return true;},"only-child":function(){var b=this;while((b=b.previousSibling)){if(b.nodeType==1){return false;
}}var a=this;while((a=a.nextSibling)){if(a.nodeType==1){return false;}}return true;},"nth-child":function(g,e){g=(g==undefined)?"n":g;var c=Selectors.Utils.parseNthArgument(g);
if(c.special!="n"){return Selectors.Pseudo[c.special].call(this,c.a,e);}var f=0;e.positions=e.positions||{};var d=$uid(this);if(!e.positions[d]){var b=this;
while((b=b.previousSibling)){if(b.nodeType!=1){continue;}f++;var a=e.positions[$uid(b)];if(a!=undefined){f=a+f;break;}}e.positions[d]=f;}return(e.positions[d]%c.a==c.b);
},index:function(a){var b=this,c=0;while((b=b.previousSibling)){if(b.nodeType==1&&++c>a){return false;}}return(c==a);},even:function(b,a){return Selectors.Pseudo["nth-child"].call(this,"2n+1",a);
},odd:function(b,a){return Selectors.Pseudo["nth-child"].call(this,"2n",a);},selected:function(){return this.selected;},enabled:function(){return(this.disabled===false);}});Element.Events.domready={onAdd:function(a){if(Browser.loaded){a.call(this);}}};(function(){var b=function(){if(Browser.loaded){return;}Browser.loaded=true;
window.fireEvent("domready");document.fireEvent("domready");};if(Browser.Engine.trident){var a=document.createElement("div");(function(){($try(function(){a.doScroll();
return document.id(a).inject(document.body).set("html","temp").dispose();}))?b():arguments.callee.delay(50);})();}else{if(Browser.Engine.webkit&&Browser.Engine.version<525){(function(){(["loaded","complete"].contains(document.readyState))?b():arguments.callee.delay(50);})();}else{window.addEvent("load",b);document.addEvent("DOMContentLoaded",b);}}})();var JSON=new Hash({$specialChars:{"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},$replaceChars:function(a){return JSON.$specialChars[a]||"\\u00"+Math.floor(a.charCodeAt()/16).toString(16)+(a.charCodeAt()%16).toString(16);
},encode:function(b){switch($type(b)){case"string":return'"'+b.replace(/[\x00-\x1f\\"]/g,JSON.$replaceChars)+'"';case"array":return"["+String(b.map(JSON.encode).clean())+"]";
case"object":case"hash":var a=[];Hash.each(b,function(e,d){var c=JSON.encode(e);if(c){a.push(JSON.encode(d)+":"+c);}});return"{"+a+"}";case"number":case"boolean":return String(b);
case false:return"null";}return null;},decode:function(string,secure){if($type(string)!="string"||!string.length){return null;}if(secure&&!(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(string.replace(/\\./g,"@").replace(/"[^"\\\n\r]*"/g,""))){return null;
}return eval("("+string+")");}});Native.implement([Hash,Array,String,Number],{toJSON:function(){return JSON.encode(this);}});var Cookie=new Class({Implements:Options,options:{path:false,domain:false,duration:false,secure:false,document:document},initialize:function(b,a){this.key=b;
this.setOptions(a);},write:function(b){b=encodeURIComponent(b);if(this.options.domain){b+="; domain="+this.options.domain;}if(this.options.path){b+="; path="+this.options.path;
}if(this.options.duration){var a=new Date();a.setTime(a.getTime()+this.options.duration*24*60*60*1000);b+="; expires="+a.toGMTString();}if(this.options.secure){b+="; secure";
}this.options.document.cookie=this.key+"="+b;return this;},read:function(){var a=this.options.document.cookie.match("(?:^|;)\\s*"+this.key.escapeRegExp()+"=([^;]*)");
return(a)?decodeURIComponent(a[1]):null;},dispose:function(){new Cookie(this.key,$merge(this.options,{duration:-1})).write("");return this;}});Cookie.write=function(b,c,a){return new Cookie(b,a).write(c);
};Cookie.read=function(a){return new Cookie(a).read();};Cookie.dispose=function(b,a){return new Cookie(b,a).dispose();};var Swiff=new Class({Implements:[Options],options:{id:null,height:1,width:1,container:null,properties:{},params:{quality:"high",allowScriptAccess:"always",wMode:"transparent",swLiveConnect:true},callBacks:{},vars:{}},toElement:function(){return this.object;
},initialize:function(l,m){this.instance="Swiff_"+$time();this.setOptions(m);m=this.options;var b=this.id=m.id||this.instance;var a=document.id(m.container);
Swiff.CallBacks[this.instance]={};var e=m.params,g=m.vars,f=m.callBacks;var h=$extend({height:m.height,width:m.width},m.properties);var k=this;for(var d in f){Swiff.CallBacks[this.instance][d]=(function(n){return function(){return n.apply(k.object,arguments);
};})(f[d]);g[d]="Swiff.CallBacks."+this.instance+"."+d;}e.flashVars=Hash.toQueryString(g);if(Browser.Engine.trident){h.classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000";
e.movie=l;}else{h.type="application/x-shockwave-flash";h.data=l;}var j='<object id="'+b+'"';for(var i in h){j+=" "+i+'="'+h[i]+'"';}j+=">";for(var c in e){if(e[c]){j+='<param name="'+c+'" value="'+e[c]+'" />';
}}j+="</object>";this.object=((a)?a.empty():new Element("div")).set("html",j).firstChild;},replaces:function(a){a=document.id(a,true);a.parentNode.replaceChild(this.toElement(),a);
return this;},inject:function(a){document.id(a,true).appendChild(this.toElement());return this;},remote:function(){return Swiff.remote.apply(Swiff,[this.toElement()].extend(arguments));
}});Swiff.CallBacks={};Swiff.remote=function(obj,fn){var rs=obj.CallFunction('<invoke name="'+fn+'" returntype="javascript">'+__flash__argumentsToXML(arguments,2)+"</invoke>");
return eval(rs);};var Fx=new Class({Implements:[Chain,Events,Options],options:{fps:50,unit:false,duration:500,link:"ignore"},initialize:function(a){this.subject=this.subject||this;
this.setOptions(a);this.options.duration=Fx.Durations[this.options.duration]||this.options.duration.toInt();var b=this.options.wait;if(b===false){this.options.link="cancel";}},getTransition:function(){return function(a){return -(Math.cos(Math.PI*a)-1)/2;};},step:function(){var a=$time();if(a<this.time+this.options.duration){var b=this.transition((a-this.time)/this.options.duration);
this.set(this.compute(this.from,this.to,b));}else{this.set(this.compute(this.from,this.to,1));this.complete();}},set:function(a){return a;},compute:function(c,b,a){return Fx.compute(c,b,a);
},check:function(){if(!this.timer){return true;}switch(this.options.link){case"cancel":this.cancel();return true;case"chain":this.chain(this.caller.bind(this,arguments));
return false;}return false;},start:function(b,a){if(!this.check(b,a)){return this;}this.from=b;this.to=a;this.time=0;this.transition=this.getTransition();
this.startTimer();this.onStart();return this;},complete:function(){if(this.stopTimer()){this.onComplete();}return this;},cancel:function(){if(this.stopTimer()){this.onCancel();}return this;},onStart:function(){this.fireEvent("start",this.subject);},onComplete:function(){this.fireEvent("complete",this.subject);if(!this.callChain()){this.fireEvent("chainComplete",this.subject);}},onCancel:function(){this.fireEvent("cancel",this.subject).clearChain();},pause:function(){this.stopTimer();return this;},resume:function(){this.startTimer();
return this;},stopTimer:function(){if(!this.timer){return false;}this.time=$time()-this.time;this.timer=$clear(this.timer);return true;},startTimer:function(){if(this.timer){return false;
}this.time=$time()-this.time;this.timer=this.step.periodical(Math.round(1000/this.options.fps),this);return true;}});Fx.compute=function(c,b,a){return(b-c)*a+c;};Fx.Durations={"short":250,normal:500,"long":1000};Fx.CSS=new Class({Extends:Fx,prepare:function(d,e,b){b=$splat(b);var c=b[1];if(!$chk(c)){b[1]=b[0];
b[0]=d.getStyle(e);}var a=b.map(this.parse);return{from:a[0],to:a[1]};},parse:function(a){a=$lambda(a)();a=(typeof a=="string")?a.split(" "):$splat(a);
return a.map(function(c){c=String(c);var b=false;Fx.CSS.Parsers.each(function(f,e){if(b){return;}var d=f.parse(c);if($chk(d)){b={value:d,parser:f};}});
b=b||{value:c,parser:Fx.CSS.Parsers.String};return b;});},compute:function(d,c,b){var a=[];(Math.min(d.length,c.length)).times(function(e){a.push({value:d[e].parser.compute(d[e].value,c[e].value,b),parser:d[e].parser});
});a.$family={name:"fx:css:value"};return a;},serve:function(c,b){if($type(c)!="fx:css:value"){c=this.parse(c);}var a=[];c.each(function(d){a=a.concat(d.parser.serve(d.value,b));});return a;},render:function(a,d,c,b){a.setStyle(d,this.serve(c,b));},search:function(a){if(Fx.CSS.Cache[a]){return Fx.CSS.Cache[a];}var b={};Array.each(document.styleSheets,function(e,d){var c=e.href;
if(c&&c.contains("://")&&!c.contains(document.domain)){return;}var f=e.rules||e.cssRules;Array.each(f,function(j,g){if(!j.style){return;}var h=(j.selectorText)?j.selectorText.replace(/^\w+/,function(i){return i.toLowerCase();
}):null;if(!h||!h.test("^"+a+"$")){return;}Element.Styles.each(function(k,i){if(!j.style[i]||Element.ShortStyles[i]){return;}k=String(j.style[i]);b[i]=(k.test(/^rgb/))?k.rgbToHex():k;
});});});return Fx.CSS.Cache[a]=b;}});Fx.CSS.Cache={};Fx.CSS.Parsers=new Hash({Color:{parse:function(a){if(a.match(/^#[0-9a-f]{3,6}$/i)){return a.hexToRgb(true);
}return((a=a.match(/(\d+),\s*(\d+),\s*(\d+)/)))?[a[1],a[2],a[3]]:false;},compute:function(c,b,a){return c.map(function(e,d){return Math.round(Fx.compute(c[d],b[d],a));
});},serve:function(a){return a.map(Number);}},Number:{parse:parseFloat,compute:Fx.compute,serve:function(b,a){return(a)?b+a:b;}},String:{parse:$lambda(false),compute:$arguments(1),serve:$arguments(0)}});
Fx.Tween=new Class({Extends:Fx.CSS,initialize:function(b,a){this.element=this.subject=document.id(b);this.parent(a);},set:function(b,a){if(arguments.length==1){a=b;
b=this.property||this.options.property;}this.render(this.element,b,a,this.options.unit);return this;},start:function(c,e,d){if(!this.check(c,e,d)){return this;
}var b=Array.flatten(arguments);this.property=this.options.property||b.shift();var a=this.prepare(this.element,this.property,b);return this.parent(a.from,a.to);
}});Element.Properties.tween={set:function(a){var b=this.retrieve("tween");if(b){b.cancel();}return this.eliminate("tween").store("tween:options",$extend({link:"cancel"},a));
},get:function(a){if(a||!this.retrieve("tween")){if(a||!this.retrieve("tween:options")){this.set("tween",a);}this.store("tween",new Fx.Tween(this,this.retrieve("tween:options")));
}return this.retrieve("tween");}};Element.implement({tween:function(a,c,b){this.get("tween").start(arguments);return this;},fade:function(c){var e=this.get("tween"),d="opacity",a;
c=$pick(c,"toggle");switch(c){case"in":e.start(d,1);break;case"out":e.start(d,0);break;case"show":e.set(d,1);break;case"hide":e.set(d,0);break;case"toggle":var b=this.retrieve("fade:flag",this.get("opacity")==1);
e.start(d,(b)?0:1);this.store("fade:flag",!b);a=true;break;default:e.start(d,arguments);}if(!a){this.eliminate("fade:flag");}return this;},highlight:function(c,a){if(!a){a=this.retrieve("highlight:original",this.getStyle("background-color"));
a=(a=="transparent")?"#fff":a;}var b=this.get("tween");b.start("background-color",c||"#ffff88",a).chain(function(){this.setStyle("background-color",this.retrieve("highlight:original"));
b.callChain();}.bind(this));return this;}});Fx.Morph=new Class({Extends:Fx.CSS,initialize:function(b,a){this.element=this.subject=document.id(b);this.parent(a);},set:function(a){if(typeof a=="string"){a=this.search(a);}for(var b in a){this.render(this.element,b,a[b],this.options.unit);}return this;},compute:function(e,d,c){var a={};
for(var b in e){a[b]=this.parent(e[b],d[b],c);}return a;},start:function(b){if(!this.check(b)){return this;}if(typeof b=="string"){b=this.search(b);}var e={},d={};
for(var c in b){var a=this.prepare(this.element,c,b[c]);e[c]=a.from;d[c]=a.to;}return this.parent(e,d);}});Element.Properties.morph={set:function(a){var b=this.retrieve("morph");
if(b){b.cancel();}return this.eliminate("morph").store("morph:options",$extend({link:"cancel"},a));},get:function(a){if(a||!this.retrieve("morph")){if(a||!this.retrieve("morph:options")){this.set("morph",a);}this.store("morph",new Fx.Morph(this,this.retrieve("morph:options")));}return this.retrieve("morph");}};Element.implement({morph:function(a){this.get("morph").start(a);
return this;}});Fx.implement({getTransition:function(){var a=this.options.transition||Fx.Transitions.Sine.easeInOut;if(typeof a=="string"){var b=a.split(":");
a=Fx.Transitions;a=a[b[0]]||a[b[0].capitalize()];if(b[1]){a=a["ease"+b[1].capitalize()+(b[2]?b[2].capitalize():"")];}}return a;}});Fx.Transition=function(b,a){a=$splat(a);
return $extend(b,{easeIn:function(c){return b(c,a);},easeOut:function(c){return 1-b(1-c,a);},easeInOut:function(c){return(c<=0.5)?b(2*c,a)/2:(2-b(2*(1-c),a))/2;}});};Fx.Transitions=new Hash({linear:$arguments(0)});Fx.Transitions.extend=function(a){for(var b in a){Fx.Transitions[b]=new Fx.Transition(a[b]);}};Fx.Transitions.extend({Pow:function(b,a){return Math.pow(b,a[0]||6);
},Expo:function(a){return Math.pow(2,8*(a-1));},Circ:function(a){return 1-Math.sin(Math.acos(a));},Sine:function(a){return 1-Math.sin((1-a)*Math.PI/2);
},Back:function(b,a){a=a[0]||1.618;return Math.pow(b,2)*((a+1)*b-a);},Bounce:function(f){var e;for(var d=0,c=1;1;d+=c,c/=2){if(f>=(7-4*d)/11){e=c*c-Math.pow((11-6*d-11*f)/4,2);
break;}}return e;},Elastic:function(b,a){return Math.pow(2,10*--b)*Math.cos(20*b*Math.PI*(a[0]||1)/3);}});["Quad","Cubic","Quart","Quint"].each(function(b,a){Fx.Transitions[b]=new Fx.Transition(function(c){return Math.pow(c,[a+2]);
});});var Request=new Class({Implements:[Chain,Events,Options],options:{url:"",data:"",headers:{"X-Requested-With":"XMLHttpRequest",Accept:"text/javascript, text/html, application/xml, text/xml, */*"},async:true,format:false,method:"post",link:"ignore",isSuccess:null,emulation:true,urlEncoded:true,encoding:"utf-8",evalScripts:false,evalResponse:false,noCache:false},initialize:function(a){this.xhr=new Browser.Request();
this.setOptions(a);this.options.isSuccess=this.options.isSuccess||this.isSuccess;this.headers=new Hash(this.options.headers);},onStateChange:function(){if(this.xhr.readyState!=4||!this.running){return;}this.running=false;this.status=0;$try(function(){this.status=this.xhr.status;}.bind(this));this.xhr.onreadystatechange=$empty;if(this.options.isSuccess.call(this,this.status)){this.response={text:this.xhr.responseText,xml:this.xhr.responseXML};
this.success(this.response.text,this.response.xml);}else{this.response={text:null,xml:null};this.failure();}},isSuccess:function(){return((this.status>=200)&&(this.status<300));},processScripts:function(a){if(this.options.evalResponse||(/(ecma|java)script/).test(this.getHeader("Content-type"))){return $exec(a);}return a.stripScripts(this.options.evalScripts);
},success:function(b,a){this.onSuccess(this.processScripts(b),a);},onSuccess:function(){this.fireEvent("complete",arguments).fireEvent("success",arguments).callChain();},failure:function(){this.onFailure();},onFailure:function(){this.fireEvent("complete").fireEvent("failure",this.xhr);},setHeader:function(a,b){this.headers.set(a,b);
return this;},getHeader:function(a){return $try(function(){return this.xhr.getResponseHeader(a);}.bind(this));},check:function(){if(!this.running){return true;
}switch(this.options.link){case"cancel":this.cancel();return true;case"chain":this.chain(this.caller.bind(this,arguments));return false;}return false;},send:function(k){if(!this.check(k)){return this;
}this.running=true;var i=$type(k);if(i=="string"||i=="element"){k={data:k};}var d=this.options;k=$extend({data:d.data,url:d.url,method:d.method},k);var g=k.data,b=k.url,a=k.method.toLowerCase();
switch($type(g)){case"element":g=document.id(g).toQueryString();break;case"object":case"hash":g=Hash.toQueryString(g);}if(this.options.format){var j="format="+this.options.format;
g=(g)?j+"&"+g:j;}if(this.options.emulation&&!["get","post"].contains(a)){var h="_method="+a;g=(g)?h+"&"+g:h;a="post";}if(this.options.urlEncoded&&a=="post"){var c=(this.options.encoding)?"; charset="+this.options.encoding:"";
this.headers.set("Content-type","application/x-www-form-urlencoded"+c);}if(this.options.noCache){var f="noCache="+new Date().getTime();g=(g)?f+"&"+g:f;
}var e=b.lastIndexOf("/");if(e>-1&&(e=b.indexOf("#"))>-1){b=b.substr(0,e);}if(g&&a=="get"){b=b+(b.contains("?")?"&":"?")+g;g=null;}this.xhr.open(a.toUpperCase(),b,this.options.async);
this.xhr.onreadystatechange=this.onStateChange.bind(this);this.headers.each(function(m,l){try{this.xhr.setRequestHeader(l,m);}catch(n){this.fireEvent("exception",[l,m]);}},this);this.fireEvent("request");this.xhr.send(g);if(!this.options.async){this.onStateChange();}return this;},cancel:function(){if(!this.running){return this;
}this.running=false;this.xhr.abort();this.xhr.onreadystatechange=$empty;this.xhr=new Browser.Request();this.fireEvent("cancel");return this;}});(function(){var a={};
["get","post","put","delete","GET","POST","PUT","DELETE"].each(function(b){a[b]=function(){var c=Array.link(arguments,{url:String.type,data:$defined});
return this.send($extend(c,{method:b}));};});Request.implement(a);})();Element.Properties.send={set:function(a){var b=this.retrieve("send");if(b){b.cancel();}return this.eliminate("send").store("send:options",$extend({data:this,link:"cancel",method:this.get("method")||"post",url:this.get("action")},a));},get:function(a){if(a||!this.retrieve("send")){if(a||!this.retrieve("send:options")){this.set("send",a);}this.store("send",new Request(this.retrieve("send:options")));}return this.retrieve("send");}};Element.implement({send:function(a){var b=this.get("send");
b.send({data:this,url:a||b.options.url});return this;}});Request.HTML=new Class({Extends:Request,options:{update:false,append:false,evalScripts:true,filter:false},processHTML:function(c){var b=c.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
c=(b)?b[1]:c;var a=new Element("div");return $try(function(){var d="<root>"+c+"</root>",g;if(Browser.Engine.trident){g=new ActiveXObject("Microsoft.XMLDOM");
g.async=false;g.loadXML(d);}else{g=new DOMParser().parseFromString(d,"text/xml");}d=g.getElementsByTagName("root")[0];if(!d){return null;}for(var f=0,e=d.childNodes.length;
f<e;f++){var h=Element.clone(d.childNodes[f],true,true);if(h){a.grab(h);}}return a;})||a.set("html",c);},success:function(d){var c=this.options,b=this.response;
b.html=d.stripScripts(function(e){b.javascript=e;});var a=this.processHTML(b.html);b.tree=a.childNodes;b.elements=a.getElements("*");if(c.filter){b.tree=b.elements.filter(c.filter);}if(c.update){document.id(c.update).empty().set("html",b.html);}else{if(c.append){document.id(c.append).adopt(a.getChildren());}}if(c.evalScripts){$exec(b.javascript);}this.onSuccess(b.tree,b.elements,b.html,b.javascript);}});Element.Properties.load={set:function(a){var b=this.retrieve("load");if(b){b.cancel();}return this.eliminate("load").store("load:options",$extend({data:this,link:"cancel",update:this,method:"get"},a));
},get:function(a){if(a||!this.retrieve("load")){if(a||!this.retrieve("load:options")){this.set("load",a);}this.store("load",new Request.HTML(this.retrieve("load:options")));
}return this.retrieve("load");}};Element.implement({load:function(){this.get("load").send(Array.link(arguments,{data:Object.type,url:String.type}));return this;
}});Request.JSON=new Class({Extends:Request,options:{secure:true},initialize:function(a){this.parent(a);this.headers.extend({Accept:"application/json","X-Request":"JSON"});
},success:function(a){this.response.json=JSON.decode(a,this.options.secure);this.onSuccess(this.response.json,a);}});
//MooTools More, <http://mootools.net/more>. Copyright (c) 2006-2009 Aaron Newton <http://clientcide.com/>, Valerio Proietti <http://mad4milk.net> & the MooTools team <http://mootools.net/developers>, MIT Style License.

MooTools.More={version:"1.2.3.1"};(function(){var a={language:"en-US",languages:{"en-US":{}},cascades:["en-US"]};var b;MooTools.lang=new Events();$extend(MooTools.lang,{setLanguage:function(c){if(!a.languages[c]){return this;
}a.language=c;this.load();this.fireEvent("langChange",c);return this;},load:function(){var c=this.cascade(this.getCurrentLanguage());b={};$each(c,function(e,d){b[d]=this.lambda(e);},this);},getCurrentLanguage:function(){return a.language;},addLanguage:function(c){a.languages[c]=a.languages[c]||{};return this;},cascade:function(e){var c=(a.languages[e]||{}).cascades||[];
c.combine(a.cascades);c.erase(e).push(e);var d=c.map(function(g){return a.languages[g];},this);return $merge.apply(this,d);},lambda:function(c){(c||{}).get=function(e,d){return $lambda(c[e]).apply(this,$splat(d));
};return c;},get:function(e,d,c){if(b&&b[e]){return(d?b[e].get(d,c):b[e]);}},set:function(d,e,c){this.addLanguage(d);langData=a.languages[d];if(!langData[e]){langData[e]={};
}$extend(langData[e],c);if(d==this.getCurrentLanguage()){this.load();this.fireEvent("langChange",d);}return this;},list:function(){return Hash.getKeys(a.languages);
}});})();var Log=new Class({log:function(){Log.logger.call(this,arguments);}});Log.logged=[];Log.logger=function(){if(window.console&&console.log){console.log.apply(console,arguments);}else{Log.logged.push(arguments);}};Class.refactor=function(b,a){$each(a,function(e,d){var c=b.prototype[d];if(c&&(c=c._origin)&&typeof e=="function"){b.implement(d,function(){var g=this.previous;
this.previous=c;var h=e.apply(this,arguments);this.previous=g;return h;});}else{b.implement(d,e);}});return b;};Class.Mutators.Binds=function(a){return a;
};Class.Mutators.initialize=function(a){return function(){$splat(this.Binds).each(function(b){var c=this[b];if(c){this[b]=c.bind(this);}},this);return a.apply(this,arguments);
};};Class.Occlude=new Class({occlude:function(c,b){b=document.id(b||this.element);var a=b.retrieve(c||this.property);if(a&&!$defined(this.occluded)){this.occluded=a;}else{this.occluded=false;b.store(c||this.property,this);}return this.occluded;}});(function(){var b={wait:function(c){return this.chain(function(){this.callChain.delay($pick(c,500),this);}.bind(this));}};Chain.implement(b);if(window.Fx){Fx.implement(b);["Css","Tween","Elements"].each(function(c){if(Fx[c]){Fx[c].implement(b);}});}try{Element.implement({chains:function(c){$splat($pick(c,["tween","morph","reveal"])).each(function(d){d=this.get(d);
if(!d){return;}d.setOptions({link:"chain"});},this);return this;},pauseFx:function(d,c){this.chains(c).get($pick(c,"tween")).wait(d);return this;}});}catch(a){}})();
Array.implement({min:function(){return Math.min.apply(null,this);},max:function(){return Math.max.apply(null,this);},average:function(){return this.length?this.sum()/this.length:0;
},sum:function(){var a=0,b=this.length;if(b){do{a+=this[--b];}while(b);}return a;},unique:function(){return[].combine(this);}});(function(){if(!Date.now){Date.now=$time;}Date.Methods={};["Date","Day","FullYear","Hours","Milliseconds","Minutes","Month","Seconds","Time","TimezoneOffset","Week","Timezone","GMTOffset","DayOfYear","LastMonth","LastDayOfMonth","UTCDate","UTCDay","UTCFullYear","AMPM","Ordinal","UTCHours","UTCMilliseconds","UTCMinutes","UTCMonth","UTCSeconds"].each(function(m){Date.Methods[m.toLowerCase()]=m;});$each({ms:"Milliseconds",year:"FullYear",min:"Minutes",mo:"Month",sec:"Seconds",hr:"Hours"},function(n,m){Date.Methods[m]=n;});var c=function(n,m){return new Array(m-n.toString().length+1).join("0")+n;
};Date.implement({set:function(r,o){switch($type(r)){case"object":for(var q in r){this.set(q,r[q]);}break;case"string":r=r.toLowerCase();var n=Date.Methods;
if(n[r]){this["set"+n[r]](o);}}return this;},get:function(o){o=o.toLowerCase();var n=Date.Methods;if(n[o]){return this["get"+n[o]]();}return null;},clone:function(){return new Date(this.get("time"));
},increment:function(m,o){m=m||"day";o=$pick(o,1);switch(m){case"year":return this.increment("month",o*12);case"month":var n=this.get("date");this.set("date",1).set("mo",this.get("mo")+o);
return this.set("date",n.min(this.get("lastdayofmonth")));case"week":return this.increment("day",o*7);case"day":return this.set("date",this.get("date")+o);
}if(!Date.units[m]){throw new Error(m+" is not a supported interval");}return this.set("time",this.get("time")+o*Date.units[m]());},decrement:function(m,n){return this.increment(m,-1*$pick(n,1));
},isLeapYear:function(){return Date.isLeapYear(this.get("year"));},clearTime:function(){return this.set({hr:0,min:0,sec:0,ms:0});},diff:function(p,n){n=n||"day";
if($type(p)=="string"){p=Date.parse(p);}switch(n){case"year":return p.get("year")-this.get("year");case"month":var m=(p.get("year")-this.get("year"))*12;
return m+p.get("mo")-this.get("mo");default:var o=p.get("time")-this.get("time");if(Date.units[n]()>o.abs()){return 0;}return((p.get("time")-this.get("time"))/Date.units[n]()).round();
}return null;},getLastDayOfMonth:function(){return Date.daysInMonth(this.get("mo"),this.get("year"));},getDayOfYear:function(){return(Date.UTC(this.get("year"),this.get("mo"),this.get("date")+1)-Date.UTC(this.get("year"),0,1))/Date.units.day();},getWeek:function(){return(this.get("dayofyear")/7).ceil();},getOrdinal:function(m){return Date.getMsg("ordinal",m||this.get("date"));},getTimezone:function(){return this.toString().replace(/^.*? ([A-Z]{3}).[0-9]{4}.*$/,"$1").replace(/^.*?\(([A-Z])[a-z]+ ([A-Z])[a-z]+ ([A-Z])[a-z]+\)$/,"$1$2$3");
},getGMTOffset:function(){var m=this.get("timezoneOffset");return((m>0)?"-":"+")+c((m.abs()/60).floor(),2)+c(m%60,2);},setAMPM:function(m){m=m.toUpperCase();
var n=this.get("hr");if(n>11&&m=="AM"){return this.decrement("hour",12);}else{if(n<12&&m=="PM"){return this.increment("hour",12);}}return this;},getAMPM:function(){return(this.get("hr")<12)?"AM":"PM";},parse:function(m){this.set("time",Date.parse(m));return this;},isValid:function(m){return !!(m||this).valueOf();},format:function(m){if(!this.isValid()){return"invalid date";
}m=m||"%x %X";m=i[m.toLowerCase()]||m;var n=this;return m.replace(/%([a-z%])/gi,function(o,p){switch(p){case"a":return Date.getMsg("days")[n.get("day")].substr(0,3);
case"A":return Date.getMsg("days")[n.get("day")];case"b":return Date.getMsg("months")[n.get("month")].substr(0,3);case"B":return Date.getMsg("months")[n.get("month")];
case"c":return n.toString();case"d":return c(n.get("date"),2);case"H":return c(n.get("hr"),2);case"I":return((n.get("hr")%12)||12);case"j":return c(n.get("dayofyear"),3);
case"m":return c((n.get("mo")+1),2);case"M":return c(n.get("min"),2);case"o":return n.get("ordinal");case"p":return Date.getMsg(n.get("ampm"));case"S":return c(n.get("seconds"),2);
case"U":return c(n.get("week"),2);case"w":return n.get("day");case"x":return n.format(Date.getMsg("shortDate"));case"X":return n.format(Date.getMsg("shortTime"));
case"y":return n.get("year").toString().substr(2);case"Y":return n.get("year");case"T":return n.get("GMTOffset");case"Z":return n.get("Timezone");}return p;
});},toISOString:function(){return this.format("iso8601");}});Date.alias("diff","compare");Date.alias("format","strftime");var i={db:"%Y-%m-%d %H:%M:%S",compact:"%Y%m%dT%H%M%S",iso8601:"%Y-%m-%dT%H:%M:%S%T",rfc822:"%a, %d %b %Y %H:%M:%S %Z","short":"%d %b %H:%M","long":"%B %d, %Y %H:%M"};
var e=Date.parse;var k=function(p,r,o){var n=-1;var q=Date.getMsg(p+"s");switch($type(r)){case"object":n=q[r.get(p)];break;case"number":n=q[month-1];if(!n){throw new Error("Invalid "+p+" index: "+index);
}break;case"string":var m=q.filter(function(s){return this.test(s);},new RegExp("^"+r,"i"));if(!m.length){throw new Error("Invalid "+p+" string");}if(m.length>1){throw new Error("Ambiguous "+p);
}n=m[0];}return(o)?q.indexOf(n):n;};Date.extend({getMsg:function(n,m){return MooTools.lang.get("Date",n,m);},units:{ms:$lambda(1),second:$lambda(1000),minute:$lambda(60000),hour:$lambda(3600000),day:$lambda(86400000),week:$lambda(608400000),month:function(n,m){var o=new Date;
return Date.daysInMonth($pick(n,o.get("mo")),$pick(m,o.get("year")))*86400000;},year:function(m){m=m||new Date().get("year");return Date.isLeapYear(m)?31622400000:31536000000;
}},daysInMonth:function(n,m){return[31,Date.isLeapYear(m)?29:28,31,30,31,30,31,31,30,31,30,31][n];},isLeapYear:function(m){return new Date(m,1,29).get("date")==29;
},parse:function(o){var n=$type(o);if(n=="number"){return new Date(o);}if(n!="string"){return o;}o=o.clean();if(!o.length){return null;}var m;Date.parsePatterns.some(function(q){var p=q.re.exec(o);
return(p)?(m=q.handler(p)):false;});return m||new Date(e(o));},parseDay:function(m,n){return k("day",m,n);},parseMonth:function(n,m){return k("month",n,m);
},parseUTC:function(n){var m=new Date(n);var o=Date.UTC(m.get("year"),m.get("mo"),m.get("date"),m.get("hr"),m.get("min"),m.get("sec"));return new Date(o);
},orderIndex:function(m){return Date.getMsg("dateOrder").indexOf(m)+1;},defineFormat:function(m,n){i[m]=n;},defineFormats:function(m){for(var n in m){Date.defineFormat(n,m[f]);}},parsePatterns:[],defineParser:function(m){Date.parsePatterns.push(m.re&&m.handler?m:j(m));},defineParsers:function(){Array.flatten(arguments).each(Date.defineParser);},define2DigitYearStart:function(m){d=m%100;g=m-d;}});var g=1900;var d=70;var a=function(m){switch(m){case"x":return(Date.orderIndex("month")==1)?"%m[.-/]%d([.-/]%y)?":"%d[.-/]%m([.-/]%y)?";
case"X":return"%H([.:]%M)?([.:]%S([.:]%s)?)?\\s?%p?\\s?%T?";case"o":return"[^\\d\\s]*";}return null;};var l={a:/[a-z]{3,}/,d:/[0-2]?[0-9]|3[01]/,H:/[01]?[0-9]|2[0-3]/,I:/0?[1-9]|1[0-2]/,M:/[0-5]?\d/,s:/\d+/,p:/[ap]\.?m\.?/,y:/\d{2}|\d{4}/,Y:/\d{4}/,T:/Z|[+-]\d{2}(?::?\d{2})?/};
l.B=l.b=l.A=l.a;l.m=l.I;l.S=l.M;var b;var j=function(o){if(!b){return{format:o};}var m=[null];var n=(o.source||o).replace(/%([a-z])/gi,function(p,q){return a(q)||p;
}).replace(/\((?!\?)/g,"(?:").replace(/ (?!\?|\*)/g,",? ").replace(/%([a-z%])/gi,function(q,s){var r=l[s];if(!r){return s;}m.push(s);return"("+r.source+")";
});return{format:o,re:new RegExp("^"+n+"$","i"),handler:function(r){var p=new Date().clearTime();for(var q=1;q<m.length;q++){p=h.call(p,m[q],r[q]);}return p;
}};};var h=function(m,n){if(!n){if(m=="m"||m=="d"){n=1;}else{return this;}}switch(m){case"a":case"A":return this.set("day",Date.parseDay(n,true));case"b":case"B":return this.set("mo",Date.parseMonth(n,true));
case"d":return this.set("date",n);case"H":case"I":return this.set("hr",n);case"m":return this.set("mo",n-1);case"M":return this.set("min",n);case"p":return this.set("ampm",n.replace(/\./g,""));
case"S":return this.set("sec",n);case"s":return this.set("ms",("0."+n)*1000);case"w":return this.set("day",n);case"Y":return this.set("year",n);case"y":n=+n;
if(n<100){n+=g+(n<d?100:0);}return this.set("year",n);case"T":if(n=="Z"){n="+00";}var o=n.match(/([+-])(\d{2}):?(\d{2})?/);o=(o[1]+"1")*(o[2]*60+(+o[3]||0))+this.getTimezoneOffset();
return this.set("time",(this*1)-o*60000);}return this;};Date.defineParsers("%Y([-./]%m([-./]%d((T| )%X)?)?)?","%Y%m%d(T%H(%M%S?)?)?","%x( %X)?","%d%o( %b( %Y)?)?( %X)?","%b %d%o?( %Y)?( %X)?","%b %Y");
MooTools.lang.addEvent("langChange",function(m){if(!MooTools.lang.get("Date")){return;}b=m;Date.parsePatterns.each(function(o,n){if(o.format){Date.parsePatterns[n]=j(o.format);}});}).fireEvent("langChange",MooTools.lang.getCurrentLanguage());})();Date.implement({timeDiffInWords:function(a){return Date.distanceOfTimeInWords(this,a||new Date);
}});Date.alias("timeDiffInWords","timeAgoInWords");Date.extend({distanceOfTimeInWords:function(b,a){return Date.getTimePhrase(((a-b)/1000).toInt());},getTimePhrase:function(c){var a=(c<0)?"Until":"Ago";
if(c<0){c*=-1;}var b=(c<60)?"lessThanMinute":(c<120)?"minute":(c<(45*60))?"minutes":(c<(90*60))?"hour":(c<(24*60*60))?"hours":(c<(48*60*60))?"day":"days";
switch(b){case"minutes":c=(c/60).round();break;case"hours":c=(c/3600).round();break;case"days":c=(c/86400).round();}return Date.getMsg(b+a,c).substitute({delta:c});
}});Date.defineParsers({re:/^tod|tom|yes/i,handler:function(a){var b=new Date().clearTime();switch(a[0]){case"tom":return b.increment();case"yes":return b.decrement();
default:return b;}}},{re:/^(next|last) ([a-z]+)$/i,handler:function(e){var g=new Date().clearTime();var b=g.getDay();var c=Date.parseDay(e[2],true);var a=c-b;
if(c<=b){a+=7;}if(e[1]=="last"){a-=7;}return g.set("date",g.getDate()+a);}});Hash.implement({getFromPath:function(a){var b=this.getClean();a.replace(/\[([^\]]+)\]|\.([^.[]+)|[^[.]+/g,function(c){if(!b){return null;
}var d=arguments[2]||arguments[1]||arguments[0];b=(d in b)?b[d]:null;return c;});return b;},cleanValues:function(a){a=a||$defined;this.each(function(c,b){if(!a(c)){this.erase(b);}},this);return this;},run:function(){var a=arguments;this.each(function(c,b){if($type(c)=="function"){c.run(a);}});}});(function(){var b=["À","à","Á","á","Â","â","Ã","ã","Ä","ä","Å","å","Ă","ă","Ą","ą","Ć","ć","Č","č","Ç","ç","Ď","ď","Đ","đ","È","è","É","é","Ê","ê","Ë","ë","Ě","ě","Ę","ę","Ğ","ğ","Ì","ì","Í","í","Î","î","Ï","ï","Ĺ","ĺ","Ľ","ľ","Ł","ł","Ñ","ñ","Ň","ň","Ń","ń","Ò","ò","Ó","ó","Ô","ô","Õ","õ","Ö","ö","Ø","ø","ő","Ř","ř","Ŕ","ŕ","Š","š","Ş","ş","Ś","ś","Ť","ť","Ť","ť","Ţ","ţ","Ù","ù","Ú","ú","Û","û","Ü","ü","Ů","ů","Ÿ","ÿ","ý","Ý","Ž","ž","Ź","ź","Ż","ż","Þ","þ","Ð","ð","ß","Œ","œ","Æ","æ","µ"];
var a=["A","a","A","a","A","a","A","a","Ae","ae","A","a","A","a","A","a","C","c","C","c","C","c","D","d","D","d","E","e","E","e","E","e","E","e","E","e","E","e","G","g","I","i","I","i","I","i","I","i","L","l","L","l","L","l","N","n","N","n","N","n","O","o","O","o","O","o","O","o","Oe","oe","O","o","o","R","r","R","r","S","s","S","s","S","s","T","t","T","t","T","t","U","u","U","u","U","u","Ue","ue","U","u","Y","y","Y","y","Z","z","Z","z","Z","z","TH","th","DH","dh","ss","OE","oe","AE","ae","u"];
var c={"[\xa0\u2002\u2003\u2009]":" ","\xb7":"*","[\u2018\u2019]":"'","[\u201c\u201d]":'"',"\u2026":"...","\u2013":"-","\u2014":"--","\uFFFD":"&raquo;"};
String.implement({standardize:function(){var d=this;b.each(function(g,e){d=d.replace(new RegExp(g,"g"),a[e]);});return d;},repeat:function(d){return new Array(d+1).join(this);
},pad:function(e,h,d){if(this.length>=e){return this;}h=h||" ";var g=h.repeat(e-this.length).substr(0,e-this.length);if(!d||d=="right"){return this+g;}if(d=="left"){return g+this;
}return g.substr(0,(g.length/2).floor())+this+g.substr(0,(g.length/2).ceil());},stripTags:function(){return this.replace(/<\/?[^>]+>/gi,"");},tidy:function(){var d=this.toString();
$each(c,function(g,e){d=d.replace(new RegExp(e,"g"),g);});return d;}});})();String.implement({parseQueryString:function(){var b=this.split(/[&;]/),a={};
if(b.length){b.each(function(h){var c=h.indexOf("="),d=c<0?[""]:h.substr(0,c).match(/[^\]\[]+/g),e=decodeURIComponent(h.substr(c+1)),g=a;d.each(function(k,j){var l=g[k];
if(j<d.length-1){g=g[k]=l||{};}else{if($type(l)=="array"){l.push(e);}else{g[k]=$defined(l)?[l,e]:e;}}});});}return a;},cleanQueryString:function(a){return this.split("&").filter(function(e){var b=e.indexOf("="),c=b<0?"":e.substr(0,b),d=e.substr(b+1);
return a?a.run([c,d]):$chk(d);}).join("&");}});var URI=new Class({Implements:Options,regex:/^(?:(\w+):)?(?:\/\/(?:(?:([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)?(\.\.?$|(?:[^?#\/]*\/)*)([^?#]*)(?:\?([^#]*))?(?:#(.*))?/,parts:["scheme","user","password","host","port","directory","file","query","fragment"],schemes:{http:80,https:443,ftp:21,rtsp:554,mms:1755,file:0},initialize:function(b,a){this.setOptions(a);
var c=this.options.base||URI.base;b=b||c;if(b&&b.parsed){this.parsed=$unlink(b.parsed);}else{this.set("value",b.href||b.toString(),c?new URI(c):false);
}},parse:function(c,b){var a=c.match(this.regex);if(!a){return false;}a.shift();return this.merge(a.associate(this.parts),b);},merge:function(b,a){if((!b||!b.scheme)&&(!a||!a.scheme)){return false;
}if(a){this.parts.every(function(c){if(b[c]){return false;}b[c]=a[c]||"";return true;});}b.port=b.port||this.schemes[b.scheme.toLowerCase()];b.directory=b.directory?this.parseDirectory(b.directory,a?a.directory:""):"/";
return b;},parseDirectory:function(b,c){b=(b.substr(0,1)=="/"?"":(c||"/"))+b;if(!b.test(URI.regs.directoryDot)){return b;}var a=[];b.replace(URI.regs.endSlash,"").split("/").each(function(d){if(d==".."&&a.length>0){a.pop();}else{if(d!="."){a.push(d);}}});return a.join("/")+"/";},combine:function(a){return a.value||a.scheme+"://"+(a.user?a.user+(a.password?":"+a.password:"")+"@":"")+(a.host||"")+(a.port&&a.port!=this.schemes[a.scheme]?":"+a.port:"")+(a.directory||"/")+(a.file||"")+(a.query?"?"+a.query:"")+(a.fragment?"#"+a.fragment:"");
},set:function(b,d,c){if(b=="value"){var a=d.match(URI.regs.scheme);if(a){a=a[1];}if(a&&!$defined(this.schemes[a.toLowerCase()])){this.parsed={scheme:a,value:d};
}else{this.parsed=this.parse(d,(c||this).parsed)||(a?{scheme:a,value:d}:{value:d});}}else{if(b=="data"){this.setData(d);}else{this.parsed[b]=d;}}return this;
},get:function(a,b){switch(a){case"value":return this.combine(this.parsed,b?b.parsed:false);case"data":return this.getData();}return this.parsed[a]||undefined;
},go:function(){document.location.href=this.toString();},toURI:function(){return this;},getData:function(c,b){var a=this.get(b||"query");if(!$chk(a)){return c?null:{};}var d=a.parseQueryString();return c?d[c]:d;},setData:function(a,c,b){if($type(arguments[0])=="string"){a=this.getData();a[arguments[0]]=arguments[1];}else{if(c){a=$merge(this.getData(),a);}}return this.set(b||"query",Hash.toQueryString(a));},clearData:function(a){return this.set(a||"query","");}});["toString","valueOf"].each(function(a){URI.prototype[a]=function(){return this.get("value");
};});URI.regs={endSlash:/\/$/,scheme:/^(\w+):/,directoryDot:/\.\/|\.$/};URI.base=new URI($$("base[href]").getLast(),{base:document.location});String.implement({toURI:function(a){return new URI(this,a);
}});URI=Class.refactor(URI,{combine:function(g,e){if(!e||g.scheme!=e.scheme||g.host!=e.host||g.port!=e.port){return this.previous.apply(this,arguments);
}var a=g.file+(g.query?"?"+g.query:"")+(g.fragment?"#"+g.fragment:"");if(!e.directory){return(g.directory||(g.file?"":"./"))+a;}var d=e.directory.split("/"),c=g.directory.split("/"),h="",j;
var b=0;for(j=0;j<d.length&&j<c.length&&d[j]==c[j];j++){}for(b=0;b<d.length-j-1;b++){h+="../";}for(b=j;b<c.length-1;b++){h+=c[b]+"/";}return(h||(g.file?"":"./"))+a;
},toAbsolute:function(a){a=new URI(a);if(a){a.set("directory","").set("file","");}return this.toRelative(a);},toRelative:function(a){return this.get("value",new URI(a));
}});Element.implement({tidy:function(){this.set("value",this.get("value").tidy());},getTextInRange:function(b,a){return this.get("value").substring(b,a);
},getSelectedText:function(){if(this.setSelectionRange){return this.getTextInRange(this.getSelectionStart(),this.getSelectionEnd());}return document.selection.createRange().text;
},getSelectedRange:function(){if($defined(this.selectionStart)){return{start:this.selectionStart,end:this.selectionEnd};}var e={start:0,end:0};var a=this.getDocument().selection.createRange();
if(!a||a.parentElement()!=this){return e;}var c=a.duplicate();if(this.type=="text"){e.start=0-c.moveStart("character",-100000);e.end=e.start+a.text.length;}else{var b=this.get("value");var d=b.length-b.match(/[\n\r]*$/)[0].length;c.moveToElementText(this);c.setEndPoint("StartToEnd",a);e.end=d-c.text.length;
c.setEndPoint("StartToStart",a);e.start=d-c.text.length;}return e;},getSelectionStart:function(){return this.getSelectedRange().start;},getSelectionEnd:function(){return this.getSelectedRange().end;
},setCaretPosition:function(a){if(a=="end"){a=this.get("value").length;}this.selectRange(a,a);return this;},getCaretPosition:function(){return this.getSelectedRange().start;
},selectRange:function(e,a){if(this.setSelectionRange){this.focus();this.setSelectionRange(e,a);}else{var c=this.get("value");var d=c.substr(e,a-e).replace(/\r/g,"").length;
e=c.substr(0,e).replace(/\r/g,"").length;var b=this.createTextRange();b.collapse(true);b.moveEnd("character",e+d);b.moveStart("character",e);b.select();
}return this;},insertAtCursor:function(b,a){var d=this.getSelectedRange();var c=this.get("value");this.set("value",c.substring(0,d.start)+b+c.substring(d.end,c.length));
if($pick(a,true)){this.selectRange(d.start,d.start+b.length);}else{this.setCaretPosition(d.start+b.length);}return this;},insertAroundCursor:function(b,a){b=$extend({before:"",defaultMiddle:"",after:""},b);
var c=this.getSelectedText()||b.defaultMiddle;var h=this.getSelectedRange();var g=this.get("value");if(h.start==h.end){this.set("value",g.substring(0,h.start)+b.before+c+b.after+g.substring(h.end,g.length));
this.selectRange(h.start+b.before.length,h.end+b.before.length+c.length);}else{var d=g.substring(h.start,h.end);this.set("value",g.substring(0,h.start)+b.before+d+b.after+g.substring(h.end,g.length));
var e=h.start+b.before.length;if($pick(a,true)){this.selectRange(e,e+d.length);}else{this.setCaretPosition(e+g.length);}}return this;}});Element.implement({measure:function(e){var h=function(i){return !!(!i||i.offsetHeight||i.offsetWidth);
};if(h(this)){return e.apply(this);}var d=this.getParent(),b=[],g=[];while(!h(d)&&d!=document.body){b.push(d.expose());d=d.getParent();}var c=this.expose();
var a=e.apply(this);c();b.each(function(i){i();});return a;},expose:function(){if(this.getStyle("display")!="none"){return $empty;}var a=this.style.cssText;
this.setStyles({display:"block",position:"absolute",visibility:"hidden"});return function(){this.style.cssText=a;}.bind(this);},getDimensions:function(a){a=$merge({computeSize:false},a);
var d={};var c=function(g,e){return(e.computeSize)?g.getComputedSize(e):g.getSize();};if(this.getStyle("display")=="none"){d=this.measure(function(){return c(this,a);
});}else{try{d=c(this,a);}catch(b){}}return $chk(d.x)?$extend(d,{width:d.x,height:d.y}):$extend(d,{x:d.width,y:d.height});},getComputedSize:function(a){a=$merge({styles:["padding","border"],plains:{height:["top","bottom"],width:["left","right"]},mode:"both"},a);
var c={width:0,height:0};switch(a.mode){case"vertical":delete c.width;delete a.plains.width;break;case"horizontal":delete c.height;delete a.plains.height;
break;}var b=[];$each(a.plains,function(h,g){h.each(function(i){a.styles.each(function(j){b.push((j=="border")?j+"-"+i+"-width":j+"-"+i);});});});var e={};
b.each(function(g){e[g]=this.getComputedStyle(g);},this);var d=[];$each(a.plains,function(h,g){var i=g.capitalize();c["total"+i]=0;c["computed"+i]=0;h.each(function(j){c["computed"+j.capitalize()]=0;
b.each(function(l,k){if(l.test(j)){e[l]=e[l].toInt()||0;c["total"+i]=c["total"+i]+e[l];c["computed"+j.capitalize()]=c["computed"+j.capitalize()]+e[l];}if(l.test(j)&&g!=l&&(l.test("border")||l.test("padding"))&&!d.contains(l)){d.push(l);
c["computed"+i]=c["computed"+i]-e[l];}});});});["Width","Height"].each(function(h){var g=h.toLowerCase();if(!$chk(c[g])){return;}c[g]=c[g]+this["offset"+h]+c["computed"+h];
c["total"+h]=c[g]+c["total"+h];delete c["computed"+h];},this);return $extend(e,c);}});(function(){var a=false;window.addEvent("domready",function(){var b=new Element("div").setStyles({position:"fixed",top:0,right:0}).inject(document.body);
a=(b.offsetTop===0);b.dispose();});Element.implement({pin:function(c){if(this.getStyle("display")=="none"){return null;}var d;if(c!==false){d=this.getPosition();
if(!this.retrieve("pinned")){var g={top:d.y-window.getScroll().y,left:d.x-window.getScroll().x};if(a){this.setStyle("position","fixed").setStyles(g);}else{this.store("pinnedByJS",true);
this.setStyles({position:"absolute",top:d.y,left:d.x});this.store("scrollFixer",(function(){if(this.retrieve("pinned")){this.setStyles({top:g.top.toInt()+window.getScroll().y,left:g.left.toInt()+window.getScroll().x});
}}).bind(this));window.addEvent("scroll",this.retrieve("scrollFixer"));}this.store("pinned",true);}}else{var e;if(!Browser.Engine.trident){if(this.getParent().getComputedStyle("position")!="static"){e=this.getParent();}else{e=this.getParent().getOffsetParent();}}d=this.getPosition(e);this.store("pinned",false);var b;if(a&&!this.retrieve("pinnedByJS")){b={top:d.y+window.getScroll().y,left:d.x+window.getScroll().x};
}else{this.store("pinnedByJS",false);window.removeEvent("scroll",this.retrieve("scrollFixer"));b={top:d.y,left:d.x};}this.setStyles($merge(b,{position:"absolute"}));
}return this.addClass("isPinned");},unpin:function(){return this.pin(false).removeClass("isPinned");},togglepin:function(){this.pin(!this.retrieve("pinned"));}});})();(function(){var a=Element.prototype.position;Element.implement({position:function(s){if(s&&($defined(s.x)||$defined(s.y))){return a?a.apply(this,arguments):this;
}$each(s||{},function(u,t){if(!$defined(u)){delete s[t];}});s=$merge({relativeTo:document.body,position:{x:"center",y:"center"},edge:false,offset:{x:0,y:0},returnPos:false,relFixedPosition:false,ignoreMargins:false,allowNegative:false},s);
var b={x:0,y:0};var i=false;var c=this.measure(function(){return document.id(this.getOffsetParent());});if(c&&c!=this.getDocument().body){b=c.measure(function(){return this.getPosition();
});i=true;s.offset.x=s.offset.x-b.x;s.offset.y=s.offset.y-b.y;}var r=function(t){if($type(t)!="string"){return t;}t=t.toLowerCase();var u={};if(t.test("left")){u.x="left";}else{if(t.test("right")){u.x="right";}else{u.x="center";}}if(t.test("upper")||t.test("top")){u.y="top";}else{if(t.test("bottom")){u.y="bottom";}else{u.y="center";}}return u;};s.edge=r(s.edge);s.position=r(s.position);if(!s.edge){if(s.position.x=="center"&&s.position.y=="center"){s.edge={x:"center",y:"center"};}else{s.edge={x:"left",y:"top"};
}}this.setStyle("position","absolute");var q=document.id(s.relativeTo)||document.body;var j=q==document.body?window.getScroll():q.getPosition();var p=j.y;
var h=j.x;if(Browser.Engine.trident){var m=q.getScrolls();p+=m.y;h+=m.x;}var k=this.getDimensions({computeSize:true,styles:["padding","border","margin"]});
if(s.ignoreMargins){s.offset.x=s.offset.x-k["margin-left"];s.offset.y=s.offset.y-k["margin-top"];}var o={};var d=s.offset.y;var e=s.offset.x;var l=window.getSize();
switch(s.position.x){case"left":o.x=h+e;break;case"right":o.x=h+e+q.offsetWidth;break;default:o.x=h+((q==document.body?l.x:q.offsetWidth)/2)+e;break;}switch(s.position.y){case"top":o.y=p+d;
break;case"bottom":o.y=p+d+q.offsetHeight;break;default:o.y=p+((q==document.body?l.y:q.offsetHeight)/2)+d;break;}if(s.edge){var n={};switch(s.edge.x){case"left":n.x=0;
break;case"right":n.x=-k.x-k.computedRight-k.computedLeft;break;default:n.x=-(k.x/2);break;}switch(s.edge.y){case"top":n.y=0;break;case"bottom":n.y=-k.y-k.computedTop-k.computedBottom;
break;default:n.y=-(k.y/2);break;}o.x=o.x+n.x;o.y=o.y+n.y;}o={left:((o.x>=0||i||s.allowNegative)?o.x:0).toInt(),top:((o.y>=0||i||s.allowNegative)?o.y:0).toInt()};
if(q.getStyle("position")=="fixed"||s.relFixedPosition){var g=window.getScroll();o.top=o.top.toInt()+g.y;o.left=o.left.toInt()+g.x;}if(s.returnPos){return o;
}else{this.setStyles(o);}return this;}});})();Element.implement({isDisplayed:function(){return this.getStyle("display")!="none";},toggle:function(){return this[this.isDisplayed()?"hide":"show"]();
},hide:function(){var b;try{if("none"!=this.getStyle("display")){b=this.getStyle("display");}}catch(a){}return this.store("originalDisplay",b||"block").setStyle("display","none");
},show:function(a){return this.setStyle("display",a||this.retrieve("originalDisplay")||"block");},swapClass:function(a,b){return this.removeClass(a).addClass(b);
}});var InputValidator=new Class({Implements:[Options],options:{errorMsg:"Validation failed.",test:function(a){return true;}},initialize:function(b,a){this.setOptions(a);
this.className=b;},test:function(b,a){if(document.id(b)){return this.options.test(document.id(b),a||this.getProps(b));}else{return false;}},getError:function(c,a){var b=this.options.errorMsg;
if($type(b)=="function"){b=b(document.id(c),a||this.getProps(c));}return b;},getProps:function(a){if(!document.id(a)){return{};}return a.get("validatorProps");
}});Element.Properties.validatorProps={set:function(a){return this.eliminate("validatorProps").store("validatorProps",a);},get:function(a){if(a){this.set(a);}if(this.retrieve("validatorProps")){return this.retrieve("validatorProps");}if(this.getProperty("validatorProps")){try{this.store("validatorProps",JSON.decode(this.getProperty("validatorProps")));}catch(c){return{};}}else{var b=this.get("class").split(" ").filter(function(d){return d.test(":");});if(!b.length){this.store("validatorProps",{});}else{a={};
b.each(function(d){var g=d.split(":");if(g[1]){try{a[g[0]]=JSON.decode(g[1]);}catch(h){}}});this.store("validatorProps",a);}}return this.retrieve("validatorProps");
}};var FormValidator=new Class({Implements:[Options,Events],Binds:["onSubmit"],options:{fieldSelectors:"input, select, textarea",ignoreHidden:true,useTitles:false,evaluateOnSubmit:true,evaluateFieldsOnBlur:true,evaluateFieldsOnChange:true,serial:true,stopOnFailure:true,warningPrefix:function(){return FormValidator.getMsg("warningPrefix")||"Warning: ";
},errorPrefix:function(){return FormValidator.getMsg("errorPrefix")||"Error: ";}},initialize:function(b,a){this.setOptions(a);this.element=document.id(b);
this.element.store("validator",this);this.warningPrefix=$lambda(this.options.warningPrefix)();this.errorPrefix=$lambda(this.options.errorPrefix)();if(this.options.evaluateOnSubmit){this.element.addEvent("submit",this.onSubmit);}if(this.options.evaluateFieldsOnBlur||this.options.evaluateFieldsOnChange){this.watchFields(this.getFields());}},toElement:function(){return this.element;
},getFields:function(){return(this.fields=this.element.getElements(this.options.fieldSelectors));},watchFields:function(a){a.each(function(b){if(this.options.evaluateFieldsOnBlur){b.addEvent("blur",this.validationMonitor.pass([b,false],this));}if(this.options.evaluateFieldsOnChange){b.addEvent("change",this.validationMonitor.pass([b,true],this));}},this);},validationMonitor:function(){$clear(this.timer);
this.timer=this.validateField.delay(50,this,arguments);},onSubmit:function(a){if(!this.validate(a)&&a){a.preventDefault();}else{this.reset();}},reset:function(){this.getFields().each(this.resetField,this);
return this;},validate:function(b){var a=this.getFields().map(function(c){return this.validateField(c,true);},this).every(function(c){return c;});this.fireEvent("formValidate",[a,this.element,b]);
if(this.options.stopOnFailure&&!a&&b){b.preventDefault();}return a;},validateField:function(j,a){if(this.paused){return true;}j=document.id(j);var d=!j.hasClass("validation-failed");
var g,i;if(this.options.serial&&!a){g=this.element.getElement(".validation-failed");i=this.element.getElement(".warning");}if(j&&(!g||a||j.hasClass("validation-failed")||(g&&!this.options.serial))){var c=j.className.split(" ").some(function(k){return this.getValidator(k);
},this);var h=[];j.className.split(" ").each(function(k){if(k&&!this.test(k,j)){h.include(k);}},this);d=h.length===0;if(c&&!j.hasClass("warnOnly")){if(d){j.addClass("validation-passed").removeClass("validation-failed");
this.fireEvent("elementPass",j);}else{j.addClass("validation-failed").removeClass("validation-passed");this.fireEvent("elementFail",[j,h]);}}if(!i){var e=j.className.split(" ").some(function(k){if(k.test("^warn-")||j.hasClass("warnOnly")){return this.getValidator(k.replace(/^warn-/,""));
}else{return null;}},this);j.removeClass("warning");var b=j.className.split(" ").map(function(k){if(k.test("^warn-")||j.hasClass("warnOnly")){return this.test(k.replace(/^warn-/,""),j,true);
}else{return null;}},this);}}return d;},test:function(b,d,e){var a=this.getValidator(b);d=document.id(d);if(d.hasClass("ignoreValidation")){return true;
}e=$pick(e,false);if(d.hasClass("warnOnly")){e=true;}var c=a?a.test(d):true;if(a&&this.isVisible(d)){this.fireEvent("elementValidate",[c,d,b,e]);}if(e){return true;
}return c;},isVisible:function(a){if(!this.options.ignoreHidden){return true;}while(a!=document.body){if(document.id(a).getStyle("display")=="none"){return false;
}a=a.getParent();}return true;},resetField:function(a){a=document.id(a);if(a){a.className.split(" ").each(function(b){if(b.test("^warn-")){b=b.replace(/^warn-/,"");}a.removeClass("validation-failed");a.removeClass("warning");a.removeClass("validation-passed");},this);}return this;},stop:function(){this.paused=true;
return this;},start:function(){this.paused=false;return this;},ignoreField:function(a,b){a=document.id(a);if(a){this.enforceField(a);if(b){a.addClass("warnOnly");}else{a.addClass("ignoreValidation");}}return this;},enforceField:function(a){a=document.id(a);if(a){a.removeClass("warnOnly").removeClass("ignoreValidation");}return this;}});FormValidator.getMsg=function(a){return MooTools.lang.get("FormValidator",a);};FormValidator.adders={validators:{},add:function(b,a){this.validators[b]=new InputValidator(b,a);
if(!this.initialize){this.implement({validators:this.validators});}},addAllThese:function(a){$A(a).each(function(b){this.add(b[0],b[1]);},this);},getValidator:function(a){return this.validators[a.split(":")[0]];
}};$extend(FormValidator,FormValidator.adders);FormValidator.implement(FormValidator.adders);FormValidator.add("IsEmpty",{errorMsg:false,test:function(a){if(a.type=="select-one"||a.type=="select"){return !(a.selectedIndex>=0&&a.options[a.selectedIndex].value!="");
}else{return((a.get("value")==null)||(a.get("value").length==0));}}});FormValidator.addAllThese([["required",{errorMsg:function(){return FormValidator.getMsg("required");
},test:function(a){return !FormValidator.getValidator("IsEmpty").test(a);}}],["minLength",{errorMsg:function(a,b){if($type(b.minLength)){return FormValidator.getMsg("minLength").substitute({minLength:b.minLength,length:a.get("value").length});
}else{return"";}},test:function(a,b){if($type(b.minLength)){return(a.get("value").length>=$pick(b.minLength,0));}else{return true;}}}],["maxLength",{errorMsg:function(a,b){if($type(b.maxLength)){return FormValidator.getMsg("maxLength").substitute({maxLength:b.maxLength,length:a.get("value").length});
}else{return"";}},test:function(a,b){return(a.get("value").length<=$pick(b.maxLength,10000));}}],["validate-integer",{errorMsg:FormValidator.getMsg.pass("integer"),test:function(a){return FormValidator.getValidator("IsEmpty").test(a)||(/^(-?[1-9]\d*|0)$/).test(a.get("value"));
}}],["validate-numeric",{errorMsg:FormValidator.getMsg.pass("numeric"),test:function(a){return FormValidator.getValidator("IsEmpty").test(a)||(/^-?(?:0$0(?=\d*\.)|[1-9]|0)\d*(\.\d+)?$/).test(a.get("value"));
}}],["validate-digits",{errorMsg:FormValidator.getMsg.pass("digits"),test:function(a){return FormValidator.getValidator("IsEmpty").test(a)||(/^[\d() .:\-\+#]+$/.test(a.get("value")));
}}],["validate-alpha",{errorMsg:FormValidator.getMsg.pass("alpha"),test:function(a){return FormValidator.getValidator("IsEmpty").test(a)||(/^[a-zA-Z]+$/).test(a.get("value"));
}}],["validate-alphanum",{errorMsg:FormValidator.getMsg.pass("alphanum"),test:function(a){return FormValidator.getValidator("IsEmpty").test(a)||!(/\W/).test(a.get("value"));
}}],["validate-date",{errorMsg:function(a,b){if(Date.parse){var c=b.dateFormat||"%x";return FormValidator.getMsg("dateSuchAs").substitute({date:new Date().format(c)});
}else{return FormValidator.getMsg("dateInFormatMDY");}},test:function(a,b){if(FormValidator.getValidator("IsEmpty").test(a)){return true;}var h;if(Date.parse){var g=b.dateFormat||"%x";
h=Date.parse(a.get("value"));var e=h.format(g);if(e!="invalid date"){a.set("value",e);}return !isNaN(h);}else{var c=/^(\d{2})\/(\d{2})\/(\d{4})$/;if(!c.test(a.get("value"))){return false;
}h=new Date(a.get("value").replace(c,"$1/$2/$3"));return(parseInt(RegExp.$1,10)==(1+h.getMonth()))&&(parseInt(RegExp.$2,10)==h.getDate())&&(parseInt(RegExp.$3,10)==h.getFullYear());
}}}],["validate-email",{errorMsg:FormValidator.getMsg.pass("email"),test:function(a){return FormValidator.getValidator("IsEmpty").test(a)||(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i).test(a.get("value"));
}}],["validate-url",{errorMsg:FormValidator.getMsg.pass("url"),test:function(a){return FormValidator.getValidator("IsEmpty").test(a)||(/^(https?|ftp|rmtp|mms):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i).test(a.get("value"));
}}],["validate-currency-dollar",{errorMsg:FormValidator.getMsg.pass("currencyDollar"),test:function(a){return FormValidator.getValidator("IsEmpty").test(a)||(/^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/).test(a.get("value"));
}}],["validate-one-required",{errorMsg:FormValidator.getMsg.pass("oneRequired"),test:function(a,b){var c=document.id(b["validate-one-required"])||a.parentNode;
return c.getElements("input").some(function(d){if(["checkbox","radio"].contains(d.get("type"))){return d.get("checked");}return d.get("value");});}}]]);
Element.Properties.validator={set:function(a){var b=this.retrieve("validator");if(b){b.setOptions(a);}return this.store("validator:options");},get:function(a){if(a||!this.retrieve("validator")){if(a||!this.retrieve("validator:options")){this.set("validator",a);}this.store("validator",new FormValidator(this,this.retrieve("validator:options")));}return this.retrieve("validator");}};Element.implement({validate:function(a){this.set("validator",a);
return this.get("validator",a).validate();}});FormValidator.Inline=new Class({Extends:FormValidator,options:{scrollToErrorsOnSubmit:true,scrollFxOptions:{transition:"quad:out",offset:{y:-20}}},initialize:function(b,a){this.parent(b,a);
this.addEvent("onElementValidate",function(h,g,e,i){var d=this.getValidator(e);if(!h&&d.getError(g)){if(i){g.addClass("warning");}var c=this.makeAdvice(e,g,d.getError(g),i);
this.insertAdvice(c,g);this.showAdvice(e,g);}else{this.hideAdvice(e,g);}});},makeAdvice:function(d,g,c,h){var e=(h)?this.warningPrefix:this.errorPrefix;
e+=(this.options.useTitles)?g.title||c:c;var a=(h)?"warning-advice":"validation-advice";var b=this.getAdvice(d,g);if(b){b=b.clone(true,true).set("html",e).replaces(b);}else{b=new Element("div",{html:e,styles:{display:"none"},id:"advice-"+d+"-"+this.getFieldId(g)}).addClass(a);}g.store("advice-"+d,b);return b;},getFieldId:function(a){return a.id?a.id:a.id="input_"+a.name;
},showAdvice:function(b,c){var a=this.getAdvice(b,c);if(a&&!c.retrieve(this.getPropName(b))&&(a.getStyle("display")=="none"||a.getStyle("visiblity")=="hidden"||a.getStyle("opacity")==0)){c.store(this.getPropName(b),true);
if(a.reveal){a.reveal();}else{a.setStyle("display","block");}}},hideAdvice:function(b,c){var a=this.getAdvice(b,c);if(a&&c.retrieve(this.getPropName(b))){c.store(this.getPropName(b),false);
if(a.dissolve){a.dissolve();}else{a.setStyle("display","none");}}},getPropName:function(a){return"advice"+a;},resetField:function(a){a=document.id(a);if(!a){return this;
}this.parent(a);a.className.split(" ").each(function(b){this.hideAdvice(b,a);},this);return this;},getAllAdviceMessages:function(d,c){var b=[];if(d.hasClass("ignoreValidation")&&!c){return b;
}var a=d.className.split(" ").some(function(h){var e=h.test("^warn-")||d.hasClass("warnOnly");if(e){h=h.replace(/^warn-/,"");}var g=this.getValidator(h);
if(!g){return;}b.push({message:g.getError(d),warnOnly:e,passed:g.test(),validator:g});},this);return b;},getAdvice:function(a,b){return b.retrieve("advice-"+a);
},insertAdvice:function(a,c){var b=c.get("validatorProps");if(!b.msgPos||!document.id(b.msgPos)){if(c.type.toLowerCase()=="radio"){c.getParent().adopt(a);}else{a.inject(document.id(c),"after");}}else{document.id(b.msgPos).grab(a);}},validateField:function(g,e){var a=this.parent(g,e);if(this.options.scrollToErrorsOnSubmit&&!a){var b=document.id(this).getElement(".validation-failed");
var c=document.id(this).getParent();while(c!=document.body&&c.getScrollSize().y==c.getSize().y){c=c.getParent();}var d=c.retrieve("fvScroller");if(!d&&window.Fx&&Fx.Scroll){d=new Fx.Scroll(c,this.options.scrollFxOptions);
c.store("fvScroller",d);}if(b){if(d){d.toElement(b);}else{c.scrollTo(c.getScroll().x,b.getPosition(c).y-20);}}}return a;}});FormValidator.addAllThese([["validate-enforce-oncheck",{test:function(a,b){if(a.checked){var c=a.getParent("form").retrieve("validator");
if(!c){return true;}(b.toEnforce||document.id(b.enforceChildrenOf).getElements("input, select, textarea")).map(function(d){c.enforceField(d);});}return true;
}}],["validate-ignore-oncheck",{test:function(a,b){if(a.checked){var c=a.getParent("form").retrieve("validator");if(!c){return true;}(b.toIgnore||document.id(b.ignoreChildrenOf).getElements("input, select, textarea")).each(function(d){c.ignoreField(d);
c.resetField(d);});}return true;}}],["validate-nospace",{errorMsg:function(){return FormValidator.getMsg("noSpace");},test:function(a,b){return !a.get("value").test(/\s/);
}}],["validate-toggle-oncheck",{test:function(b,c){var d=b.getParent("form").retrieve("validator");if(!d){return true;}var a=c.toToggle||document.id(c.toToggleChildrenOf).getElements("input, select, textarea");
if(!b.checked){a.each(function(e){d.ignoreField(e);d.resetField(e);});}else{a.each(function(e){d.enforceField(e);});}return true;}}],["validate-reqchk-bynode",{errorMsg:function(){return FormValidator.getMsg("reqChkByNode");
},test:function(a,b){return(document.id(b.nodeId).getElements(b.selector||"input[type=checkbox], input[type=radio]")).some(function(c){return c.checked;
});}}],["validate-required-check",{errorMsg:function(a,b){return b.useTitle?a.get("title"):FormValidator.getMsg("requiredChk");},test:function(a,b){return !!a.checked;
}}],["validate-reqchk-byname",{errorMsg:function(a,b){return FormValidator.getMsg("reqChkByName").substitute({label:b.label||a.get("type")});},test:function(b,d){var c=d.groupName||b.get("name");
var a=$$(document.getElementsByName(c)).some(function(h,g){return h.checked;});var e=b.getParent("form").retrieve("validator");if(a&&e){e.resetField(b);}return a;}}],["validate-match",{errorMsg:function(a,b){return FormValidator.getMsg("match").substitute({matchName:b.matchName||document.id(b.matchInput).get("name")});
},test:function(b,c){var d=b.get("value");var a=document.id(c.matchInput)&&document.id(c.matchInput).get("value");return d&&a?d==a:true;}}],["validate-after-date",{errorMsg:function(a,b){return FormValidator.getMsg("afterDate").substitute({label:b.afterLabel||(b.afterElement?FormValidator.getMsg("startDate"):FormValidator.getMsg("currentDate"))});
},test:function(b,c){var d=document.id(c.afterElement)?Date.parse(document.id(c.afterElement).get("value")):new Date();var a=Date.parse(b.get("value"));
return a&&d?a>=d:true;}}],["validate-before-date",{errorMsg:function(a,b){return FormValidator.getMsg("beforeDate").substitute({label:b.beforeLabel||(b.beforeElement?FormValidator.getMsg("endDate"):FormValidator.getMsg("currentDate"))});
},test:function(b,c){var d=Date.parse(b.get("value"));var a=document.id(c.beforeElement)?Date.parse(document.id(c.beforeElement).get("value")):new Date();
return a&&d?a>=d:true;}}],["validate-custom-required",{errorMsg:function(){return FormValidator.getMsg("required");},test:function(a,b){return a.get("value")!=b.emptyValue;
}}],["validate-same-month",{errorMsg:function(a,b){var c=document.id(b.sameMonthAs)&&document.id(b.sameMonthAs).get("value");var d=a.get("value");if(d!=""){return FormValidator.getMsg(c?"sameMonth":"startMonth");
}},test:function(a,b){var d=Date.parse(a.get("value"));var c=Date.parse(document.id(b.sameMonthAs)&&document.id(b.sameMonthAs).get("value"));return d&&c?d.format("%B")==c.format("%B"):true;
}}]]);var OverText=new Class({Implements:[Options,Events,Class.Occlude],Binds:["reposition","assert","focus"],options:{element:"label",positionOptions:{position:"upperLeft",edge:"upperLeft",offset:{x:4,y:2}},poll:false,pollInterval:250},property:"OverText",initialize:function(b,a){this.element=document.id(b);
if(this.occlude()){return this.occluded;}this.setOptions(a);this.attach(this.element);OverText.instances.push(this);if(this.options.poll){this.poll();}return this;
},toElement:function(){return this.element;},attach:function(){var a=this.options.textOverride||this.element.get("alt")||this.element.get("title");if(!a){return;}this.text=new Element(this.options.element,{"class":"overTxtLabel",styles:{lineHeight:"normal",position:"absolute"},html:a,events:{click:this.hide.pass(true,this)}}).inject(this.element,"after");
if(this.options.element=="label"){this.text.set("for",this.element.get("id"));}this.element.addEvents({focus:this.focus,blur:this.assert,change:this.assert}).store("OverTextDiv",this.text);
window.addEvent("resize",this.reposition.bind(this));this.assert(true);this.reposition();},startPolling:function(){this.pollingPaused=false;return this.poll();
},poll:function(a){if(this.poller&&!a){return this;}var b=function(){if(!this.pollingPaused){this.assert(true);}}.bind(this);if(a){$clear(this.poller);}else{this.poller=b.periodical(this.options.pollInterval,this);}return this;},stopPolling:function(){this.pollingPaused=true;return this.poll(true);},focus:function(){if(!this.text.isDisplayed()||this.element.get("disabled")){return;}this.hide();},hide:function(b){if(this.text.isDisplayed()&&!this.element.get("disabled")){this.text.hide();this.fireEvent("textHide",[this.text,this.element]);
this.pollingPaused=true;try{if(!b){this.element.fireEvent("focus").focus();}}catch(a){}}return this;},show:function(){if(!this.text.isDisplayed()){this.text.show();
this.reposition();this.fireEvent("textShow",[this.text,this.element]);this.pollingPaused=false;}return this;},assert:function(a){this[this.test()?"show":"hide"](a);},test:function(){var a=this.element.get("value");return !a;},reposition:function(){this.assert(true);if(!this.element.getParent()||!this.element.offsetHeight){return this.stopPolling().hide();
}if(this.test()){this.text.position($merge(this.options.positionOptions,{relativeTo:this.element}));}return this;}});OverText.instances=[];OverText.update=function(){return OverText.instances.map(function(a){if(a.element&&a.text){return a.reposition();
}return null;});};if(window.Fx&&Fx.Reveal){Fx.Reveal.implement({hideInputs:Browser.Engine.trident?"select, input, textarea, object, embed, .overTxtLabel":false});
}Fx.Elements=new Class({Extends:Fx.CSS,initialize:function(b,a){this.elements=this.subject=$$(b);this.parent(a);},compute:function(h,j,k){var c={};for(var d in h){var a=h[d],e=j[d],g=c[d]={};
for(var b in a){g[b]=this.parent(a[b],e[b],k);}}return c;},set:function(b){for(var c in b){var a=b[c];for(var d in a){this.render(this.elements[c],d,a[d],this.options.unit);}}return this;},start:function(c){if(!this.check(c)){return this;}var j={},k={};for(var d in c){var g=c[d],a=j[d]={},h=k[d]={};for(var b in g){var e=this.prepare(this.elements[d],b,g[b]);
a[b]=e.from;h[b]=e.to;}}return this.parent(j,k);}});var Accordion=Fx.Accordion=new Class({Extends:Fx.Elements,options:{display:0,show:false,height:true,width:false,opacity:true,fixedHeight:false,fixedWidth:false,wait:false,alwaysHide:false,trigger:"click",initialDisplayFx:true},initialize:function(){var c=Array.link(arguments,{container:Element.type,options:Object.type,togglers:$defined,elements:$defined});
this.parent(c.elements,c.options);this.togglers=$$(c.togglers);this.container=document.id(c.container);this.previous=-1;if(this.options.alwaysHide){this.options.wait=true;}if($chk(this.options.show)){this.options.display=false;this.previous=this.options.show;}if(this.options.start){this.options.display=false;this.options.show=false;}this.effects={};if(this.options.opacity){this.effects.opacity="fullOpacity";}if(this.options.width){this.effects.width=this.options.fixedWidth?"fullWidth":"offsetWidth";}if(this.options.height){this.effects.height=this.options.fixedHeight?"fullHeight":"scrollHeight";}for(var b=0,a=this.togglers.length;b<a;b++){this.addSection(this.togglers[b],this.elements[b]);}this.elements.each(function(e,d){if(this.options.show===d){this.fireEvent("active",[this.togglers[d],e]);}else{for(var g in this.effects){e.setStyle(g,0);}}},this);if($chk(this.options.display)){this.display(this.options.display,this.options.initialDisplayFx);}},addSection:function(d,b){d=document.id(d);
b=document.id(b);var e=this.togglers.contains(d);this.togglers.include(d);this.elements.include(b);var a=this.togglers.indexOf(d);d.addEvent(this.options.trigger,this.display.bind(this,a));
if(this.options.height){b.setStyles({"padding-top":0,"border-top":"none","padding-bottom":0,"border-bottom":"none"});}if(this.options.width){b.setStyles({"padding-left":0,"border-left":"none","padding-right":0,"border-right":"none"});
}b.fullOpacity=1;if(this.options.fixedWidth){b.fullWidth=this.options.fixedWidth;}if(this.options.fixedHeight){b.fullHeight=this.options.fixedHeight;}b.setStyle("overflow","hidden");
if(!e){for(var c in this.effects){b.setStyle(c,0);}}return this;},display:function(a,b){b=$pick(b,true);a=($type(a)=="element")?this.elements.indexOf(a):a;
if((this.timer&&this.options.wait)||(a===this.previous&&!this.options.alwaysHide)){return this;}this.previous=a;var c={};this.elements.each(function(g,e){c[e]={};
var d=(e!=a)||(this.options.alwaysHide&&(g.offsetHeight>0));this.fireEvent(d?"background":"active",[this.togglers[e],g]);for(var h in this.effects){c[e][h]=d?0:g[this.effects[h]];}},this);return b?this.start(c):this.set(c);}});Fx.Move=new Class({Extends:Fx.Morph,options:{relativeTo:document.body,position:"center",edge:false,offset:{x:0,y:0}},start:function(a){return this.parent(this.element.position($merge(this.options,a,{returnPos:true})));
}});Element.Properties.move={set:function(a){var b=this.retrieve("move");if(b){b.cancel();}return this.eliminate("move").store("move:options",$extend({link:"cancel"},a));
},get:function(a){if(a||!this.retrieve("move")){if(a||!this.retrieve("move:options")){this.set("move",a);}this.store("move",new Fx.Move(this,this.retrieve("move:options")));
}return this.retrieve("move");}};Element.implement({move:function(a){this.get("move").start(a);return this;}});Fx.Reveal=new Class({Extends:Fx.Morph,options:{styles:["padding","border","margin"],transitionOpacity:!Browser.Engine.trident4,mode:"vertical",display:"block",hideInputs:Browser.Engine.trident?"select, input, textarea, object, embed":false},dissolve:function(){try{if(!this.hiding&&!this.showing){if(this.element.getStyle("display")!="none"){this.hiding=true;
this.showing=false;this.hidden=true;var d=this.element.getComputedSize({styles:this.options.styles,mode:this.options.mode});var h=(this.element.style.height===""||this.element.style.height=="auto");
this.element.setStyle("display","block");if(this.options.transitionOpacity){d.opacity=1;}var b={};$each(d,function(i,e){b[e]=[i,0];},this);var g=this.element.getStyle("overflow");
this.element.setStyle("overflow","hidden");var a=this.options.hideInputs?this.element.getElements(this.options.hideInputs):null;this.$chain.unshift(function(){if(this.hidden){this.hiding=false;
$each(d,function(i,e){d[e]=i;},this);this.element.setStyles($merge({display:"none",overflow:g},d));if(h){if(["vertical","both"].contains(this.options.mode)){this.element.style.height="";}if(["width","both"].contains(this.options.mode)){this.element.style.width="";}}if(a){a.setStyle("visibility","visible");}}this.fireEvent("hide",this.element);
this.callChain();}.bind(this));if(a){a.setStyle("visibility","hidden");}this.start(b);}else{this.callChain.delay(10,this);this.fireEvent("complete",this.element);
this.fireEvent("hide",this.element);}}else{if(this.options.link=="chain"){this.chain(this.dissolve.bind(this));}else{if(this.options.link=="cancel"&&!this.hiding){this.cancel();
this.dissolve();}}}}catch(c){this.hiding=false;this.element.setStyle("display","none");this.callChain.delay(10,this);this.fireEvent("complete",this.element);
this.fireEvent("hide",this.element);}return this;},reveal:function(){try{if(!this.showing&&!this.hiding){if(this.element.getStyle("display")=="none"||this.element.getStyle("visiblity")=="hidden"||this.element.getStyle("opacity")==0){this.showing=true;
this.hiding=false;this.hidden=false;var h,d;this.element.measure(function(){h=(this.element.style.height===""||this.element.style.height=="auto");d=this.element.getComputedSize({styles:this.options.styles,mode:this.options.mode});
}.bind(this));$each(d,function(i,e){d[e]=i;});if($chk(this.options.heightOverride)){d.height=this.options.heightOverride.toInt();}if($chk(this.options.widthOverride)){d.width=this.options.widthOverride.toInt();}if(this.options.transitionOpacity){this.element.setStyle("opacity",0);d.opacity=1;}var b={height:0,display:this.options.display};$each(d,function(i,e){b[e]=0;});var g=this.element.getStyle("overflow");this.element.setStyles($merge(b,{overflow:"hidden"}));var a=this.options.hideInputs?this.element.getElements(this.options.hideInputs):null;
if(a){a.setStyle("visibility","hidden");}this.start(d);this.$chain.unshift(function(){this.element.setStyle("overflow",g);if(!this.options.heightOverride&&h){if(["vertical","both"].contains(this.options.mode)){this.element.style.height="";}if(["width","both"].contains(this.options.mode)){this.element.style.width="";}}if(!this.hidden){this.showing=false;}if(a){a.setStyle("visibility","visible");}this.callChain();this.fireEvent("show",this.element);}.bind(this));}else{this.callChain();this.fireEvent("complete",this.element);this.fireEvent("show",this.element);}}else{if(this.options.link=="chain"){this.chain(this.reveal.bind(this));}else{if(this.options.link=="cancel"&&!this.showing){this.cancel();this.reveal();}}}}catch(c){this.element.setStyles({display:this.options.display,visiblity:"visible",opacity:1});this.showing=false;this.callChain.delay(10,this);this.fireEvent("complete",this.element);
this.fireEvent("show",this.element);}return this;},toggle:function(){if(this.element.getStyle("display")=="none"||this.element.getStyle("visiblity")=="hidden"||this.element.getStyle("opacity")==0){this.reveal();}else{this.dissolve();}return this;}});Element.Properties.reveal={set:function(a){var b=this.retrieve("reveal");if(b){b.cancel();}return this.eliminate("reveal").store("reveal:options",$extend({link:"cancel"},a));
},get:function(a){if(a||!this.retrieve("reveal")){if(a||!this.retrieve("reveal:options")){this.set("reveal",a);}this.store("reveal",new Fx.Reveal(this,this.retrieve("reveal:options")));
}return this.retrieve("reveal");}};Element.Properties.dissolve=Element.Properties.reveal;Element.implement({reveal:function(a){this.get("reveal",a).reveal();
return this;},dissolve:function(a){this.get("reveal",a).dissolve();return this;},nix:function(){var a=Array.link(arguments,{destroy:Boolean.type,options:Object.type});
this.get("reveal",a.options).dissolve().chain(function(){this[a.destroy?"destroy":"dispose"]();}.bind(this));return this;},wink:function(){var b=Array.link(arguments,{duration:Number.type,options:Object.type});
var a=this.get("reveal",b.options);a.reveal().chain(function(){(function(){a.dissolve();}).delay(b.duration||2000);});}});Fx.Scroll=new Class({Extends:Fx,options:{offset:{x:0,y:0},wheelStops:true},initialize:function(b,a){this.element=this.subject=document.id(b);
this.parent(a);var d=this.cancel.bind(this,false);if($type(this.element)!="element"){this.element=document.id(this.element.getDocument().body);}var c=this.element;
if(this.options.wheelStops){this.addEvent("start",function(){c.addEvent("mousewheel",d);},true);this.addEvent("complete",function(){c.removeEvent("mousewheel",d);},true);}},set:function(){var a=Array.flatten(arguments);this.element.scrollTo(a[0],a[1]);},compute:function(c,b,a){return[0,1].map(function(d){return Fx.compute(c[d],b[d],a);
});},start:function(c,i){if(!this.check(c,i)){return this;}var e=this.element.getSize(),g=this.element.getScrollSize();var b=this.element.getScroll(),d={x:c,y:i};
for(var h in d){var a=g[h]-e[h];if($chk(d[h])){d[h]=($type(d[h])=="number")?d[h].limit(0,a):a;}else{d[h]=b[h];}d[h]+=this.options.offset[h];}return this.parent([b.x,b.y],[d.x,d.y]);
},toTop:function(){return this.start(false,0);},toLeft:function(){return this.start(0,false);},toRight:function(){return this.start("right",false);},toBottom:function(){return this.start(false,"bottom");
},toElement:function(b){var a=document.id(b).getPosition(this.element);return this.start(a.x,a.y);},scrollIntoView:function(c,e,d){e=e?$splat(e):["x","y"];
var i={};c=document.id(c);var g=c.getPosition(this.element);var j=c.getSize();var h=this.element.getScroll();var a=this.element.getSize();var b={x:g.x+j.x,y:g.y+j.y};
["x","y"].each(function(k){if(e.contains(k)){if(b[k]>h[k]+a[k]){i[k]=b[k]-a[k];}if(g[k]<h[k]){i[k]=g[k];}}if(i[k]==null){i[k]=h[k];}if(d&&d[k]){i[k]=i[k]+d[k];}},this);if(i.x!=h.x||i.y!=h.y){this.start(i.x,i.y);}return this;}});Fx.Slide=new Class({Extends:Fx,options:{mode:"vertical"},initialize:function(b,a){this.addEvent("complete",function(){this.open=(this.wrapper["offset"+this.layout.capitalize()]!=0);
if(this.open&&Browser.Engine.webkit419){this.element.dispose().inject(this.wrapper);}},true);this.element=this.subject=document.id(b);this.parent(a);var c=this.element.retrieve("wrapper");
this.wrapper=c||new Element("div",{styles:$extend(this.element.getStyles("margin","position"),{overflow:"hidden"})}).wraps(this.element);this.element.store("wrapper",this.wrapper).setStyle("margin",0);
this.now=[];this.open=true;},vertical:function(){this.margin="margin-top";this.layout="height";this.offset=this.element.offsetHeight;},horizontal:function(){this.margin="margin-left";
this.layout="width";this.offset=this.element.offsetWidth;},set:function(a){this.element.setStyle(this.margin,a[0]);this.wrapper.setStyle(this.layout,a[1]);
return this;},compute:function(c,b,a){return[0,1].map(function(d){return Fx.compute(c[d],b[d],a);});},start:function(b,e){if(!this.check(b,e)){return this;
}this[e||this.options.mode]();var d=this.element.getStyle(this.margin).toInt();var c=this.wrapper.getStyle(this.layout).toInt();var a=[[d,c],[0,this.offset]];
var h=[[d,c],[-this.offset,0]];var g;switch(b){case"in":g=a;break;case"out":g=h;break;case"toggle":g=(c==0)?a:h;}return this.parent(g[0],g[1]);},slideIn:function(a){return this.start("in",a);
},slideOut:function(a){return this.start("out",a);},hide:function(a){this[a||this.options.mode]();this.open=false;return this.set([-this.offset,0]);},show:function(a){this[a||this.options.mode]();
this.open=true;return this.set([0,this.offset]);},toggle:function(a){return this.start("toggle",a);}});Element.Properties.slide={set:function(b){var a=this.retrieve("slide");
if(a){a.cancel();}return this.eliminate("slide").store("slide:options",$extend({link:"cancel"},b));},get:function(a){if(a||!this.retrieve("slide")){if(a||!this.retrieve("slide:options")){this.set("slide",a);}this.store("slide",new Fx.Slide(this,this.retrieve("slide:options")));}return this.retrieve("slide");}};Element.implement({slide:function(d,e){d=d||"toggle";
var b=this.get("slide"),a;switch(d){case"hide":b.hide(e);break;case"show":b.show(e);break;case"toggle":var c=this.retrieve("slide:flag",b.open);b[c?"slideOut":"slideIn"](e);
this.store("slide:flag",!c);a=true;break;default:b.start(d,e);}if(!a){this.eliminate("slide:flag");}return this;}});var SmoothScroll=Fx.SmoothScroll=new Class({Extends:Fx.Scroll,initialize:function(b,c){c=c||document;
this.doc=c.getDocument();var d=c.getWindow();this.parent(this.doc,b);this.links=this.options.links?$$(this.options.links):$$(this.doc.links);var a=d.location.href.match(/^[^#]*/)[0]+"#";
this.links.each(function(g){if(g.href.indexOf(a)!=0){return;}var e=g.href.substr(a.length);if(e){this.useLink(g,e);}},this);if(!Browser.Engine.webkit419){this.addEvent("complete",function(){d.location.hash=this.anchor;},true);}},useLink:function(c,a){var b;c.addEvent("click",function(d){if(b!==false&&!b){b=document.id(a)||this.doc.getElement("a[name="+a+"]");}if(b){d.preventDefault();
this.anchor=a;this.toElement(b);c.blur();}}.bind(this));}});Fx.Sort=new Class({Extends:Fx.Elements,options:{mode:"vertical"},initialize:function(b,a){this.parent(b,a);
this.elements.each(function(c){if(c.getStyle("position")=="static"){c.setStyle("position","relative");}});this.setDefaultOrder();},setDefaultOrder:function(){this.currentOrder=this.elements.map(function(b,a){return a;
});},sort:function(e){if($type(e)!="array"){return false;}var j=0;var a=0;var i={};var d=this.options.mode=="vertical";var g=this.elements.map(function(n,k){var m=n.getComputedSize({styles:["border","padding","margin"]});
var o;if(d){o={top:j,margin:m["margin-top"],height:m.totalHeight};j+=o.height-m["margin-top"];}else{o={left:a,margin:m["margin-left"],width:m.totalWidth};
a+=o.width;}var l=d?"top":"left";i[k]={};var p=n.getStyle(l).toInt();i[k][l]=p||0;return o;},this);this.set(i);e=e.map(function(k){return k.toInt();});
if(e.length!=this.elements.length){this.currentOrder.each(function(k){if(!e.contains(k)){e.push(k);}});if(e.length>this.elements.length){e.splice(this.elements.length-1,e.length-this.elements.length);}}j=0;a=0;var b=0;var c={};e.each(function(m,k){var l={};if(d){l.top=j-g[m].top-b;j+=g[m].height;}else{l.left=a-g[m].left;a+=g[m].width;}b=b+g[m].margin;
c[m]=l;},this);var h={};$A(e).sort().each(function(k){h[k]=c[k];});this.start(h);this.currentOrder=e;return this;},rearrangeDOM:function(a){a=a||this.currentOrder;
var b=this.elements[0].getParent();var c=[];this.elements.setStyle("opacity",0);a.each(function(d){c.push(this.elements[d].inject(b).setStyles({top:0,left:0}));
},this);this.elements.setStyle("opacity",1);this.elements=$$(c);this.setDefaultOrder();return this;},getDefaultOrder:function(){return this.elements.map(function(b,a){return a;
});},forward:function(){return this.sort(this.getDefaultOrder());},backward:function(){return this.sort(this.getDefaultOrder().reverse());},reverse:function(){return this.sort(this.currentOrder.reverse());
},sortByElements:function(a){return this.sort(a.map(function(b){return this.elements.indexOf(b);},this));},swap:function(c,b){if($type(c)=="element"){c=this.elements.indexOf(c);}if($type(b)=="element"){b=this.elements.indexOf(b);}var a=$A(this.currentOrder);a[this.currentOrder.indexOf(c)]=b;a[this.currentOrder.indexOf(b)]=c;this.sort(a);
}});var Drag=new Class({Implements:[Events,Options],options:{snap:6,unit:"px",grid:false,style:true,limit:false,handle:false,invert:false,preventDefault:false,modifiers:{x:"left",y:"top"}},initialize:function(){var b=Array.link(arguments,{options:Object.type,element:$defined});
this.element=document.id(b.element);this.document=this.element.getDocument();this.setOptions(b.options||{});var a=$type(this.options.handle);this.handles=((a=="array"||a=="collection")?$$(this.options.handle):document.id(this.options.handle))||this.element;
this.mouse={now:{},pos:{}};this.value={start:{},now:{}};this.selection=(Browser.Engine.trident)?"selectstart":"mousedown";this.bound={start:this.start.bind(this),check:this.check.bind(this),drag:this.drag.bind(this),stop:this.stop.bind(this),cancel:this.cancel.bind(this),eventStop:$lambda(false)};
this.attach();},attach:function(){this.handles.addEvent("mousedown",this.bound.start);return this;},detach:function(){this.handles.removeEvent("mousedown",this.bound.start);
return this;},start:function(c){if(this.options.preventDefault){c.preventDefault();}this.mouse.start=c.page;this.fireEvent("beforeStart",this.element);
var a=this.options.limit;this.limit={x:[],y:[]};for(var d in this.options.modifiers){if(!this.options.modifiers[d]){continue;}if(this.options.style){this.value.now[d]=this.element.getStyle(this.options.modifiers[d]).toInt();}else{this.value.now[d]=this.element[this.options.modifiers[d]];}if(this.options.invert){this.value.now[d]*=-1;}this.mouse.pos[d]=c.page[d]-this.value.now[d];
if(a&&a[d]){for(var b=2;b--;b){if($chk(a[d][b])){this.limit[d][b]=$lambda(a[d][b])();}}}}if($type(this.options.grid)=="number"){this.options.grid={x:this.options.grid,y:this.options.grid};
}this.document.addEvents({mousemove:this.bound.check,mouseup:this.bound.cancel});this.document.addEvent(this.selection,this.bound.eventStop);},check:function(a){if(this.options.preventDefault){a.preventDefault();}var b=Math.round(Math.sqrt(Math.pow(a.page.x-this.mouse.start.x,2)+Math.pow(a.page.y-this.mouse.start.y,2)));if(b>this.options.snap){this.cancel();this.document.addEvents({mousemove:this.bound.drag,mouseup:this.bound.stop});
this.fireEvent("start",[this.element,a]).fireEvent("snap",this.element);}},drag:function(a){if(this.options.preventDefault){a.preventDefault();}this.mouse.now=a.page;
for(var b in this.options.modifiers){if(!this.options.modifiers[b]){continue;}this.value.now[b]=this.mouse.now[b]-this.mouse.pos[b];if(this.options.invert){this.value.now[b]*=-1;}if(this.options.limit&&this.limit[b]){if($chk(this.limit[b][1])&&(this.value.now[b]>this.limit[b][1])){this.value.now[b]=this.limit[b][1];}else{if($chk(this.limit[b][0])&&(this.value.now[b]<this.limit[b][0])){this.value.now[b]=this.limit[b][0];}}}if(this.options.grid[b]){this.value.now[b]-=((this.value.now[b]-(this.limit[b][0]||0))%this.options.grid[b]);}if(this.options.style){this.element.setStyle(this.options.modifiers[b],this.value.now[b]+this.options.unit);}else{this.element[this.options.modifiers[b]]=this.value.now[b];}}this.fireEvent("drag",[this.element,a]);},cancel:function(a){this.document.removeEvent("mousemove",this.bound.check);
this.document.removeEvent("mouseup",this.bound.cancel);if(a){this.document.removeEvent(this.selection,this.bound.eventStop);this.fireEvent("cancel",this.element);}},stop:function(a){this.document.removeEvent(this.selection,this.bound.eventStop);this.document.removeEvent("mousemove",this.bound.drag);this.document.removeEvent("mouseup",this.bound.stop);
if(a){this.fireEvent("complete",[this.element,a]);}}});Element.implement({makeResizable:function(a){var b=new Drag(this,$merge({modifiers:{x:"width",y:"height"}},a));
this.store("resizer",b);return b.addEvent("drag",function(){this.fireEvent("resize",b);}.bind(this));}});Drag.Move=new Class({Extends:Drag,options:{droppables:[],container:false,precalculate:false,includeMargins:true,checkDroppables:true},initialize:function(c,b){this.parent(c,b);
this.droppables=$$(this.options.droppables);this.container=document.id(this.options.container);if(this.container&&$type(this.container)!="element"){this.container=document.id(this.container.getDocument().body);}var a=this.element.getStyle("position");if(a=="static"){a="absolute";}if([this.element.getStyle("left"),this.element.getStyle("top")].contains("auto")){this.element.position(this.element.getPosition(this.element.offsetParent));}this.element.setStyle("position",a);this.addEvent("start",this.checkDroppables,true);this.overed=null;},start:function(g){if(this.container){var b=this.container.getCoordinates(this.element.getOffsetParent()),c={},e={};
["top","right","bottom","left"].each(function(h){c[h]=this.container.getStyle("border-"+h).toInt();e[h]=this.element.getStyle("margin-"+h).toInt();},this);
var d=this.element.offsetWidth+e.left+e.right;var a=this.element.offsetHeight+e.top+e.bottom;if(this.options.includeMargins){$each(e,function(i,h){e[h]=0;});}if(this.container==this.element.getOffsetParent()){this.options.limit={x:[0-e.left,b.right-c.left-c.right-d+e.right],y:[0-e.top,b.bottom-c.top-c.bottom-a+e.bottom]};
}else{this.options.limit={x:[b.left+c.left-e.left,b.right-c.right-d+e.right],y:[b.top+c.top-e.top,b.bottom-c.bottom-a+e.bottom]};}}if(this.options.precalculate){this.positions=this.droppables.map(function(h){return h.getCoordinates();
});}this.parent(g);},checkAgainst:function(c,b){c=(this.positions)?this.positions[b]:c.getCoordinates();var a=this.mouse.now;return(a.x>c.left&&a.x<c.right&&a.y<c.bottom&&a.y>c.top);
},checkDroppables:function(){var a=this.droppables.filter(this.checkAgainst,this).getLast();if(this.overed!=a){if(this.overed){this.fireEvent("leave",[this.element,this.overed]);}if(a){this.fireEvent("enter",[this.element,a]);}this.overed=a;}},drag:function(a){this.parent(a);if(this.options.checkDroppables&&this.droppables.length){this.checkDroppables();}},stop:function(a){this.checkDroppables();this.fireEvent("drop",[this.element,this.overed,a]);this.overed=null;return this.parent(a);}});Element.implement({makeDraggable:function(a){var b=new Drag.Move(this,a);
this.store("dragger",b);return b;}});var Slider=new Class({Implements:[Events,Options],Binds:["clickedElement","draggedKnob","scrolledElement"],options:{onTick:function(a){if(this.options.snap){a=this.toPosition(this.step);}this.knob.setStyle(this.property,a);},snap:false,offset:0,range:false,wheel:false,steps:100,mode:"horizontal"},initialize:function(g,a,e){this.setOptions(e);
this.element=document.id(g);this.knob=document.id(a);this.previousChange=this.previousEnd=this.step=-1;var h,b={},d={x:false,y:false};switch(this.options.mode){case"vertical":this.axis="y";
this.property="top";h="offsetHeight";break;case"horizontal":this.axis="x";this.property="left";h="offsetWidth";}this.half=this.knob[h]/2;this.full=this.element[h]-this.knob[h]+(this.options.offset*2);
this.min=$chk(this.options.range[0])?this.options.range[0]:0;this.max=$chk(this.options.range[1])?this.options.range[1]:this.options.steps;this.range=this.max-this.min;
this.steps=this.options.steps||this.full;this.stepSize=Math.abs(this.range)/this.steps;this.stepWidth=this.stepSize*this.full/Math.abs(this.range);this.knob.setStyle("position","relative").setStyle(this.property,-this.options.offset);
d[this.axis]=this.property;b[this.axis]=[-this.options.offset,this.full-this.options.offset];this.bound={clickedElement:this.clickedElement.bind(this),scrolledElement:this.scrolledElement.bindWithEvent(this),draggedKnob:this.draggedKnob.bind(this)};
var c={snap:0,limit:b,modifiers:d,onDrag:this.bound.draggedKnob,onStart:this.bound.draggedKnob,onBeforeStart:(function(){this.isDragging=true;}).bind(this),onComplete:function(){this.isDragging=false;
this.draggedKnob();this.end();}.bind(this)};if(this.options.snap){c.grid=Math.ceil(this.stepWidth);c.limit[this.axis][1]=this.full;}this.drag=new Drag(this.knob,c);
this.attach();},attach:function(){this.element.addEvent("mousedown",this.bound.clickedElement);if(this.options.wheel){this.element.addEvent("mousewheel",this.bound.scrolledElement);}this.drag.attach();return this;},detach:function(){this.element.removeEvent("mousedown",this.bound.clickedElement);this.element.removeEvent("mousewheel",this.bound.scrolledElement);
this.drag.detach();return this;},set:function(a){if(!((this.range>0)^(a<this.min))){a=this.min;}if(!((this.range>0)^(a>this.max))){a=this.max;}this.step=Math.round(a);
this.checkStep();this.fireEvent("tick",this.toPosition(this.step));this.end();return this;},clickedElement:function(c){if(this.isDragging||c.target==this.knob){return;}var b=this.range<0?-1:1;var a=c.page[this.axis]-this.element.getPosition()[this.axis]-this.half;a=a.limit(-this.options.offset,this.full-this.options.offset);
this.step=Math.round(this.min+b*this.toStep(a));this.checkStep();this.fireEvent("tick",a);this.end();},scrolledElement:function(a){var b=(this.options.mode=="horizontal")?(a.wheel<0):(a.wheel>0);
this.set(b?this.step-this.stepSize:this.step+this.stepSize);a.stop();},draggedKnob:function(){var b=this.range<0?-1:1;var a=this.drag.value.now[this.axis];
a=a.limit(-this.options.offset,this.full-this.options.offset);this.step=Math.round(this.min+b*this.toStep(a));this.checkStep();},checkStep:function(){if(this.previousChange!=this.step){this.previousChange=this.step;
this.fireEvent("change",this.step);}},end:function(){if(this.previousEnd!==this.step){this.previousEnd=this.step;this.fireEvent("complete",this.step+"");}},toStep:function(a){var b=(a+this.options.offset)*this.stepSize/this.full*this.steps;return this.options.steps?Math.round(b-=b%this.stepSize):b;},toPosition:function(a){return(this.full*Math.abs(this.min-a))/(this.steps*this.stepSize)-this.options.offset;}});var Sortables=new Class({Implements:[Events,Options],options:{snap:4,opacity:1,clone:false,revert:false,handle:false,constrain:false},initialize:function(a,b){this.setOptions(b);
this.elements=[];this.lists=[];this.idle=true;this.addLists($$(document.id(a)||a));if(!this.options.clone){this.options.revert=false;}if(this.options.revert){this.effect=new Fx.Morph(null,$merge({duration:250,link:"cancel"},this.options.revert));
}},attach:function(){this.addLists(this.lists);return this;},detach:function(){this.lists=this.removeLists(this.lists);return this;},addItems:function(){Array.flatten(arguments).each(function(a){this.elements.push(a);
var b=a.retrieve("sortables:start",this.start.bindWithEvent(this,a));(this.options.handle?a.getElement(this.options.handle)||a:a).addEvent("mousedown",b);
},this);return this;},addLists:function(){Array.flatten(arguments).each(function(a){this.lists.push(a);this.addItems(a.getChildren());},this);return this;
},removeItems:function(){return $$(Array.flatten(arguments).map(function(a){this.elements.erase(a);var b=a.retrieve("sortables:start");(this.options.handle?a.getElement(this.options.handle)||a:a).removeEvent("mousedown",b);
return a;},this));},removeLists:function(){return $$(Array.flatten(arguments).map(function(a){this.lists.erase(a);this.removeItems(a.getChildren());return a;
},this));},getClone:function(b,a){if(!this.options.clone){return new Element("div").inject(document.body);}if($type(this.options.clone)=="function"){return this.options.clone.call(this,b,a,this.list);
}return a.clone(true).setStyles({margin:"0px",position:"absolute",visibility:"hidden",width:a.getStyle("width")}).inject(this.list).position(a.getPosition(a.getOffsetParent()));
},getDroppables:function(){var a=this.list.getChildren();if(!this.options.constrain){a=this.lists.concat(a).erase(this.list);}return a.erase(this.clone).erase(this.element);
},insert:function(c,b){var a="inside";if(this.lists.contains(b)){this.list=b;this.drag.droppables=this.getDroppables();}else{a=this.element.getAllPrevious().contains(b)?"before":"after";}this.element.inject(b,a);this.fireEvent("sort",[this.element,this.clone]);},start:function(b,a){if(!this.idle){return;}this.idle=false;this.element=a;
this.opacity=a.get("opacity");this.list=a.getParent();this.clone=this.getClone(b,a);this.drag=new Drag.Move(this.clone,{snap:this.options.snap,container:this.options.constrain&&this.element.getParent(),droppables:this.getDroppables(),onSnap:function(){b.stop();
this.clone.setStyle("visibility","visible");this.element.set("opacity",this.options.opacity||0);this.fireEvent("start",[this.element,this.clone]);}.bind(this),onEnter:this.insert.bind(this),onCancel:this.reset.bind(this),onComplete:this.end.bind(this)});
this.clone.inject(this.element,"before");this.drag.start(b);},end:function(){this.drag.detach();this.element.set("opacity",this.opacity);if(this.effect){var a=this.element.getStyles("width","height");
var b=this.clone.computePosition(this.element.getPosition(this.clone.offsetParent));this.effect.element=this.clone;this.effect.start({top:b.top,left:b.left,width:a.width,height:a.height,opacity:0.25}).chain(this.reset.bind(this));
}else{this.reset();}},reset:function(){this.idle=true;this.clone.destroy();this.fireEvent("complete",this.element);},serialize:function(){var c=Array.link(arguments,{modifier:Function.type,index:$defined});
var b=this.lists.map(function(d){return d.getChildren().map(c.modifier||function(e){return e.get("id");},this);},this);var a=c.index;if(this.lists.length==1){a=0;}return $chk(a)&&a>=0&&a<this.lists.length?b[a]:b;}});Request.JSONP=new Class({Implements:[Chain,Events,Options,Log],options:{url:"",data:{},retries:0,timeout:0,link:"ignore",callbackKey:"callback",injectScript:document.head},initialize:function(a){this.setOptions(a);
this.running=false;this.requests=0;this.triesRemaining=[];},check:function(){if(!this.running){return true;}switch(this.options.link){case"cancel":this.cancel();
return true;case"chain":this.chain(this.caller.bind(this,arguments));return false;}return false;},send:function(c){if(!$chk(arguments[1])&&!this.check(c)){return this;
}var e=$type(c),a=this.options,b=$chk(arguments[1])?arguments[1]:this.requests++;if(e=="string"||e=="element"){c={data:c};}c=$extend({data:a.data,url:a.url},c);
if(!$chk(this.triesRemaining[b])){this.triesRemaining[b]=this.options.retries;}var d=this.triesRemaining[b];(function(){var g=this.getScript(c);this.log("JSONP retrieving script with url: "+g.get("src"));
this.fireEvent("request",g);this.running=true;(function(){if(d){this.triesRemaining[b]=d-1;if(g){g.destroy();this.send(c,b);this.fireEvent("retry",this.triesRemaining[b]);}}else{if(g&&this.options.timeout){g.destroy();this.cancel();this.fireEvent("failure");}}}).delay(this.options.timeout,this);}).delay(Browser.Engine.trident?50:0,this);
return this;},cancel:function(){if(!this.running){return this;}this.running=false;this.fireEvent("cancel");return this;},getScript:function(c){var b=Request.JSONP.counter,d;
Request.JSONP.counter++;switch($type(c.data)){case"element":d=document.id(c.data).toQueryString();break;case"object":case"hash":d=Hash.toQueryString(c.data);}var e=c.url+(c.url.test("\\?")?"&":"?")+(c.callbackKey||this.options.callbackKey)+"=Request.JSONP.request_map.request_"+b+(d?"&"+d:"");if(e.length>2083){this.log("JSONP "+e+" will fail in Internet Explorer, which enforces a 2083 bytes length limit on URIs");
}var a=new Element("script",{type:"text/javascript",src:e});Request.JSONP.request_map["request_"+b]=function(g){this.success(g,a);}.bind(this);return a.inject(this.options.injectScript);
},success:function(b,a){if(a){a.destroy();}this.running=false;this.log("JSONP successfully retrieved: ",b);this.fireEvent("complete",[b]).fireEvent("success",[b]).callChain();
}});Request.JSONP.counter=0;Request.JSONP.request_map={};Request.Queue=new Class({Implements:[Options,Events],Binds:["attach","request","complete","cancel","success","failure","exception"],options:{stopOnFailure:true,autoAdvance:true,concurrent:1,requests:{}},initialize:function(a){this.setOptions(a);
this.requests=new Hash;this.addRequests(this.options.requests);this.queue=[];this.reqBinders={};},addRequest:function(a,b){this.requests.set(a,b);this.attach(a,b);
return this;},addRequests:function(a){$each(a,function(c,b){this.addRequest(b,c);},this);return this;},getName:function(a){return this.requests.keyOf(a);
},attach:function(a,b){if(b._groupSend){return this;}["request","complete","cancel","success","failure","exception"].each(function(c){if(!this.reqBinders[a]){this.reqBinders[a]={};
}this.reqBinders[a][c]=function(){this["on"+c.capitalize()].apply(this,[a,b].extend(arguments));}.bind(this);b.addEvent(c,this.reqBinders[a][c]);},this);
b._groupSend=b.send;b.send=function(c){this.send(a,c);return b;}.bind(this);return this;},removeRequest:function(b){var a=$type(b)=="object"?this.getName(b):b;
if(!a&&$type(a)!="string"){return this;}b=this.requests.get(a);if(!b){return this;}["request","complete","cancel","success","failure","exception"].each(function(c){b.removeEvent(c,this.reqBinders[a][c]);},this);b.send=b._groupSend;delete b._groupSend;return this;},getRunning:function(){return this.requests.filter(function(a){return a.running;});},isRunning:function(){return !!this.getRunning().getKeys().length;
},send:function(b,a){var c=function(){this.requests.get(b)._groupSend(a);this.queue.erase(c);}.bind(this);c.name=b;if(this.getRunning().getKeys().length>=this.options.concurrent||(this.error&&this.options.stopOnFailure)){this.queue.push(c);}else{c();}return this;},hasNext:function(a){return(!a)?!!this.queue.length:!!this.queue.filter(function(b){return b.name==a;}).length;},resume:function(){this.error=false;
(this.options.concurrent-this.getRunning().getKeys().length).times(this.runNext,this);return this;},runNext:function(a){if(!this.queue.length){return this;
}if(!a){this.queue[0]();}else{var b;this.queue.each(function(c){if(!b&&c.name==a){b=true;c();}});}return this;},runAll:function(){this.queue.each(function(a){a();});return this;},clear:function(a){if(!a){this.queue.empty();}else{this.queue=this.queue.map(function(b){if(b.name!=a){return b;}else{return false;}}).filter(function(b){return b;
});}return this;},cancel:function(a){this.requests.get(a).cancel();return this;},onRequest:function(){this.fireEvent("request",arguments);},onComplete:function(){this.fireEvent("complete",arguments);},onCancel:function(){if(this.options.autoAdvance&&!this.error){this.runNext();}this.fireEvent("cancel",arguments);},onSuccess:function(){if(this.options.autoAdvance&&!this.error){this.runNext();}this.fireEvent("success",arguments);},onFailure:function(){this.error=true;if(!this.options.stopOnFailure&&this.options.autoAdvance){this.runNext();}this.fireEvent("failure",arguments);
},onException:function(){this.error=true;if(!this.options.stopOnFailure&&this.options.autoAdvance){this.runNext();}this.fireEvent("exception",arguments);
}});Request.implement({options:{initialDelay:5000,delay:5000,limit:60000},startTimer:function(b){var a=(function(){if(!this.running){this.send({data:b});
}});this.timer=a.delay(this.options.initialDelay,this);this.lastDelay=this.options.initialDelay;this.completeCheck=function(c){$clear(this.timer);if(c){this.lastDelay=this.options.delay;}else{this.lastDelay=(this.lastDelay+this.options.delay).min(this.options.limit);}this.timer=a.delay(this.lastDelay,this);};this.addEvent("complete",this.completeCheck);
return this;},stopTimer:function(){$clear(this.timer);this.removeEvent("complete",this.completeCheck);return this;}});var Asset={javascript:function(g,d){d=$extend({onload:$empty,document:document,check:$lambda(true)},d);
var b=new Element("script",{src:g,type:"text/javascript"});var e=d.onload.bind(b),a=d.check,h=d.document;delete d.onload;delete d.check;delete d.document;
b.addEvents({load:e,readystatechange:function(){if(["loaded","complete"].contains(this.readyState)){e();}}}).set(d);if(Browser.Engine.webkit419){var c=(function(){if(!$try(a)){return;}$clear(c);e();}).periodical(50);}return b.inject(h.head);},css:function(b,a){return new Element("link",$merge({rel:"stylesheet",media:"screen",type:"text/css",href:b},a)).inject(document.head);
},image:function(c,b){b=$merge({onload:$empty,onabort:$empty,onerror:$empty},b);var d=new Image();var a=document.id(d)||new Element("img");["load","abort","error"].each(function(e){var g="on"+e;
var h=b[g];delete b[g];d[g]=function(){if(!d){return;}if(!a.parentNode){a.width=d.width;a.height=d.height;}d=d.onload=d.onabort=d.onerror=null;h.delay(1,a,a);
a.fireEvent(e,a,1);};});d.src=a.src=c;if(d&&d.complete){d.onload.delay(1);}return a.set(b);},images:function(d,c){c=$merge({onComplete:$empty,onProgress:$empty,onError:$empty,properties:{}},c);
d=$splat(d);var a=[];var b=0;return new Elements(d.map(function(e){return Asset.image(e,$extend(c.properties,{onload:function(){c.onProgress.call(this,b,d.indexOf(e));
b++;if(b==d.length){c.onComplete();}},onerror:function(){c.onError.call(this,b,d.indexOf(e));b++;if(b==d.length){c.onComplete();}}}));}));}};var Color=new Native({initialize:function(b,c){if(arguments.length>=3){c="rgb";
b=Array.slice(arguments,0,3);}else{if(typeof b=="string"){if(b.match(/rgb/)){b=b.rgbToHex().hexToRgb(true);}else{if(b.match(/hsb/)){b=b.hsbToRgb();}else{b=b.hexToRgb(true);}}}}c=c||"rgb";switch(c){case"hsb":var a=b;b=b.hsbToRgb();b.hsb=a;break;case"hex":b=b.hexToRgb(true);break;}b.rgb=b.slice(0,3);b.hsb=b.hsb||b.rgbToHsb();
b.hex=b.rgbToHex();return $extend(b,this);}});Color.implement({mix:function(){var a=Array.slice(arguments);var c=($type(a.getLast())=="number")?a.pop():50;
var b=this.slice();a.each(function(d){d=new Color(d);for(var e=0;e<3;e++){b[e]=Math.round((b[e]/100*(100-c))+(d[e]/100*c));}});return new Color(b,"rgb");
},invert:function(){return new Color(this.map(function(a){return 255-a;}));},setHue:function(a){return new Color([a,this.hsb[1],this.hsb[2]],"hsb");},setSaturation:function(a){return new Color([this.hsb[0],a,this.hsb[2]],"hsb");
},setBrightness:function(a){return new Color([this.hsb[0],this.hsb[1],a],"hsb");}});var $RGB=function(d,c,a){return new Color([d,c,a],"rgb");};var $HSB=function(d,c,a){return new Color([d,c,a],"hsb");
};var $HEX=function(a){return new Color(a,"hex");};Array.implement({rgbToHsb:function(){var b=this[0],c=this[1],k=this[2];var h,g,i;var j=Math.max(b,c,k),e=Math.min(b,c,k);
var l=j-e;i=j/255;g=(j!=0)?l/j:0;if(g==0){h=0;}else{var d=(j-b)/l;var a=(j-c)/l;var m=(j-k)/l;if(b==j){h=m-a;}else{if(c==j){h=2+d-m;}else{h=4+a-d;}}h/=6;
if(h<0){h++;}}return[Math.round(h*360),Math.round(g*100),Math.round(i*100)];},hsbToRgb:function(){var c=Math.round(this[2]/100*255);if(this[1]==0){return[c,c,c];}else{var a=this[0]%360;var e=a%60;var g=Math.round((this[2]*(100-this[1]))/10000*255);var d=Math.round((this[2]*(6000-this[1]*e))/600000*255);var b=Math.round((this[2]*(6000-this[1]*(60-e)))/600000*255);
switch(Math.floor(a/60)){case 0:return[c,b,g];case 1:return[d,c,g];case 2:return[g,c,b];case 3:return[g,d,c];case 4:return[b,g,c];case 5:return[c,g,d];
}}return false;}});String.implement({rgbToHsb:function(){var a=this.match(/\d{1,3}/g);return(a)?a.rgbToHsb():null;},hsbToRgb:function(){var a=this.match(/\d{1,3}/g);
return(a)?a.hsbToRgb():null;}});var Group=new Class({initialize:function(){this.instances=Array.flatten(arguments);this.events={};this.checker={};},addEvent:function(b,a){this.checker[b]=this.checker[b]||{};
this.events[b]=this.events[b]||[];if(this.events[b].contains(a)){return false;}else{this.events[b].push(a);}this.instances.each(function(c,d){c.addEvent(b,this.check.bind(this,[b,c,d]));},this);return this;},check:function(c,a,b){this.checker[c][b]=true;var d=this.instances.every(function(g,e){return this.checker[c][e]||false;},this);if(!d){return;}this.checker[c]={};this.events[c].each(function(e){e.call(this,this.instances,a);},this);}});Hash.Cookie=new Class({Extends:Cookie,options:{autoSave:true},initialize:function(b,a){this.parent(b,a);
this.load();},save:function(){var a=JSON.encode(this.hash);if(!a||a.length>4096){return false;}if(a=="{}"){this.dispose();}else{this.write(a);}return true;
},load:function(){this.hash=new Hash(JSON.decode(this.read(),true));return this;}});Hash.each(Hash.prototype,function(b,a){if(typeof b=="function"){Hash.Cookie.implement(a,function(){var c=b.apply(this.hash,arguments);
if(this.options.autoSave){this.save();}return c;});}});var IframeShim=new Class({Implements:[Options,Events,Class.Occlude],options:{className:"iframeShim",display:false,zIndex:null,margin:0,offset:{x:0,y:0},browsers:(Browser.Engine.trident4||(Browser.Engine.gecko&&!Browser.Engine.gecko19&&Browser.Platform.mac))},property:"IframeShim",initialize:function(b,a){this.element=document.id(b);
if(this.occlude()){return this.occluded;}this.setOptions(a);this.makeShim();return this;},makeShim:function(){if(this.options.browsers){var c=this.element.getStyle("zIndex").toInt();
if(!c){c=1;var b=this.element.getStyle("position");if(b=="static"||!b){this.element.setStyle("position","relative");}this.element.setStyle("zIndex",c);
}c=($chk(this.options.zIndex)&&c>this.options.zIndex)?this.options.zIndex:c-1;if(c<0){c=1;}this.shim=new Element("iframe",{src:'javascript:false;document.write("");',scrolling:"no",frameborder:0,styles:{zIndex:c,position:"absolute",border:"none",filter:"progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)"},"class":this.options.className}).store("IframeShim",this);
var a=(function(){this.shim.inject(this.element,"after");this[this.options.display?"show":"hide"]();this.fireEvent("inject");}).bind(this);if(Browser.Engine.trident&&!IframeShim.ready){window.addEvent("load",a);}else{a();}}else{this.position=this.hide=this.show=this.dispose=$lambda(this);}},position:function(){if(!IframeShim.ready){return this;}var a=this.element.measure(function(){return this.getSize();
});if($type(this.options.margin)){a.x=a.x-(this.options.margin*2);a.y=a.y-(this.options.margin*2);this.options.offset.x+=this.options.margin;this.options.offset.y+=this.options.margin;}if(this.shim){this.shim.set({width:a.x,height:a.y}).position({relativeTo:this.element,offset:this.options.offset});}return this;},hide:function(){if(this.shim){this.shim.setStyle("display","none");}return this;},show:function(){if(this.shim){this.shim.setStyle("display","block");}return this.position();},dispose:function(){if(this.shim){this.shim.dispose();}return this;},destroy:function(){if(this.shim){this.shim.destroy();}return this;}});window.addEvent("load",function(){IframeShim.ready=true;});var Scroller=new Class({Implements:[Events,Options],options:{area:20,velocity:1,onChange:function(a,b){this.element.scrollTo(a,b);},fps:50},initialize:function(b,a){this.setOptions(a);this.element=document.id(b);this.listener=($type(this.element)!="element")?document.id(this.element.getDocument().body):this.element;
this.timer=null;this.bound={attach:this.attach.bind(this),detach:this.detach.bind(this),getCoords:this.getCoords.bind(this)};},start:function(){this.listener.addEvents({mouseenter:this.bound.attach,mouseleave:this.bound.detach});
},stop:function(){this.listener.removeEvents({mouseenter:this.bound.attach,mouseleave:this.bound.detach});this.timer=$clear(this.timer);},attach:function(){this.listener.addEvent("mousemove",this.bound.getCoords);},detach:function(){this.listener.removeEvent("mousemove",this.bound.getCoords);this.timer=$clear(this.timer);},getCoords:function(a){this.page=(this.listener.get("tag")=="body")?a.client:a.page;
if(!this.timer){this.timer=this.scroll.periodical(Math.round(1000/this.options.fps),this);}},scroll:function(){var b=this.element.getSize(),a=this.element.getScroll(),g=this.element.getOffsets(),c=this.element.getScrollSize(),e={x:0,y:0};
for(var d in this.page){if(this.page[d]<(this.options.area+g[d])&&a[d]!=0){e[d]=(this.page[d]-this.options.area-g[d])*this.options.velocity;}else{if(this.page[d]+this.options.area>(b[d]+g[d])&&a[d]+b[d]!=c[d]){e[d]=(this.page[d]-b[d]+this.options.area-g[d])*this.options.velocity;}}}if(e.y||e.x){this.fireEvent("change",[a.x+e.x,a.y+e.y]);}}});var Tips=new Class({Implements:[Events,Options],options:{onShow:function(a){a.setStyle("visibility","visible");},onHide:function(a){a.setStyle("visibility","hidden");},title:"title",text:function(a){return a.get("rel")||a.get("href");},showDelay:100,hideDelay:100,className:null,offset:{x:16,y:16},fixed:false},initialize:function(){var a=Array.link(arguments,{options:Object.type,elements:$defined});
if(a.options&&a.options.offsets){a.options.offset=a.options.offsets;}this.setOptions(a.options);this.container=new Element("div",{"class":"tip"});this.tip=this.getTip();
if(a.elements){this.attach(a.elements);}},getTip:function(){return new Element("div",{"class":this.options.className,styles:{visibility:"hidden",display:"none",position:"absolute",top:0,left:0}}).adopt(new Element("div",{"class":"tip-top"}),this.container,new Element("div",{"class":"tip-bottom"})).inject(document.body);
},attach:function(b){var a=function(d,c){if(d==null){return"";}return $type(d)=="function"?d(c):c.get(d);};$$(b).each(function(d){var e=a(this.options.title,d);
d.erase("title").store("tip:native",e).retrieve("tip:title",e);d.retrieve("tip:text",a(this.options.text,d));var c=["enter","leave"];if(!this.options.fixed){c.push("move");}c.each(function(g){d.addEvent("mouse"+g,d.retrieve("tip:"+g,this["element"+g.capitalize()].bindWithEvent(this,d)));},this);},this);return this;},detach:function(a){$$(a).each(function(c){["enter","leave","move"].each(function(d){c.removeEvent("mouse"+d,c.retrieve("tip:"+d)||$empty);});c.eliminate("tip:enter").eliminate("tip:leave").eliminate("tip:move");if($type(this.options.title)=="string"&&this.options.title=="title"){var b=c.retrieve("tip:native");
if(b){c.set("title",b);}}},this);return this;},elementEnter:function(b,a){$A(this.container.childNodes).each(Element.dispose);["title","text"].each(function(d){var c=a.retrieve("tip:"+d);
if(!c){return;}this[d+"Element"]=new Element("div",{"class":"tip-"+d}).inject(this.container);this.fill(this[d+"Element"],c);},this);this.timer=$clear(this.timer);
this.timer=this.show.delay(this.options.showDelay,this,a);this.tip.setStyle("display","block");this.position((!this.options.fixed)?b:{page:a.getPosition()});
},elementLeave:function(b,a){$clear(this.timer);this.tip.setStyle("display","none");this.timer=this.hide.delay(this.options.hideDelay,this,a);},elementMove:function(a){this.position(a);},position:function(d){var b=window.getSize(),a=window.getScroll(),e={x:this.tip.offsetWidth,y:this.tip.offsetHeight},c={x:"left",y:"top"},g={};for(var h in c){g[c[h]]=d.page[h]+this.options.offset[h];
if((g[c[h]]+e[h]-a[h])>b[h]){g[c[h]]=d.page[h]-this.options.offset[h]-e[h];}}this.tip.setStyles(g);},fill:function(a,b){if(typeof b=="string"){a.set("html",b);}else{a.adopt(b);}},show:function(a){this.fireEvent("show",[this.tip,a]);},hide:function(a){this.fireEvent("hide",[this.tip,a]);}});MooTools.lang.set("en-US","Date",{months:["January","February","March","April","May","June","July","August","September","October","November","December"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dateOrder:["month","date","year"],shortDate:"%m/%d/%Y",shortTime:"%I:%M%p",AM:"AM",PM:"PM",ordinal:function(a){return(a>3&&a<21)?"th":["th","st","nd","rd","th"][Math.min(a%10,4)];},lessThanMinuteAgo:"less than a minute ago",minuteAgo:"about a minute ago",minutesAgo:"{delta} minutes ago",hourAgo:"about an hour ago",hoursAgo:"about {delta} hours ago",dayAgo:"1 day ago",daysAgo:"{delta} days ago",lessThanMinuteUntil:"less than a minute from now",minuteUntil:"about a minute from now",minutesUntil:"{delta} minutes from now",hourUntil:"about an hour from now",hoursUntil:"about {delta} hours from now",dayUntil:"1 day from now",daysUntil:"{delta} days from now"});
MooTools.lang.set("en-US","FormValidator",{required:"This field is required.",minLength:"Please enter at least {minLength} characters (you entered {length} characters).",maxLength:"Please enter no more than {maxLength} characters (you entered {length} characters).",integer:"Please enter an integer in this field. Numbers with decimals (e.g. 1.25) are not permitted.",numeric:'Please enter only numeric values in this field (i.e. "1" or "1.1" or "-1" or "-1.1").',digits:"Please use numbers and punctuation only in this field (for example, a phone number with dashes or dots is permitted).",alpha:"Please use letters only (a-z) with in this field. No spaces or other characters are allowed.",alphanum:"Please use only letters (a-z) or numbers (0-9) only in this field. No spaces or other characters are allowed.",dateSuchAs:"Please enter a valid date such as {date}",dateInFormatMDY:'Please enter a valid date such as MM/DD/YYYY (i.e. "12/31/1999")',email:'Please enter a valid email address. For example "fred@domain.com".',url:"Please enter a valid URL such as http://www.google.com.",currencyDollar:"Please enter a valid $ amount. For example $100.00 .",oneRequired:"Please enter something for at least one of these inputs.",errorPrefix:"Error: ",warningPrefix:"Warning: ",noSpace:"There can be no spaces in this input.",reqChkByNode:"No items are selected.",requiredChk:"This field is required.",reqChkByName:"Please select a {label}.",match:"This field needs to match the {matchName} field",startDate:"the start date",endDate:"the end date",currendDate:"the current date",afterDate:"The date should be the same or after {label}.",beforeDate:"The date should be the same or before {label}.",startMonth:"Please select a start month",sameMonth:"These two dates must be in the same month - you must change one or the other."});
/*  SWFObject v2.2 <http://code.google.com/p/swfobject/>
    is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();

/**
 * SqueezeBox - Expandable Lightbox
 *
 * Allows to open various content as modal,
 * centered and animated box.
 *
 * Dependencies: MooTools 1.2
 *
 * Inspired by
 *  ... Lokesh Dhakar   - The original Lightbox v2
 *
 * @version     1.1 rc4
 *
 * @license     MIT-style license
 * @author      Harald Kirschner <mail [at] digitarald.de>
 * @copyright   Author
 */

var SqueezeBox = {

    presets: {
        onOpen: $empty,
        onClose: $empty,
        onUpdate: $empty,
        onResize: $empty,
        onMove: $empty,
        onShow: $empty,
        onHide: $empty,
        size: {x: 600, y: 450},
        sizeLoading: {x: 200, y: 150},
        marginInner: {x: 20, y: 20},
        marginImage: {x: 50, y: 75},
        handler: false,
        target: null,
        closable: true,
        closeBtn: true,
        zIndex: 65555,
        overlayOpacity: 0.7,
        classWindow: '',
        classOverlay: '',
        overlayFx: {},
        resizeFx: {},
        contentFx: {},
        parse: false, // 'rel'
        parseSecure: false,
        shadow: true,
        document: null,
        ajaxOptions: {}},

    initialize: function(presets) {
        if (this.options) return this;

        this.presets = $merge(this.presets, presets);
        this.doc = this.presets.document || document;
        this.options = {};
        this.setOptions(this.presets).build();
        this.bound = {
            window: this.reposition.bind(this, [null]),
            scroll: this.checkTarget.bind(this),
            close: this.close.bind(this),
            key: this.onKey.bind(this)
        };
        this.isOpen = this.isLoading = false;
        return this;
    },

    build: function() {
        this.overlay = new Element('div', {
            id: 'sbox-overlay',
            styles: {display: 'none', zIndex: this.options.zIndex}
        });
        this.win = new Element('div', {
            id: 'sbox-window',
            styles: {display: 'none', zIndex: this.options.zIndex + 2}
        });
        if (this.options.shadow) {
            if (Browser.Engine.webkit420) {
                this.win.setStyle('-webkit-box-shadow', '0 0 10px rgba(0, 0, 0, 0.7)');
            } else if (!Browser.Engine.trident4) {
                var shadow = new Element('div', {'class': 'sbox-bg-wrap'}).inject(this.win);
                var relay = function(e) {
                    this.overlay.fireEvent('click', [e]);
                }.bind(this);
                ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'].each(function(dir) {
                    new Element('div', {'class': 'sbox-bg sbox-bg-' + dir}).inject(shadow).addEvent('click', relay);
                });
            }
        }
        this.content = new Element('div', {id: 'sbox-content'}).inject(this.win);
        this.closeBtn = new Element('a', {id: 'sbox-btn-close', href: '#'}).inject(this.win);
        this.fx = {
            overlay: new Fx.Tween(this.overlay, $merge({
                property: 'opacity',
                onStart: Events.prototype.clearChain,
                duration: 250,
                link: 'cancel'
            }, this.options.overlayFx)).set(0),
            win: new Fx.Morph(this.win, $merge({
                onStart: Events.prototype.clearChain,
                unit: 'px',
                duration: 750,
                transition: Fx.Transitions.Quint.easeOut,
                link: 'cancel',
                unit: 'px'
            }, this.options.resizeFx)),
            content: new Fx.Tween(this.content, $merge({
                property: 'opacity',
                duration: 250,
                link: 'cancel'
            }, this.options.contentFx)).set(0)
        };
        $(this.doc.body).adopt(this.overlay, this.win);
    },

    assign: function(to, options) {
        return ($(to) || $$(to)).addEvent('click', function() {
            return !SqueezeBox.fromElement(this, options);
        });
    },

    open: function(subject, options) {
        this.initialize();

        if (this.element != null) this.trash();
        this.element = $(subject) || false;

        this.setOptions($merge(this.presets, options || {}));

        if (this.element && this.options.parse) {
            var obj = this.element.getProperty(this.options.parse);
            if (obj && (obj = JSON.decode(obj, this.options.parseSecure))) this.setOptions(obj);
        }
        this.url = ((this.element) ? (this.element.get('href')) : subject) || this.options.url || '';

        this.assignOptions();

        var handler = handler || this.options.handler;
        if (handler) return this.setContent(handler, this.parsers[handler].call(this, true));
        var ret = false;
        return this.parsers.some(function(parser, key) {
            var content = parser.call(this);
            if (content) {
                ret = this.setContent(key, content);
                return true;
            }
            return false;
        }, this);
    },

    fromElement: function(from, options) {
        return this.open(from, options);
    },

    assignOptions: function() {
        this.overlay.set('class', this.options.classOverlay);
        this.win.set('class', this.options.classWindow);
        if (Browser.Engine.trident4) this.win.addClass('sbox-window-ie6');
    },

    close: function(e) {
        var stoppable = ($type(e) == 'event');
        if (stoppable) e.stop();
        if (!this.isOpen || (stoppable && !$lambda(this.options.closable).call(this, e))) return this;
        this.fx.overlay.start(0).chain(this.toggleOverlay.bind(this));
        this.win.setStyle('display', 'none');
        this.fireEvent('onClose', [this.content]);
        this.trash();
        this.toggleListeners();
        this.isOpen = false;
        return this;
    },

    trash: function() {
        this.element = this.asset = null;
        this.content.empty();
        this.options = {};
        this.removeEvents().setOptions(this.presets).callChain();
    },

    onError: function() {
        this.asset = null;
        this.setContent('string', this.options.errorMsg || 'An error occurred');
    },

    setContent: function(handler, content) {
        if (!this.handlers[handler]) return false;
        this.content.className = 'sbox-content-' + handler;
        this.applyTimer = this.applyContent.delay(this.fx.overlay.options.duration, this, this.handlers[handler].call(this, content));
        if (this.overlay.retrieve('opacity')) return this;
        this.toggleOverlay(true);
        this.fx.overlay.start(this.options.overlayOpacity);
        return this.reposition();
    },

    applyContent: function(content, size) {
        if (!this.isOpen && !this.applyTimer) return;
        this.applyTimer = $clear(this.applyTimer);
        this.hideContent();
        if (!content) {this.toggleLoading(true);} else {
            if (this.isLoading) this.toggleLoading(false);
            this.fireEvent('onUpdate', [this.content], 20);
        }
        if (content) {
            if (['string', 'array'].contains($type(content))) this.content.set('html', content);
            else if (!this.content.hasChild(content)) this.content.adopt(content);
        }
        this.callChain();
        if (!this.isOpen) {
            this.toggleListeners(true);
            this.resize(size, true);
            this.isOpen = true;
            this.fireEvent('onOpen', [this.content]);
        } else {this.resize(size);}
    },

    resize: function(size, instantly) {
        this.showTimer = $clear(this.showTimer || null);
        var box = this.doc.getSize(), scroll = this.doc.getScroll();
        this.size = $merge((this.isLoading) ? this.options.sizeLoading : this.options.size, size);
        var to = {
            width: this.size.x,
            height: this.size.y,
            left: (scroll.x + (box.x - this.size.x - this.options.marginInner.x) / 2).toInt(),
            top: (scroll.y + (box.y - this.size.y - this.options.marginInner.y) / 2).toInt()
        };
        this.hideContent();
        if (!instantly) {this.fx.win.start(to).chain(this.showContent.bind(this));} else {
            this.win.setStyles(to).setStyle('display', '');
            this.showTimer = this.showContent.delay(50, this);
        }
        return this.reposition();
    },

    toggleListeners: function(state) {
        var fn = (state) ? 'addEvent' : 'removeEvent';
        this.closeBtn[fn]('click', this.bound.close);
        this.overlay[fn]('click', this.bound.close);
        this.doc[fn]('keydown', this.bound.key)[fn]('mousewheel', this.bound.scroll);
        this.doc.getWindow()[fn]('resize', this.bound.window)[fn]('scroll', this.bound.window);
    },

    toggleLoading: function(state) {
        this.isLoading = state;
        this.win[(state) ? 'addClass' : 'removeClass']('sbox-loading');
        if (state) this.fireEvent('onLoading', [this.win]);
    },

    toggleOverlay: function(state) {
        var full = this.doc.getSize().x;
        this.overlay.setStyle('display', (state) ? '' : 'none');
        this.doc.body[(state) ? 'addClass' : 'removeClass']('body-overlayed');
        if (state) {
            this.scrollOffset = this.doc.getWindow().getSize().x - full;
            this.doc.body.setStyle('margin-right', this.scrollOffset);
        } else {
            this.doc.body.setStyle('margin-right', '');
        }
    },

    showContent: function() {
        if (this.content.get('opacity')) this.fireEvent('onShow', [this.win]);
        this.fx.content.start(1);
    },

    hideContent: function() {
        if (!this.content.get('opacity')) this.fireEvent('onHide', [this.win]);
        this.fx.content.cancel().set(0);
    },

    onKey: function(e) {
        switch (e.key) {
            case 'esc': this.close(e);
            case 'up': case 'down': return false;
        }
    },

    checkTarget: function(e) {
        return this.content.hasChild(e.target);
    },

    reposition: function() {
        var size = this.doc.getSize(), scroll = this.doc.getScroll(), ssize = this.doc.getScrollSize();
        this.overlay.setStyles({
            width: ssize.x + 'px',
            height: ssize.y + 'px'
        });
        this.win.setStyles({
            left: (scroll.x + (size.x - this.win.offsetWidth) / 2 - this.scrollOffset).toInt() + 'px',
            top: (scroll.y + (size.y - this.win.offsetHeight) / 2).toInt() + 'px'
        });
        return this.fireEvent('onMove', [this.overlay, this.win]);
    },

    removeEvents: function(type){
        if (!this.$events) return this;
        if (!type) this.$events = null;
        else if (this.$events[type]) this.$events[type] = null;
        return this;
    },

    extend: function(properties) {
        return $extend(this, properties);
    },

    handlers: new Hash(),

    parsers: new Hash()

};

SqueezeBox.extend(new Events($empty)).extend(new Options($empty)).extend(new Chain($empty));

SqueezeBox.parsers.extend({

    image: function(preset) {
        return (preset || (/\.(?:jpg|png|gif)$/i).test(this.url)) ? this.url : false;
    },

    clone: function(preset) {
        if ($(this.options.target)) return $(this.options.target);
        if (this.element && !this.element.parentNode) return this.element;
        var bits = this.url.match(/#([\w-]+)$/);
        return (bits) ? $(bits[1]) : (preset ? this.element : false);
    },

    ajax: function(preset) {
        return (preset || (this.url && !(/^(?:javascript|#)/i).test(this.url))) ? this.url : false;
    },

    iframe: function(preset) {
        return (preset || this.url) ? this.url : false;
    },

    string: function(preset) {
        return true;
    }
});

SqueezeBox.handlers.extend({

    image: function(url) {
        var size, tmp = new Image();
        this.asset = null;
        tmp.onload = tmp.onabort = tmp.onerror = (function() {
            tmp.onload = tmp.onabort = tmp.onerror = null;
            if (!tmp.width) {
                this.onError.delay(10, this);
                return;
            }
            var box = this.doc.getSize();
            box.x -= this.options.marginImage.x;
            box.y -= this.options.marginImage.y;
            size = {x: tmp.width, y: tmp.height};
            for (var i = 2; i--;) {
                if (size.x > box.x) {
                    size.y *= box.x / size.x;
                    size.x = box.x;
                } else if (size.y > box.y) {
                    size.x *= box.y / size.y;
                    size.y = box.y;
                }
            }
            size.x = size.x.toInt();
            size.y = size.y.toInt();
            this.asset = $(tmp);
            tmp = null;
            this.asset.width = size.x;
            this.asset.height = size.y;
            this.applyContent(this.asset, size);
        }).bind(this);
        tmp.src = url;
        if (tmp && tmp.onload && tmp.complete) tmp.onload();
        return (this.asset) ? [this.asset, size] : null;
    },

    clone: function(el) {
        if (el) return el.clone();
        return this.onError();
    },

    adopt: function(el) {
        if (el) return el;
        return this.onError();
    },

    ajax: function(url) {
        var options = this.options.ajaxOptions || {};
        this.asset = new Request.HTML($merge({
            method: 'get',
            evalScripts: false
        }, this.options.ajaxOptions)).addEvents({
            onSuccess: function(resp) {
                this.applyContent(resp);
                if (options.evalScripts !== null && !options.evalScripts) $exec(this.asset.response.javascript);
                this.fireEvent('onAjax', [resp, this.asset]);
                this.asset = null;
            }.bind(this),
            onFailure: this.onError.bind(this)
        });
        this.asset.send.delay(10, this.asset, [{url: url}]);
    },

    iframe: function(url) {
        this.asset = new Element('iframe', $merge({
            src: url,
            frameBorder: 0,
            width: this.options.size.x,
            height: this.options.size.y
        }, this.options.iframeOptions));
        if (this.options.iframePreload) {
            this.asset.addEvent('load', function() {
                this.applyContent(this.asset.setStyle('display', ''));
            }.bind(this));
            this.asset.setStyle('display', 'none').inject(this.content);
            return false;
        }
        return this.asset;
    },

    string: function(str) {
        return str;
    }

});

SqueezeBox.handlers.url = SqueezeBox.handlers.ajax;
SqueezeBox.parsers.url = SqueezeBox.parsers.ajax;
SqueezeBox.parsers.adopt = SqueezeBox.parsers.clone;

/***************************************
*
*   Javascript Textile->HTML conversion
*
*   ben@ben-daglish.net (with thanks to John Hughes for improvements)
*   Issued under the "do what you like with it - I take no respnsibility" licence
****************************************/

var inpr,inbq,inbqq,html;
var aliases = new Array;
var alg={'>':'right','<':'left','=':'center','<>':'justify','~':'bottom','^':'top'};
var ent={"'":"&#8217;"," - ":" &#8211; ","--":"&#8212;"," x ":" &#215; ","\\.\\.\\.":"&#8230;","\\(C\\)":"&#169;","\\(R\\)":"&#174;","\\(TM\\)":"&#8482;"};
var tags={"b":"\\*\\*","i":"__","em":"_","strong":"\\*","cite":"\\?\\?","sup":"\\^","sub":"~","span":"\\%","del":"-","code":"@","ins":"\\+","del":"-"};
var le="\n\n";
var lstlev=0,lst="",elst="",intable=0,mm="";
var para = /^p(\S*)\.\s*(.*)/;
var rfn = /^fn(\d+)\.\s*(.*)/;
var bq = /^bq\.(\.)?\s*/;
var table=/^table\s*{(.*)}\..*/;
var trstyle = /^\{(\S+)\}\.\s*\|/;

function convert(t) {
    var lines = t.split(/\r?\n/);
    html="";
    inpr=inbq=inbqq=0;
    for(var i=0;i<lines.length;i++) {
        if(lines[i].indexOf("[") == 0) {
            var m = lines[i].indexOf("]");
            aliases[lines[i].substring(1,m)]=lines[i].substring(m+1);
        }
    }
    for(i=0;i<lines.length;i++) {
        if (lines[i].indexOf("[") == 0) {continue;}
        if(mm=para.exec(lines[i])){stp(1);inpr=1;html += lines[i].replace(para,"<p"+make_attr(mm[1])+">"+prep(mm[2]));continue;}
        if(mm = /^h(\d)(\S*)\.\s*(.*)/.exec(lines[i])){stp(1);html += tag("h"+mm[1],make_attr(mm[2]),prep(mm[3]))+le;continue;}
        if(mm=rfn.exec(lines[i])){stp(1);inpr=1;html+=lines[i].replace(rfn,'<p id="fn'+mm[1]+'"><sup>'+mm[1]+'<\/sup>'+prep(mm[2]));continue;}
        if (lines[i].indexOf("*") == 0) {lst="<ul>";elst="<\/ul>";}
        else if (lines[i].indexOf("#") == 0) {lst="<\ol>";elst="<\/ol>";}
        else {while (lstlev > 0) {html += elst;if(lstlev > 1){html += "<\/li>";}else{html+="\n";}html+="\n";lstlev--;}lst="";}
        if(lst) {
            stp(1);
            var m = /^([*#]+)\s*(.*)/.exec(lines[i]);
            var lev = m[1].length;
            while(lev < lstlev) {html += elst+"<\/li>\n";lstlev--;}
            while(lstlev < lev) {html=html.replace(/<\/li>\n$/,"\n");html += lst;lstlev++;}
            html += tag("li","",prep(m[2]))+"\n";
            continue;
        }
        if (lines[i].match(table)){stp(1);intable=1;html += lines[i].replace(table,'<table style="$1;">\n');continue;}
        if ((lines[i].indexOf("|") == 0)  || (lines[i].match(trstyle)) ) {
            stp(1);
            if(!intable) {html += "<table>\n";intable=1;}
            var rowst="";var trow="";
            var ts=trstyle.exec(lines[i]);
            if(ts){rowst=qat('style',ts[1]);lines[i]=lines[i].replace(trstyle,"\|");}
            var cells = lines[i].split("|");
            for(j=1;j<cells.length-1;j++) {
                var ttag="td";
                if(cells[j].indexOf("_.")==0) {ttag="th";cells[j]=cells[j].substring(2);}
                cells[j]=prep(cells[j]);
                var al=/^([<>=^~\/\\\{]+.*?)\.(.*)/.exec(cells[j]);
                var at="",st="";
                if(al != null) {
                    cells[j]=al[2];
                    var cs= /\\(\d+)/.exec(al[1]);if(cs != null){at +=qat('colspan',cs[1]);}
                    var rs= /\/(\d+)/.exec(al[1]);if(rs != null){at +=qat('rowspan',rs[1]);}
                    var va= /([\^~])/.exec(al[1]);if(va != null){st +="vertical-align:"+alg[va[1]]+";";}
                    var ta= /(<>|=|<|>)/.exec(al[1]);if(ta != null){st +="text-align:"+alg[ta[1]]+";";}
                    var is= /\{([^\}]+)\}/.exec(al[1]);if(is != null){st +=is[1];}
                    if(st != ""){at+=qat('style',st);}
                }
                trow += tag(ttag,at,cells[j]);
            }
            html += "\t"+tag("tr",rowst,trow)+"\n";
            continue;
        }
        if(intable) {html += "<\/table>"+le;intable=0;}

        if (lines[i]=="") {stp();}
        else if (!inpr) {
            if(mm=bq.exec(lines[i])){lines[i]=lines[i].replace(bq,"");html +="<blockquote>";inbq=1;if(mm[1]) {inbqq=1;}}
            html += "<p>"+prep(lines[i]);inpr=1;
        }
        else {html += prep(lines[i]);}
    }
    stp();
    return html;
}

function prep(m){
    for(i in ent) {m=m.replace(new RegExp(i,"g"),ent[i]);}
    for(i in tags) {
        m = make_tag(m,RegExp("^"+tags[i]+"(.+?)"+tags[i]),i,"");
        m = make_tag(m,RegExp(" "+tags[i]+"(.+?)"+tags[i]),i," ");
    }
    m=m.replace(/\[(\d+)\]/g,'<sup><a href="#fn$1">$1<\/a><\/sup>');
    m=m.replace(/([A-Z]+)\((.*?)\)/g,'<acronym title="$2">$1<\/acronym>');
    m=m.replace(/\"([^\"]+)\":((http|https|mailto):\S+)/g,'<a href="$2">$1<\/a>');
    m = make_image(m,/!([^!\s]+)!:(\S+)/);
    m = make_image(m,/!([^!\s]+)!/);
    m=m.replace(/"([^\"]+)":(\S+)/g,function($0,$1,$2){return tag("a",qat('href',aliases[$2]),$1)});
    m=m.replace(/(=)?"([^\"]+)"/g,function($0,$1,$2){return ($1)?$0:"&#8220;"+$2+"&#8221;"});
    return m;
}

function make_tag(s,re,t,sp) {
    while(m = re.exec(s)) {
        var st = make_attr(m[1]);
        m[1]=m[1].replace(/^[\[\{\(]\S+[\]\}\)]/g,"");
        m[1]=m[1].replace(/^[<>=()]+/,"");
        s = s.replace(re,sp+tag(t,st,m[1]));
    }
    return s;
}

function make_image(m,re) {
    var ma = re.exec(m);
    if(ma != null) {
        var attr="";var st="";
        var at = /\((.*)\)$/.exec(ma[1]);
        if(at != null) {attr = qat('alt',at[1])+qat("title",at[1]);ma[1]=ma[1].replace(/\((.*)\)$/,"");}
        if(ma[1].match(/^[><]/)) {st = "float:"+((ma[1].indexOf(">")==0)?"right;":"left;");ma[1]=ma[1].replace(/^[><]/,"");}
        var pdl = /(\(+)/.exec(ma[1]);if(pdl){st+="padding-left:"+pdl[1].length+"em;";}
        var pdr = /(\)+)/.exec(ma[1]);if(pdr){st+="padding-right:"+pdr[1].length+"em;";}
        if(st){attr += qat('style',st);}
        var im = '<img src="'+ma[1]+'"'+attr+" />";
        if(ma.length >2) {im=tag('a',qat('href',ma[2]),im);}
        m = m.replace(re,im);
    }
    return m;
}

function make_attr(s) {
    var st="";var at="";
    if(!s){return "";}
    var l=/\[(\w\w)\]/.exec(s);
    if(l != null) {at += qat('lang',l[1]);}
    var ci=/\((\S+)\)/.exec(s);
    if(ci != null) {
        s = s.replace(/\((\S+)\)/,"");
        at += ci[1].replace(/#(.*)$/,' id="$1"').replace(/^(\S+)/,' class="$1"');
    }
    var ta= /(<>|=|<|>)/.exec(s);if(ta){st +="text-align:"+alg[ta[1]]+";";}
    var ss=/\{(\S+)\}/.exec(s);if(ss){st += ss[1];if(!ss[1].match(/;$/)){st+= ";";}}
    var pdl = /(\(+)/.exec(s);if(pdl){st+="padding-left:"+pdl[1].length+"em;";}
    var pdr = /(\)+)/.exec(s);if(pdr){st+="padding-right:"+pdr[1].length+"em;";}
    if(st) {at += qat('style',st);}
    return at;
}

function qat(a,v){return ' '+a+'="'+v+'"';}
function tag(t,a,c) {return "<"+t+a+">"+c+"</"+t+">";}
function stp(b){if(b){inbqq=0;}if(inpr){html+="<\/p>"+le;inpr=0;}if(inbq && !inbqq){html+="<\/blockquote>"+le;inbq=0;}}

/*
* Flext - A Mootools Based Flexible TextArea Class
* version 1.1 - for mootools 1.2
* by Graham McNicoll
*
* Copyright 2008-2009 - Education.com
* License:  MIT-style license.
*/
var Flext=new Class({Implements:Options,options:{aniTime:300,maxHeight:0,defaultMaxHeight:1000,parentDepth:6,growClass:"growme",enterStoppedClass:"stopenter",enterSubmitsClass:"entersubmits",replaceGhostTextClass:"replaceghosttext",growParentsClass:"growparents",ghostTextAttr:"ghosttext",ghostClassAttr:"ghostclass"},initialize:function(B,A){this.setOptions(A);this.el=document.id(B);this.autoGrow=B.hasClass(this.options.growClass);this.stopEnter=B.hasClass(this.options.enterStoppedClass);this.enterSubmits=B.hasClass(this.options.enterSubmitsClass);this.useGhostText=B.hasClass(this.options.replaceGhostTextClass);this.growParents=B.hasClass(this.options.growParentsClass);if(this.autoGrow){this.resizer=new Fx.Tween(this.el,{duration:this.options.aniTime});this.getMaxSize();this.reachedMax=false;this.startSize=this.origSize=this.el.getSize().y;this.vertPadding=this.el.getStyle("padding-top").toInt()+this.el.getStyle("padding-bottom").toInt()+this.el.getStyle("border-top").toInt()+this.el.getStyle("border-bottom").toInt();this.el.setStyle("overflow","hidden");this.el.addEvents({keyup:function(C){this.checkSize(C)}.bind(this),change:function(C){this.checkSize(C)}.bind(this),click:function(C){this.checkSize(C)}.bind(this)});this.checkSize()}if(this.stopEnter){this.el.addEvent("keydown",function(C){if(C.key=="enter"){C.stop();if(this.enterSubmits){this.submitForm()}}}.bind(this))}if(this.useGhostText){this.ghostText=this.el.get(this.options.ghostTextAttr);this.ghostClass=this.el.get(this.options.ghostClassAttr);if(this.ghostText){if(this.el.value!=this.ghostText){this.el.removeClass(this.ghostClass)}this.el.addEvents({focus:function(C){if(this.el.value==this.ghostText){this.el.set("value","");if(this.ghostClass){this.el.removeClass(this.ghostClass)}}}.bind(this),blur:function(C){if(this.el.value==""){this.el.set("value",this.ghostText);if(this.ghostClass){this.el.addClass(this.ghostClass)}}}.bind(this)})}}},getMaxSize:function(){this.maxSize=this.options.maxHeight;if(this.maxSize==0){var A=this.el.className.match(/maxheight-(\d*)/);if(A){this.maxSize=A[1]}else{this.maxSize=this.options.defaultMaxHeight}}},checkSize:function(D){var C=this.el.getSize();var B=this.el.getScrollSize();if(navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var A=(B.y)}else{var A=(B.y+this.vertPadding)}if(A>C.y){this.resizeIt(C,B)}},resizeIt:function(D,C){var A=C.y;if((C.y+this.vertPadding)>this.maxSize&&!this.reachedMax){A=this.maxSize;this.el.setStyle("overflow","");this.resizer.start("height",A);if(this.growParents){var B=A-this.startSize;this.resizeParents(this.el,0,B)}this.reachedMax=true}if(!this.reachedMax){var B=A-this.startSize;if(B<0){B=0}this.startSize=A;this.resizer.start("height",A);if(this.growParents){this.resizeParents(this.el,0,B)}}},resizeParents:function(D,C,B){if(C<this.options.parentDepth){var E=D.getParent();if(E){if(E.style.height&&E.style.height!=""){if(E.retrieve("flextAdjusted")){var A=(E.getStyle("height").toInt()+B)}else{E.store("flextAdjusted",true);var A=(E.getStyle("height").toInt()+B+this.vertPadding)}E.setStyle("height",A)}return this.resizeParents(E,(C+1),B)}return true}else{return true}},submitForm:function(){var B=this.el.getParent("form");if(B){var A=B.get("name");document[A].submit()}}});window.addEvent("domready",function(){$$("textarea.flext").each(function(B,A){new Flext(B)})});

var FormCheck=new Class({Implements:[Options,Events],options:{tipsClass:"fc-tbx",errorClass:"fc-error",fieldErrorClass:"fc-field-error",trimValue:false,validateDisabled:false,submitByAjax:false,ajaxResponseDiv:false,ajaxEvalScripts:false,onAjaxRequest:$empty,onAjaxSuccess:$empty,onAjaxFailure:$empty,display:{showErrors:0,titlesInsteadNames:0,errorsLocation:1,indicateErrors:1,indicateErrorsInit:0,keepFocusOnError:0,checkValueIfEmpty:1,addClassErrorToField:0,fixPngForIe:1,replaceTipsEffect:1,flashTips:0,closeTipsButton:1,tipsPosition:"right",tipsOffsetX:-45,tipsOffsetY:0,listErrorsAtTop:false,scrollToFirst:true,fadeDuration:300},alerts:{required:"This field is required.",alpha:"This field accepts alphabetic characters only.",alphanum:"This field accepts alphanumeric characters only.",nodigit:"No digits are accepted.",digit:"Please enter a valid integer.",digitltd:"The value must be between %0 and %1",number:"Please enter a valid number.",email:"Please enter a valid email.",phone:"Please enter a valid phone.",url:"Please enter a valid url.",confirm:"This field is different from %0",differs:"This value must be different of %0",length_str:"The length is incorrect, it must be between %0 and %1",length_fix:"The length is incorrect, it must be exactly %0 characters",lengthmax:"The length is incorrect, it must be at max %0",lengthmin:"The length is incorrect, it must be at least %0",checkbox:"Please check the box",radios:"Please select a radio",select:"Please choose a value"},regexp:{required:/[^.*]/,alpha:/^[a-z ._-]+$/i,alphanum:/^[a-z0-9 ._-]+$/i,digit:/^[-+]?[0-9]+$/,nodigit:/^[^0-9]+$/,number:/^[-+]?\d*\.?\d+$/,email:/^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i,phone:/^[\d\s ().-]+$/,url:/^(http|https|ftp)\:\/\/[a-z0-9\-\.]+\.[a-z]{2,3}(:[a-z0-9]*)?\/?([a-z0-9\-\._\?\,\'\/\\\+&amp;%\$#\=~])*$/i}},initialize:function(C,A){if(this.form=$(C)){this.form.isValid=true;this.regex=["length"];this.setOptions(A);if(typeof (formcheckLanguage)!="undefined"){this.options.alerts=$merge(this.options.alerts,formcheckLanguage)}this.validations=[];this.alreadyIndicated=false;this.firstError=false;var B=new Hash(this.options.regexp);B.each(function(E,D){this.regex.push(D)},this);this.form.getElements("*[class*=validate]").each(function(D){this.register(D)},this);this.form.addEvents({submit:this.onSubmit.bind(this)});if(this.options.display.fixPngForIe){this.fixIeStuffs()}document.addEvent("mousewheel",function(){this.isScrolling=false}.bind(this))}},register:function(el){el.validation=[];el.getProperty("class").split(" ").each(function(classX){if(classX.match(/^validate(\[.+\])$/)){var validators=eval(classX.match(/^validate(\[.+\])$/)[1]);for(var i=0;i<validators.length;i++){el.validation.push(validators[i]);if(validators[i].match(/^confirm\[/)){var field=eval(validators[i].match(/^.+(\[.+\])$/)[1].replace(/([A-Z0-9\._-]+)/i,"'$1'"));if(this.form[field].validation.contains("required")){el.validation.push("required")}}}this.addListener(el)}},this)},dispose:function(A){this.validations.erase(A)},addListener:function(B){this.validations.push(B);B.errors=[];if(this.options.display.indicateErrorsInit){this.validations.each(function(C){if(!this.manageError(C,"submit")){this.form.isValid=false}},this);return true}if(B.validation[0]=="submit"){B.addEvent("click",function(C){this.onSubmit(C)}.bind(this));return true}if(this.isChildType(B)==false){B.addEvent("blur",function(){(function(){if(!this.fxRunning&&(B.element||this.options.display.showErrors==1)&&(this.options.display.checkValueIfEmpty||B.value)){this.manageError(B,"blur")}}.bind(this)).delay(100)}.bind(this))}else{if(this.isChildType(B)==true){var A=this.form.getElements('input[name="'+B.getProperty("name")+'"]');A.each(function(C){C.addEvent("blur",function(){(function(){if((B.element||this.options.display.showErrors==1)&&(this.options.display.checkValueIfEmpty||B.value)){this.manageError(B,"click")}}.bind(this)).delay(100)}.bind(this))},this)}}},validate:function(el){el.errors=[];el.isOk=true;if(!this.options.validateDisabled&&el.get("disabled")){return true}if(this.options.trimValue&&el.value){el.value=el.value.trim()}el.validation.each(function(rule){if(this.isChildType(el)){if(this.validateGroup(el)==false){el.isOk=false}}else{var ruleArgs=[];if(rule.match(/^.+\[/)){var ruleMethod=rule.split("[")[0];ruleArgs=eval(rule.match(/^.+(\[.+\])$/)[1].replace(/([A-Z0-9\._-]+)/i,"'$1'"))}else{var ruleMethod=rule}if(this.regex.contains(ruleMethod)&&el.get("tag")!="select"){if(this.validateRegex(el,ruleMethod,ruleArgs)==false){el.isOk=false}}if(ruleMethod=="confirm"){if(this.validateConfirm(el,ruleArgs)==false){el.isOk=false}}if(ruleMethod=="differs"){if(this.validateDiffers(el,ruleArgs)==false){el.isOk=false}}if(el.get("tag")=="select"||(el.type=="checkbox"&&ruleMethod=="required")){if(this.simpleValidate(el)==false){el.isOk=false}}if(rule.match(/%[A-Z0-9\._-]+$/i)||(el.isOk&&rule.match(/~[A-Z0-9\._-]+$/i))){if(eval(rule.slice(1)+"(el)")==false){el.isOk=false}}}},this);if(el.isOk){return true}else{return false}},simpleValidate:function(A){if(A.get("tag")=="select"&&A.selectedIndex<=0){A.errors.push(this.options.alerts.select);return false}else{if(A.type=="checkbox"&&A.checked==false){A.errors.push(this.options.alerts.checkbox);return false}}return true},validateRegex:function(C,B,D){var E="";if(D[1]&&B=="length"){if(D[1]==-1){this.options.regexp.length=new RegExp("^[\\s\\S]{"+D[0]+",}$");E=this.options.alerts.lengthmin.replace("%0",D[0])}else{if(D[0]==D[1]){this.options.regexp.length=new RegExp("^[\\s\\S]{"+D[0]+"}$");E=this.options.alerts.length_fix.replace("%0",D[0])}else{this.options.regexp.length=new RegExp("^[\\s\\S]{"+D[0]+","+D[1]+"}$");E=this.options.alerts.length_str.replace("%0",D[0]).replace("%1",D[1])}}}else{if(D[0]&&B=="length"){this.options.regexp.length=new RegExp("^.{0,"+D[0]+"}$");E=this.options.alerts.lengthmax.replace("%0",D[0])}else{E=this.options.alerts[B]}}if(D[1]&&B=="digit"){var A=true;if(!this.options.regexp.digit.test(C.value)){C.errors.push(this.options.alerts[B]);A=false}if(D[1]==-1){if(C.value>=D[0]){var F=true}else{var F=false}E=this.options.alerts.digitmin.replace("%0",D[0])}else{if(C.value>=D[0]&&C.value<=D[1]){var F=true}else{var F=false}E=this.options.alerts.digitltd.replace("%0",D[0]).replace("%1",D[1])}if(A==false||F==false){C.errors.push(E);return false}}else{if(this.options.regexp[B].test(C.value)==false){C.errors.push(E);return false}}return true},validateConfirm:function(B,C){var A=C[0];if(B.value!=this.form[A].value){if(this.options.display.titlesInsteadNames){var D=this.options.alerts.confirm.replace("%0",this.form[A].getProperty("title"))}else{var D=this.options.alerts.confirm.replace("%0",A)}B.errors.push(D);return false}return true},validateDiffers:function(A,C){var B=C[0];if(A.value==this.form[B].value){if(this.options.display.titlesInsteadNames){var D=this.options.alerts.differs.replace("%0",this.form[B].getProperty("title"))}else{var D=this.options.alerts.differs.replace("%0",B)}A.errors.push(D);return false}return true},isChildType:function(A){return($defined(A.type)&&A.type=="radio")?true:false},validateGroup:function(D){D.errors=[];var A=this.form[D.getProperty("name")];D.group=A;var C=false;for(var B=0;B<A.length;B++){if(A[B].checked){C=true}}if(C==false){D.errors.push(this.options.alerts.radios);return false}else{return true}},listErrorsAtTop:function(A){if(!this.form.element){this.form.element=new Element("div",{id:"errorlist","class":this.options.errorClass}).injectTop(this.form)}if($type(A)=="collection"){new Element("p").set("html","<span>"+A[0].name+" : </span>"+A[0].errors[0]).injectInside(this.form.element)}else{if((A.validation.contains("required")&&A.errors.length>0)||(A.errors.length>0&&A.value&&A.validation.contains("required")==false)){A.errors.each(function(B){new Element("p").set("html","<span>"+A.name+" : </span>"+B).injectInside(this.form.element)},this)}}},manageError:function(A,C){var B=this.validate(A);if((!B&&A.validation.flatten()[0].contains("confirm["))||(!B&&A.validation.contains("required"))||(!A.validation.contains("required")&&A.value&&!B)){if(this.options.display.listErrorsAtTop==true&&C=="submit"){this.listErrorsAtTop(A,C)}if(this.options.display.indicateErrors==2||this.alreadyIndicated==false||A.name==this.alreadyIndicated.name){if(!this.firstError){this.firstError=A}this.alreadyIndicated=A;if(this.options.display.keepFocusOnError&&A.name==this.firstError.name){(function(){A.focus()}).delay(20)}this.addError(A);return false}}else{if((B||(!A.validation.contains("required")&&!A.value))&&A.element){this.removeError(A);return true}}return true},addError:function(C){if(!C.element&&this.options.display.indicateErrors!=0){if(this.options.display.errorsLocation==1){var E=(this.options.display.tipsPosition=="left")?C.getCoordinates().left:C.getCoordinates().right;var B={opacity:0,position:"absolute","float":"left",left:E+this.options.display.tipsOffsetX};C.element=new Element("div",{"class":this.options.tipsClass,styles:B}).injectInside(document.body);this.addPositionEvent(C)}else{if(this.options.display.errorsLocation==2){C.element=new Element("div",{"class":this.options.errorClass,styles:{opacity:0}}).injectBefore(C)}else{if(this.options.display.errorsLocation==3){C.element=new Element("div",{"class":this.options.errorClass,styles:{opacity:0}});if($type(C.group)=="object"||$type(C.group)=="collection"){C.element.injectAfter(C.group[C.group.length-1])}else{C.element.injectAfter(C)}}}}}if(C.element&&C.element!=true){C.element.empty();if(this.options.display.errorsLocation==1){var D=[];C.errors.each(function(F){D.push(new Element("p").set("html",F))});var A=this.makeTips(D).injectInside(C.element);if(this.options.display.closeTipsButton){A.getElements("a.close").addEvent("mouseup",function(){this.removeError(C)}.bind(this))}C.element.setStyle("top",C.getCoordinates().top-A.getCoordinates().height+this.options.display.tipsOffsetY)}else{C.errors.each(function(F){new Element("p").set("html",F).injectInside(C.element)})}if(!this.options.display.fadeDuration||Browser.Engine.trident&&Browser.Engine.version==5&&this.options.display.errorsLocation<2){C.element.setStyle("opacity",1)}else{C.fx=new Fx.Tween(C.element,{duration:this.options.display.fadeDuration,ignore:true,onStart:function(){this.fxRunning=true}.bind(this),onComplete:function(){this.fxRunning=false;if(C.element&&C.element.getStyle("opacity").toInt()==0){C.element.destroy();C.element=false}}.bind(this)});if(C.element.getStyle("opacity").toInt()!=1){C.fx.start("opacity",1)}}}if(this.options.display.addClassErrorToField&&this.isChildType(C)==false){C.addClass(this.options.fieldErrorClass);C.element=C.element||true}},addPositionEvent:function(A){if(this.options.display.replaceTipsEffect){A.event=function(){new Fx.Morph(A.element,{duration:this.options.display.fadeDuration}).start({left:[A.element.getStyle("left"),A.getCoordinates().right+this.options.display.tipsOffsetX],top:[A.element.getStyle("top"),A.getCoordinates().top-A.element.getCoordinates().height+this.options.display.tipsOffsetY]})}.bind(this)}else{A.event=function(){A.element.setStyles({left:A.getCoordinates().right+this.options.display.tipsOffsetX,top:A.getCoordinates().top-A.element.getCoordinates().height+this.options.display.tipsOffsetY})}.bind(this)}window.addEvent("resize",A.event)},removeError:function(A){this.alreadyIndicated=false;A.errors=[];A.isOK=true;window.removeEvent("resize",A.event);if(this.options.display.errorsLocation>=2&&A.element){new Fx.Tween(A.element,{duration:this.options.display.fadeDuration}).start("height",0)}if(!this.options.display.fadeDuration||Browser.Engine.trident&&Browser.Engine.version==5&&this.options.display.errorsLocation==1&&A.element){this.fxRunning=true;A.element.destroy();A.element=false;(function(){this.fxRunning=false}.bind(this)).delay(200)}else{if(A.element&&A.element!=true){A.fx.start("opacity",0)}}if(this.options.display.addClassErrorToField&&!this.isChildType(A)){A.removeClass(this.options.fieldErrorClass)}},focusOnError:function(B){if(this.options.display.scrollToFirst&&!this.alreadyFocused&&!this.isScrolling){if(!this.options.display.indicateErrors||!this.options.display.errorsLocation){var A=B.getCoordinates().top-30}else{if(this.alreadyIndicated.element){switch(this.options.display.errorsLocation){case 1:var A=B.element.getCoordinates().top;break;case 2:var A=B.element.getCoordinates().top-30;break;case 3:var A=B.getCoordinates().top-30;break}this.isScrolling=true}}if(window.getScroll.y!=A){new Fx.Scroll(window,{onComplete:function(){this.isScrolling=false;B.focus()}.bind(this)}).start(0,A)}else{this.isScrolling=false;B.focus()}this.alreadyFocused=true}},fixIeStuffs:function(){if(Browser.Engine.trident4){var F=new RegExp("url\\(([.a-zA-Z0-9_/:-]+.png)\\)");var H=new RegExp("(.+)formcheck.css");for(var C=0;C<document.styleSheets.length;C++){if(document.styleSheets[C].href.match(/formcheck\.css$/)){var E=document.styleSheets[C].href.replace(H,"$1");var D=document.styleSheets[C].rules.length;for(var B=0;B<D;B++){var I=document.styleSheets[C].rules[B].style;var G=E+I.backgroundImage.replace(F,"$1");if(G&&G.match(/\.png/i)){var A=(I.backgroundRepeat=="no-repeat")?"crop":"scale";I.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, src='"+G+"', sizingMethod='"+A+"')";I.backgroundImage="none"}}}}}},makeTips:function(C){var E=new Element("table");E.cellPadding="0";E.cellSpacing="0";E.border="0";var D=new Element("tbody").injectInside(E);var B=new Element("tr").injectInside(D);new Element("td",{"class":"tl"}).injectInside(B);new Element("td",{"class":"t"}).injectInside(B);new Element("td",{"class":"tr"}).injectInside(B);var H=new Element("tr").injectInside(D);new Element("td",{"class":"l"}).injectInside(H);var A=new Element("td",{"class":"c"}).injectInside(H);var G=new Element("div",{"class":"err"}).injectInside(A);C.each(function(I){I.injectInside(G)});if(this.options.display.closeTipsButton){new Element("a",{"class":"close"}).injectInside(A)}new Element("td",{"class":"r"}).injectInside(H);var F=new Element("tr").injectInside(D);new Element("td",{"class":"bl"}).injectInside(F);new Element("td",{"class":"b"}).injectInside(F);new Element("td",{"class":"br"}).injectInside(F);return E},reinitialize:function(){this.validations.each(function(A){if(A.element){A.errors=[];A.isOK=true;if(this.options.display.flashTips==1){A.element.destroy();A.element=false}}},this);if(this.form.element){this.form.element.empty()}this.alreadyFocused=false;this.firstError=false;this.elementToRemove=this.alreadyIndicated;this.alreadyIndicated=false;this.form.isValid=true},submitByAjax:function(){var A=this.form.getProperty("action");this.fireEvent("ajaxRequest");new Request({url:A,method:this.form.getProperty("method"),data:this.form.toQueryString(),evalScripts:this.options.ajaxEvalScripts,onFailure:function(B){this.fireEvent("ajaxFailure",B)}.bind(this),onSuccess:function(B){this.fireEvent("ajaxSuccess",B);if(this.options.ajaxResponseDiv){$(this.options.ajaxResponseDiv).set("html",B)}}.bind(this)}).send()},onSubmit:function(A){this.reinitialize();this.validations.each(function(C){var B=this.manageError(C,"submit");if(!B){this.form.isValid=false}},this);if(this.form.isValid){if(this.options.submitByAjax){new Event(A).stop();this.submitByAjax()}}else{new Event(A).stop();if(this.elementToRemove&&this.elementToRemove!=this.firstError&&this.options.display.indicateErrors==1){this.removeError(this.elementToRemove)}this.focusOnError(this.firstError)}}});

/*
* FancyForm 0.95
* By Vacuous Virtuoso, lipidity.com
* ---
* Checkbox and radio input replacement script.
* Toggles defined class when input is selected.
*/

var FancyForm = {
    start: function(elements, options){
        if(FancyForm.initing != undefined) return;
        if($type(elements)!='array') elements = $$('input');
        if(!options) options = [];
        FancyForm.onclasses = ($type(options['onClasses']) == 'object') ? options['onClasses'] : {
            checkbox: 'checked',
            radio: 'selected'
        }
        FancyForm.offclasses = ($type(options['offClasses']) == 'object') ? options['offClasses'] : {
            checkbox: 'unchecked',
            radio: 'unselected'
        }
        if($type(options['extraClasses']) == 'object'){
            FancyForm.extra = options['extraClasses'];
        } else if(options['extraClasses']){
            FancyForm.extra = {
                checkbox: 'f_checkbox',
                radio: 'f_radio',
                on: 'f_on',
                off: 'f_off',
                all: 'fancy'
            }
        } else {
            FancyForm.extra = {};}
        FancyForm.onSelect = $pick(options['onSelect'], function(el){});
        FancyForm.onDeselect = $pick(options['onDeselect'], function(el){});
        FancyForm.chks = [];
        FancyForm.add(elements);
        $each($$('form'), function(x) {
            x.addEvent('reset', function(a) {window.setTimeout(function(){FancyForm.chks.each(function(x){FancyForm.update(x);x.inputElement.blur()})}, 200);
            });
        });
    },
    add: function(elements){
        if($type(elements) == 'element')
            elements = [elements];
        FancyForm.initing = 1;
        var keeps = [];
        var newChks = elements.filter(function(chk){
            if($type(chk) != 'element' || chk.inputElement || (chk.get('tag') == 'input' && chk.getParent().inputElement))
                return false;
            if(chk.get('tag') == 'input' && (FancyForm.onclasses[chk.getProperty('type')])){
                var el = chk.getParent();
                if(el.getElement('input')==chk){
                    el.type = chk.getProperty('type');
                    el.inputElement = chk;
                    this.push(el);
                } else {
                    chk.addEvent('click',function(f){
                        if(f.event.stopPropagation) f.event.stopPropagation();
                    });
                }
            } else if((chk.inputElement = chk.getElement('input')) && (FancyForm.onclasses[(chk.type = chk.inputElement.getProperty('type'))])){
                return true;
            }
            return false;
        }.bind(keeps));
        newChks = newChks.combine(keeps);
        newChks.each(function(chk){
            var c = chk.inputElement;
            c.setStyle('position', 'absolute');
            c.setStyle('left', '-9999px');
            chk.addEvent('selectStart', function(f){f.stop()});
            chk.name = c.getProperty('name');
            FancyForm.update(chk);
        });
        newChks.each(function(chk){
            var c = chk.inputElement;
            chk.addEvent('click', function(f){
                f.stop(); f.type = 'prop';
                c.fireEvent('click', f, 1);
            });
            chk.addEvent('mousedown', function(f){
                if($type(c.onmousedown) == 'function')
                    c.onmousedown();
                f.preventDefault();
            });
            chk.addEvent('mouseup', function(f){
                if($type(c.onmouseup) == 'function')
                    c.onmouseup();
            });
            c.addEvent('focus', function(f){
                if(FancyForm.focus)
                    chk.setStyle('outline', '1px dotted');
            });
            c.addEvent('blur', function(f){
                chk.setStyle('outline', 0);
            });
            c.addEvent('click', function(f){
                if(f.event.stopPropagation) f.event.stopPropagation();
                if(c.getProperty('disabled')) // c.getStyle('position') != 'absolute'
                    return;
                if (!chk.hasClass(FancyForm.onclasses[chk.type]))
                    c.setProperty('checked', 'checked');
                else if(chk.type != 'radio')
                    c.setProperty('checked', false);
                if(f.type == 'prop')
                    FancyForm.focus = 0;
                FancyForm.update(chk);
                FancyForm.focus = 1;
                if(f.type == 'prop' && !FancyForm.initing && $type(c.onclick) == 'function')
                     c.onclick();
            });
            c.addEvent('mouseup', function(f){
                if(f.event.stopPropagation) f.event.stopPropagation();
            });
            c.addEvent('mousedown', function(f){
                if(f.event.stopPropagation) f.event.stopPropagation();
            });
            if(extraclass = FancyForm.extra[chk.type])
                chk.addClass(extraclass);
            if(extraclass = FancyForm.extra['all'])
                chk.addClass(extraclass);
        });
        FancyForm.chks.combine(newChks);
        FancyForm.initing = 0;
    },
    update: function(chk){
        if(chk.inputElement.getProperty('checked')) {
            chk.removeClass(FancyForm.offclasses[chk.type]);
            chk.addClass(FancyForm.onclasses[chk.type]);
            if (chk.type == 'radio'){
                FancyForm.chks.each(function(other){
                    if (other.name == chk.name && other != chk) {
                        other.inputElement.setProperty('checked', false);
                        FancyForm.update(other);
                    }
                });
            }
            if(extraclass = FancyForm.extra['on'])
                chk.addClass(extraclass);
            if(extraclass = FancyForm.extra['off'])
                chk.removeClass(extraclass);
            if(!FancyForm.initing)
                FancyForm.onSelect(chk);
        } else {
            chk.removeClass(FancyForm.onclasses[chk.type]);
            chk.addClass(FancyForm.offclasses[chk.type]);
            if(extraclass = FancyForm.extra['off'])
                chk.addClass(extraclass);
            if(extraclass = FancyForm.extra['on'])
                chk.removeClass(extraclass);
            if(!FancyForm.initing)
                FancyForm.onDeselect(chk);
        }
        if(!FancyForm.initing)
            chk.inputElement.focus();
    },
    all: function(){
        FancyForm.chks.each(function(chk){
            chk.inputElement.setProperty('checked', 'checked');
            FancyForm.update(chk);
        });
    },
    none: function(){
        FancyForm.chks.each(function(chk){
            chk.inputElement.setProperty('checked', false);
            FancyForm.update(chk);
        });
    }
};

/**
 * Version: 1.0 Alpha-1
 * Build Date: 13-Nov-2007
 * Copyright (c) 2006-2007, Coolite Inc. (http://www.coolite.com/). All rights reserved.
 * License: Licensed under The MIT License. See license.txt and http://www.datejs.com/license/.
 * Website: http://www.datejs.com/ or http://www.coolite.com/datejs/
 */
Date.CultureInfo={name:"en-US",englishName:"English (United States)",nativeName:"English (United States)",dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],abbreviatedDayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],shortestDayNames:["Su","Mo","Tu","We","Th","Fr","Sa"],firstLetterDayNames:["S","M","T","W","T","F","S"],monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],abbreviatedMonthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],amDesignator:"AM",pmDesignator:"PM",firstDayOfWeek:0,twoDigitYearMax:2029,dateElementOrder:"mdy",formatPatterns:{shortDate:"M/d/yyyy",longDate:"dddd, MMMM dd, yyyy",shortTime:"h:mm tt",longTime:"h:mm:ss tt",fullDateTime:"dddd, MMMM dd, yyyy h:mm:ss tt",sortableDateTime:"yyyy-MM-ddTHH:mm:ss",universalSortableDateTime:"yyyy-MM-dd HH:mm:ssZ",rfc1123:"ddd, dd MMM yyyy HH:mm:ss GMT",monthDay:"MMMM dd",yearMonth:"MMMM, yyyy"},regexPatterns:{jan:/^jan(uary)?/i,feb:/^feb(ruary)?/i,mar:/^mar(ch)?/i,apr:/^apr(il)?/i,may:/^may/i,jun:/^jun(e)?/i,jul:/^jul(y)?/i,aug:/^aug(ust)?/i,sep:/^sep(t(ember)?)?/i,oct:/^oct(ober)?/i,nov:/^nov(ember)?/i,dec:/^dec(ember)?/i,sun:/^su(n(day)?)?/i,mon:/^mo(n(day)?)?/i,tue:/^tu(e(s(day)?)?)?/i,wed:/^we(d(nesday)?)?/i,thu:/^th(u(r(s(day)?)?)?)?/i,fri:/^fr(i(day)?)?/i,sat:/^sa(t(urday)?)?/i,future:/^next/i,past:/^last|past|prev(ious)?/i,add:/^(\+|after|from)/i,subtract:/^(\-|before|ago)/i,yesterday:/^yesterday/i,today:/^t(oday)?/i,tomorrow:/^tomorrow/i,now:/^n(ow)?/i,millisecond:/^ms|milli(second)?s?/i,second:/^sec(ond)?s?/i,minute:/^min(ute)?s?/i,hour:/^h(ou)?rs?/i,week:/^w(ee)?k/i,month:/^m(o(nth)?s?)?/i,day:/^d(ays?)?/i,year:/^y((ea)?rs?)?/i,shortMeridian:/^(a|p)/i,longMeridian:/^(a\.?m?\.?|p\.?m?\.?)/i,timezone:/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\s*(\+|\-)\s*\d\d\d\d?)|gmt)/i,ordinalSuffix:/^\s*(st|nd|rd|th)/i,timeContext:/^\s*(\:|a|p)/i},abbreviatedTimeZoneStandard:{GMT:"-000",EST:"-0400",CST:"-0500",MST:"-0600",PST:"-0700"},abbreviatedTimeZoneDST:{GMT:"-000",EDT:"-0500",CDT:"-0600",MDT:"-0700",PDT:"-0800"}};
Date.getMonthNumberFromName=function(name){var n=Date.CultureInfo.monthNames,m=Date.CultureInfo.abbreviatedMonthNames,s=name.toLowerCase();for(var i=0;i<n.length;i++){if(n[i].toLowerCase()==s||m[i].toLowerCase()==s){return i;}}
return-1;};Date.getDayNumberFromName=function(name){var n=Date.CultureInfo.dayNames,m=Date.CultureInfo.abbreviatedDayNames,o=Date.CultureInfo.shortestDayNames,s=name.toLowerCase();for(var i=0;i<n.length;i++){if(n[i].toLowerCase()==s||m[i].toLowerCase()==s){return i;}}
return-1;};Date.isLeapYear=function(year){return(((year%4===0)&&(year%100!==0))||(year%400===0));};Date.getDaysInMonth=function(year,month){return[31,(Date.isLeapYear(year)?29:28),31,30,31,30,31,31,30,31,30,31][month];};Date.getTimezoneOffset=function(s,dst){return(dst||false)?Date.CultureInfo.abbreviatedTimeZoneDST[s.toUpperCase()]:Date.CultureInfo.abbreviatedTimeZoneStandard[s.toUpperCase()];};Date.getTimezoneAbbreviation=function(offset,dst){var n=(dst||false)?Date.CultureInfo.abbreviatedTimeZoneDST:Date.CultureInfo.abbreviatedTimeZoneStandard,p;for(p in n){if(n[p]===offset){return p;}}
return null;};Date.prototype.clone=function(){return new Date(this.getTime());};Date.prototype.compareTo=function(date){if(isNaN(this)){throw new Error(this);}
if(date instanceof Date&&!isNaN(date)){return(this>date)?1:(this<date)?-1:0;}else{throw new TypeError(date);}};Date.prototype.equals=function(date){return(this.compareTo(date)===0);};Date.prototype.between=function(start,end){var t=this.getTime();return t>=start.getTime()&&t<=end.getTime();};Date.prototype.addMilliseconds=function(value){this.setMilliseconds(this.getMilliseconds()+value);return this;};Date.prototype.addSeconds=function(value){return this.addMilliseconds(value*1000);};Date.prototype.addMinutes=function(value){return this.addMilliseconds(value*60000);};Date.prototype.addHours=function(value){return this.addMilliseconds(value*3600000);};Date.prototype.addDays=function(value){return this.addMilliseconds(value*86400000);};Date.prototype.addWeeks=function(value){return this.addMilliseconds(value*604800000);};Date.prototype.addMonths=function(value){var n=this.getDate();this.setDate(1);this.setMonth(this.getMonth()+value);this.setDate(Math.min(n,this.getDaysInMonth()));return this;};Date.prototype.addYears=function(value){return this.addMonths(value*12);};Date.prototype.add=function(config){if(typeof config=="number"){this._orient=config;return this;}
var x=config;if(x.millisecond||x.milliseconds){this.addMilliseconds(x.millisecond||x.milliseconds);}
if(x.second||x.seconds){this.addSeconds(x.second||x.seconds);}
if(x.minute||x.minutes){this.addMinutes(x.minute||x.minutes);}
if(x.hour||x.hours){this.addHours(x.hour||x.hours);}
if(x.month||x.months){this.addMonths(x.month||x.months);}
if(x.year||x.years){this.addYears(x.year||x.years);}
if(x.day||x.days){this.addDays(x.day||x.days);}
return this;};Date._validate=function(value,min,max,name){if(typeof value!="number"){throw new TypeError(value+" is not a Number.");}else if(value<min||value>max){throw new RangeError(value+" is not a valid value for "+name+".");}
return true;};Date.validateMillisecond=function(n){return Date._validate(n,0,999,"milliseconds");};Date.validateSecond=function(n){return Date._validate(n,0,59,"seconds");};Date.validateMinute=function(n){return Date._validate(n,0,59,"minutes");};Date.validateHour=function(n){return Date._validate(n,0,23,"hours");};Date.validateDay=function(n,year,month){return Date._validate(n,1,Date.getDaysInMonth(year,month),"days");};Date.validateMonth=function(n){return Date._validate(n,0,11,"months");};Date.validateYear=function(n){return Date._validate(n,1,9999,"seconds");};Date.prototype.set=function(config){var x=config;if(!x.millisecond&&x.millisecond!==0){x.millisecond=-1;}
if(!x.second&&x.second!==0){x.second=-1;}
if(!x.minute&&x.minute!==0){x.minute=-1;}
if(!x.hour&&x.hour!==0){x.hour=-1;}
if(!x.day&&x.day!==0){x.day=-1;}
if(!x.month&&x.month!==0){x.month=-1;}
if(!x.year&&x.year!==0){x.year=-1;}
if(x.millisecond!=-1&&Date.validateMillisecond(x.millisecond)){this.addMilliseconds(x.millisecond-this.getMilliseconds());}
if(x.second!=-1&&Date.validateSecond(x.second)){this.addSeconds(x.second-this.getSeconds());}
if(x.minute!=-1&&Date.validateMinute(x.minute)){this.addMinutes(x.minute-this.getMinutes());}
if(x.hour!=-1&&Date.validateHour(x.hour)){this.addHours(x.hour-this.getHours());}
if(x.month!==-1&&Date.validateMonth(x.month)){this.addMonths(x.month-this.getMonth());}
if(x.year!=-1&&Date.validateYear(x.year)){this.addYears(x.year-this.getFullYear());}
if(x.day!=-1&&Date.validateDay(x.day,this.getFullYear(),this.getMonth())){this.addDays(x.day-this.getDate());}
if(x.timezone){this.setTimezone(x.timezone);}
if(x.timezoneOffset){this.setTimezoneOffset(x.timezoneOffset);}
return this;};Date.prototype.clearTime=function(){this.setHours(0);this.setMinutes(0);this.setSeconds(0);this.setMilliseconds(0);return this;};Date.prototype.isLeapYear=function(){var y=this.getFullYear();return(((y%4===0)&&(y%100!==0))||(y%400===0));};Date.prototype.isWeekday=function(){return!(this.is().sat()||this.is().sun());};Date.prototype.getDaysInMonth=function(){return Date.getDaysInMonth(this.getFullYear(),this.getMonth());};Date.prototype.moveToFirstDayOfMonth=function(){return this.set({day:1});};Date.prototype.moveToLastDayOfMonth=function(){return this.set({day:this.getDaysInMonth()});};Date.prototype.moveToDayOfWeek=function(day,orient){var diff=(day-this.getDay()+7*(orient||+1))%7;return this.addDays((diff===0)?diff+=7*(orient||+1):diff);};Date.prototype.moveToMonth=function(month,orient){var diff=(month-this.getMonth()+12*(orient||+1))%12;return this.addMonths((diff===0)?diff+=12*(orient||+1):diff);};Date.prototype.getDayOfYear=function(){return Math.floor((this-new Date(this.getFullYear(),0,1))/86400000);};Date.prototype.getWeekOfYear=function(firstDayOfWeek){var y=this.getFullYear(),m=this.getMonth(),d=this.getDate();var dow=firstDayOfWeek||Date.CultureInfo.firstDayOfWeek;var offset=7+1-new Date(y,0,1).getDay();if(offset==8){offset=1;}
var daynum=((Date.UTC(y,m,d,0,0,0)-Date.UTC(y,0,1,0,0,0))/86400000)+1;var w=Math.floor((daynum-offset+7)/7);if(w===dow){y--;var prevOffset=7+1-new Date(y,0,1).getDay();if(prevOffset==2||prevOffset==8){w=53;}else{w=52;}}
return w;};Date.prototype.isDST=function(){console.log('isDST');return this.toString().match(/(E|C|M|P)(S|D)T/)[2]=="D";};Date.prototype.getTimezone=function(){return Date.getTimezoneAbbreviation(this.getUTCOffset,this.isDST());};Date.prototype.setTimezoneOffset=function(s){var here=this.getTimezoneOffset(),there=Number(s)*-6/10;this.addMinutes(there-here);return this;};Date.prototype.setTimezone=function(s){return this.setTimezoneOffset(Date.getTimezoneOffset(s));};Date.prototype.getUTCOffset=function(){var n=this.getTimezoneOffset()*-10/6,r;if(n<0){r=(n-10000).toString();return r[0]+r.substr(2);}else{r=(n+10000).toString();return"+"+r.substr(1);}};Date.prototype.getDayName=function(abbrev){return abbrev?Date.CultureInfo.abbreviatedDayNames[this.getDay()]:Date.CultureInfo.dayNames[this.getDay()];};Date.prototype.getMonthName=function(abbrev){return abbrev?Date.CultureInfo.abbreviatedMonthNames[this.getMonth()]:Date.CultureInfo.monthNames[this.getMonth()];};Date.prototype._toString=Date.prototype.toString;Date.prototype.toString=function(format){var self=this;var p=function p(s){return(s.toString().length==1)?"0"+s:s;};return format?format.replace(/dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|zz?z?/g,function(format){switch(format){case"hh":return p(self.getHours()<13?self.getHours():(self.getHours()-12));case"h":return self.getHours()<13?self.getHours():(self.getHours()-12);case"HH":return p(self.getHours());case"H":return self.getHours();case"mm":return p(self.getMinutes());case"m":return self.getMinutes();case"ss":return p(self.getSeconds());case"s":return self.getSeconds();case"yyyy":return self.getFullYear();case"yy":return self.getFullYear().toString().substring(2,4);case"dddd":return self.getDayName();case"ddd":return self.getDayName(true);case"dd":return p(self.getDate());case"d":return self.getDate().toString();case"MMMM":return self.getMonthName();case"MMM":return self.getMonthName(true);case"MM":return p((self.getMonth()+1));case"M":return self.getMonth()+1;case"t":return self.getHours()<12?Date.CultureInfo.amDesignator.substring(0,1):Date.CultureInfo.pmDesignator.substring(0,1);case"tt":return self.getHours()<12?Date.CultureInfo.amDesignator:Date.CultureInfo.pmDesignator;case"zzz":case"zz":case"z":return"";}}):this._toString();};
Date.now=function(){return new Date();};Date.today=function(){return Date.now().clearTime();};Date.prototype._orient=+1;Date.prototype.next=function(){this._orient=+1;return this;};Date.prototype.last=Date.prototype.prev=Date.prototype.previous=function(){this._orient=-1;return this;};Date.prototype._is=false;Date.prototype.is=function(){this._is=true;return this;};Number.prototype._dateElement="day";Number.prototype.fromNow=function(){var c={};c[this._dateElement]=this;return Date.now().add(c);};Number.prototype.ago=function(){var c={};c[this._dateElement]=this*-1;return Date.now().add(c);};(function(){var $D=Date.prototype,$N=Number.prototype;var dx=("sunday monday tuesday wednesday thursday friday saturday").split(/\s/),mx=("january february march april may june july august september october november december").split(/\s/),px=("Millisecond Second Minute Hour Day Week Month Year").split(/\s/),de;var df=function(n){return function(){if(this._is){this._is=false;return this.getDay()==n;}
return this.moveToDayOfWeek(n,this._orient);};};for(var i=0;i<dx.length;i++){$D[dx[i]]=$D[dx[i].substring(0,3)]=df(i);}
var mf=function(n){return function(){if(this._is){this._is=false;return this.getMonth()===n;}
return this.moveToMonth(n,this._orient);};};for(var j=0;j<mx.length;j++){$D[mx[j]]=$D[mx[j].substring(0,3)]=mf(j);}
var ef=function(j){return function(){if(j.substring(j.length-1)!="s"){j+="s";}
return this["add"+j](this._orient);};};var nf=function(n){return function(){this._dateElement=n;return this;};};for(var k=0;k<px.length;k++){de=px[k].toLowerCase();$D[de]=$D[de+"s"]=ef(px[k]);$N[de]=$N[de+"s"]=nf(de);}}());Date.prototype.toJSONString=function(){return this.toString("yyyy-MM-ddThh:mm:ssZ");};Date.prototype.toShortDateString=function(){return this.toString(Date.CultureInfo.formatPatterns.shortDatePattern);};Date.prototype.toLongDateString=function(){return this.toString(Date.CultureInfo.formatPatterns.longDatePattern);};Date.prototype.toShortTimeString=function(){return this.toString(Date.CultureInfo.formatPatterns.shortTimePattern);};Date.prototype.toLongTimeString=function(){return this.toString(Date.CultureInfo.formatPatterns.longTimePattern);};Date.prototype.getOrdinal=function(){switch(this.getDate()){case 1:case 21:case 31:return"st";case 2:case 22:return"nd";case 3:case 23:return"rd";default:return"th";}};
(function(){Date.Parsing={Exception:function(s){this.message="Parse error at '"+s.substring(0,10)+" ...'";}};var $P=Date.Parsing;var _=$P.Operators={rtoken:function(r){return function(s){var mx=s.match(r);if(mx){return([mx[0],s.substring(mx[0].length)]);}else{throw new $P.Exception(s);}};},token:function(s){return function(s){return _.rtoken(new RegExp("^\s*"+s+"\s*"))(s);};},stoken:function(s){return _.rtoken(new RegExp("^"+s));},until:function(p){return function(s){var qx=[],rx=null;while(s.length){try{rx=p.call(this,s);}catch(e){qx.push(rx[0]);s=rx[1];continue;}
break;}
return[qx,s];};},many:function(p){return function(s){var rx=[],r=null;while(s.length){try{r=p.call(this,s);}catch(e){return[rx,s];}
rx.push(r[0]);s=r[1];}
return[rx,s];};},optional:function(p){return function(s){var r=null;try{r=p.call(this,s);}catch(e){return[null,s];}
return[r[0],r[1]];};},not:function(p){return function(s){try{p.call(this,s);}catch(e){return[null,s];}
throw new $P.Exception(s);};},ignore:function(p){return p?function(s){var r=null;r=p.call(this,s);return[null,r[1]];}:null;},product:function(){var px=arguments[0],qx=Array.prototype.slice.call(arguments,1),rx=[];for(var i=0;i<px.length;i++){rx.push(_.each(px[i],qx));}
return rx;},cache:function(rule){var cache={},r=null;return function(s){try{r=cache[s]=(cache[s]||rule.call(this,s));}catch(e){r=cache[s]=e;}
if(r instanceof $P.Exception){throw r;}else{return r;}};},any:function(){var px=arguments;return function(s){var r=null;for(var i=0;i<px.length;i++){if(px[i]==null){continue;}
try{r=(px[i].call(this,s));}catch(e){r=null;}
if(r){return r;}}
throw new $P.Exception(s);};},each:function(){var px=arguments;return function(s){var rx=[],r=null;for(var i=0;i<px.length;i++){if(px[i]==null){continue;}
try{r=(px[i].call(this,s));}catch(e){throw new $P.Exception(s);}
rx.push(r[0]);s=r[1];}
return[rx,s];};},all:function(){var px=arguments,_=_;return _.each(_.optional(px));},sequence:function(px,d,c){d=d||_.rtoken(/^\s*/);c=c||null;if(px.length==1){return px[0];}
return function(s){var r=null,q=null;var rx=[];for(var i=0;i<px.length;i++){try{r=px[i].call(this,s);}catch(e){break;}
rx.push(r[0]);try{q=d.call(this,r[1]);}catch(ex){q=null;break;}
s=q[1];}
if(!r){throw new $P.Exception(s);}
if(q){throw new $P.Exception(q[1]);}
if(c){try{r=c.call(this,r[1]);}catch(ey){throw new $P.Exception(r[1]);}}
return[rx,(r?r[1]:s)];};},between:function(d1,p,d2){d2=d2||d1;var _fn=_.each(_.ignore(d1),p,_.ignore(d2));return function(s){var rx=_fn.call(this,s);return[[rx[0][0],r[0][2]],rx[1]];};},list:function(p,d,c){d=d||_.rtoken(/^\s*/);c=c||null;return(p instanceof Array?_.each(_.product(p.slice(0,-1),_.ignore(d)),p.slice(-1),_.ignore(c)):_.each(_.many(_.each(p,_.ignore(d))),px,_.ignore(c)));},set:function(px,d,c){d=d||_.rtoken(/^\s*/);c=c||null;return function(s){var r=null,p=null,q=null,rx=null,best=[[],s],last=false;for(var i=0;i<px.length;i++){q=null;p=null;r=null;last=(px.length==1);try{r=px[i].call(this,s);}catch(e){continue;}
rx=[[r[0]],r[1]];if(r[1].length>0&&!last){try{q=d.call(this,r[1]);}catch(ex){last=true;}}else{last=true;}
if(!last&&q[1].length===0){last=true;}
if(!last){var qx=[];for(var j=0;j<px.length;j++){if(i!=j){qx.push(px[j]);}}
p=_.set(qx,d).call(this,q[1]);if(p[0].length>0){rx[0]=rx[0].concat(p[0]);rx[1]=p[1];}}
if(rx[1].length<best[1].length){best=rx;}
if(best[1].length===0){break;}}
if(best[0].length===0){return best;}
if(c){try{q=c.call(this,best[1]);}catch(ey){throw new $P.Exception(best[1]);}
best[1]=q[1];}
return best;};},forward:function(gr,fname){return function(s){return gr[fname].call(this,s);};},replace:function(rule,repl){return function(s){var r=rule.call(this,s);return[repl,r[1]];};},process:function(rule,fn){return function(s){var r=rule.call(this,s);return[fn.call(this,r[0]),r[1]];};},min:function(min,rule){return function(s){var rx=rule.call(this,s);if(rx[0].length<min){throw new $P.Exception(s);}
return rx;};}};var _generator=function(op){return function(){var args=null,rx=[];if(arguments.length>1){args=Array.prototype.slice.call(arguments);}else if(arguments[0]instanceof Array){args=arguments[0];}
if(args){for(var i=0,px=args.shift();i<px.length;i++){args.unshift(px[i]);rx.push(op.apply(null,args));args.shift();return rx;}}else{return op.apply(null,arguments);}};};var gx="optional not ignore cache".split(/\s/);for(var i=0;i<gx.length;i++){_[gx[i]]=_generator(_[gx[i]]);}
var _vector=function(op){return function(){if(arguments[0]instanceof Array){return op.apply(null,arguments[0]);}else{return op.apply(null,arguments);}};};var vx="each any all".split(/\s/);for(var j=0;j<vx.length;j++){_[vx[j]]=_vector(_[vx[j]]);}}());(function(){var flattenAndCompact=function(ax){var rx=[];for(var i=0;i<ax.length;i++){if(ax[i]instanceof Array){rx=rx.concat(flattenAndCompact(ax[i]));}else{if(ax[i]){rx.push(ax[i]);}}}
return rx;};Date.Grammar={};Date.Translator={hour:function(s){return function(){this.hour=Number(s);};},minute:function(s){return function(){this.minute=Number(s);};},second:function(s){return function(){this.second=Number(s);};},meridian:function(s){return function(){this.meridian=s.slice(0,1).toLowerCase();};},timezone:function(s){return function(){var n=s.replace(/[^\d\+\-]/g,"");if(n.length){this.timezoneOffset=Number(n);}else{this.timezone=s.toLowerCase();}};},day:function(x){var s=x[0];return function(){this.day=Number(s.match(/\d+/)[0]);};},month:function(s){return function(){this.month=((s.length==3)?Date.getMonthNumberFromName(s):(Number(s)-1));};},year:function(s){return function(){var n=Number(s);this.year=((s.length>2)?n:(n+(((n+2000)<Date.CultureInfo.twoDigitYearMax)?2000:1900)));};},rday:function(s){return function(){switch(s){case"yesterday":this.days=-1;break;case"tomorrow":this.days=1;break;case"today":this.days=0;break;case"now":this.days=0;this.now=true;break;}};},finishExact:function(x){x=(x instanceof Array)?x:[x];var now=new Date();this.year=now.getFullYear();this.month=now.getMonth();this.day=1;this.hour=0;this.minute=0;this.second=0;for(var i=0;i<x.length;i++){if(x[i]){x[i].call(this);}}
this.hour=(this.meridian=="p"&&this.hour<13)?this.hour+12:this.hour;if(this.day>Date.getDaysInMonth(this.year,this.month)){throw new RangeError(this.day+" is not a valid value for days.");}
var r=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second);if(this.timezone){r.set({timezone:this.timezone});}else if(this.timezoneOffset){r.set({timezoneOffset:this.timezoneOffset});}
return r;},finish:function(x){x=(x instanceof Array)?flattenAndCompact(x):[x];if(x.length===0){return null;}
for(var i=0;i<x.length;i++){if(typeof x[i]=="function"){x[i].call(this);}}
if(this.now){return new Date();}
var today=Date.today();var method=null;var expression=!!(this.days!=null||this.orient||this.operator);if(expression){var gap,mod,orient;orient=((this.orient=="past"||this.operator=="subtract")?-1:1);if(this.weekday){this.unit="day";gap=(Date.getDayNumberFromName(this.weekday)-today.getDay());mod=7;this.days=gap?((gap+(orient*mod))%mod):(orient*mod);}
if(this.month){this.unit="month";gap=(this.month-today.getMonth());mod=12;this.months=gap?((gap+(orient*mod))%mod):(orient*mod);this.month=null;}
if(!this.unit){this.unit="day";}
if(this[this.unit+"s"]==null||this.operator!=null){if(!this.value){this.value=1;}
if(this.unit=="week"){this.unit="day";this.value=this.value*7;}
this[this.unit+"s"]=this.value*orient;}
return today.add(this);}else{if(this.meridian&&this.hour){this.hour=(this.hour<13&&this.meridian=="p")?this.hour+12:this.hour;}
if(this.weekday&&!this.day){this.day=(today.addDays((Date.getDayNumberFromName(this.weekday)-today.getDay()))).getDate();}
if(this.month&&!this.day){this.day=1;}
return today.set(this);}}};var _=Date.Parsing.Operators,g=Date.Grammar,t=Date.Translator,_fn;g.datePartDelimiter=_.rtoken(/^([\s\-\.\,\/\x27]+)/);g.timePartDelimiter=_.stoken(":");g.whiteSpace=_.rtoken(/^\s*/);g.generalDelimiter=_.rtoken(/^(([\s\,]|at|on)+)/);var _C={};g.ctoken=function(keys){var fn=_C[keys];if(!fn){var c=Date.CultureInfo.regexPatterns;var kx=keys.split(/\s+/),px=[];for(var i=0;i<kx.length;i++){px.push(_.replace(_.rtoken(c[kx[i]]),kx[i]));}
fn=_C[keys]=_.any.apply(null,px);}
return fn;};g.ctoken2=function(key){return _.rtoken(Date.CultureInfo.regexPatterns[key]);};g.h=_.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2]|[1-9])/),t.hour));g.hh=_.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2])/),t.hour));g.H=_.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3]|[0-9])/),t.hour));g.HH=_.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3])/),t.hour));g.m=_.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/),t.minute));g.mm=_.cache(_.process(_.rtoken(/^[0-5][0-9]/),t.minute));g.s=_.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/),t.second));g.ss=_.cache(_.process(_.rtoken(/^[0-5][0-9]/),t.second));g.hms=_.cache(_.sequence([g.H,g.mm,g.ss],g.timePartDelimiter));g.t=_.cache(_.process(g.ctoken2("shortMeridian"),t.meridian));g.tt=_.cache(_.process(g.ctoken2("longMeridian"),t.meridian));g.z=_.cache(_.process(_.rtoken(/^(\+|\-)?\s*\d\d\d\d?/),t.timezone));g.zz=_.cache(_.process(_.rtoken(/^(\+|\-)\s*\d\d\d\d/),t.timezone));g.zzz=_.cache(_.process(g.ctoken2("timezone"),t.timezone));g.timeSuffix=_.each(_.ignore(g.whiteSpace),_.set([g.tt,g.zzz]));g.time=_.each(_.optional(_.ignore(_.stoken("T"))),g.hms,g.timeSuffix);g.d=_.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1]|\d)/),_.optional(g.ctoken2("ordinalSuffix"))),t.day));g.dd=_.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1])/),_.optional(g.ctoken2("ordinalSuffix"))),t.day));g.ddd=g.dddd=_.cache(_.process(g.ctoken("sun mon tue wed thu fri sat"),function(s){return function(){this.weekday=s;};}));g.M=_.cache(_.process(_.rtoken(/^(1[0-2]|0\d|\d)/),t.month));g.MM=_.cache(_.process(_.rtoken(/^(1[0-2]|0\d)/),t.month));g.MMM=g.MMMM=_.cache(_.process(g.ctoken("jan feb mar apr may jun jul aug sep oct nov dec"),t.month));g.y=_.cache(_.process(_.rtoken(/^(\d\d?)/),t.year));g.yy=_.cache(_.process(_.rtoken(/^(\d\d)/),t.year));g.yyy=_.cache(_.process(_.rtoken(/^(\d\d?\d?\d?)/),t.year));g.yyyy=_.cache(_.process(_.rtoken(/^(\d\d\d\d)/),t.year));_fn=function(){return _.each(_.any.apply(null,arguments),_.not(g.ctoken2("timeContext")));};g.day=_fn(g.d,g.dd);g.month=_fn(g.M,g.MMM);g.year=_fn(g.yyyy,g.yy);g.orientation=_.process(g.ctoken("past future"),function(s){return function(){this.orient=s;};});g.operator=_.process(g.ctoken("add subtract"),function(s){return function(){this.operator=s;};});g.rday=_.process(g.ctoken("yesterday tomorrow today now"),t.rday);g.unit=_.process(g.ctoken("minute hour day week month year"),function(s){return function(){this.unit=s;};});g.value=_.process(_.rtoken(/^\d\d?(st|nd|rd|th)?/),function(s){return function(){this.value=s.replace(/\D/g,"");};});g.expression=_.set([g.rday,g.operator,g.value,g.unit,g.orientation,g.ddd,g.MMM]);_fn=function(){return _.set(arguments,g.datePartDelimiter);};g.mdy=_fn(g.ddd,g.month,g.day,g.year);g.ymd=_fn(g.ddd,g.year,g.month,g.day);g.dmy=_fn(g.ddd,g.day,g.month,g.year);g.date=function(s){return((g[Date.CultureInfo.dateElementOrder]||g.mdy).call(this,s));};g.format=_.process(_.many(_.any(_.process(_.rtoken(/^(dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|zz?z?)/),function(fmt){if(g[fmt]){return g[fmt];}else{throw Date.Parsing.Exception(fmt);}}),_.process(_.rtoken(/^[^dMyhHmstz]+/),function(s){return _.ignore(_.stoken(s));}))),function(rules){return _.process(_.each.apply(null,rules),t.finishExact);});var _F={};var _get=function(f){return _F[f]=(_F[f]||g.format(f)[0]);};g.formats=function(fx){if(fx instanceof Array){var rx=[];for(var i=0;i<fx.length;i++){rx.push(_get(fx[i]));}
return _.any.apply(null,rx);}else{return _get(fx);}};g._formats=g.formats(["yyyy-MM-ddTHH:mm:ss","ddd, MMM dd, yyyy H:mm:ss tt","ddd MMM d yyyy HH:mm:ss zzz","d"]);g._start=_.process(_.set([g.date,g.time,g.expression],g.generalDelimiter,g.whiteSpace),t.finish);g.start=function(s){try{var r=g._formats.call({},s);if(r[1].length===0){return r;}}catch(e){}
return g._start.call({},s);};}());Date._parse=Date.parse;Date.parse=function(s){var r=null;if(!s){return null;}
try{r=Date.Grammar.start.call({},s);}catch(e){return null;}
return((r[1].length===0)?r[0]:null);};Date.getParseFunction=function(fx){var fn=Date.Grammar.formats(fx);return function(s){var r=null;try{r=fn.call({},s);}catch(e){return null;}
return((r[1].length===0)?r[0]:null);};};Date.parseExact=function(s,fx){return Date.getParseFunction(fx)(s);};

/**
 * @version: 1.0 Alpha-1
 * @author: Coolite Inc. http://www.coolite.com/
 * @date: 2008-04-13
 * @copyright: Copyright (c) 2006-2008, Coolite Inc. (http://www.coolite.com/). All rights reserved.
 * @license: Licensed under The MIT License. See license.txt and http://www.datejs.com/license/.
 * @website: http://www.datejs.com/
 */

(function () {
    var $D = Date,
        $P = $D.prototype,
        $C = $D.CultureInfo,
        $f = [],
        p = function (s, l) {
            if (!l) {
                l = 2;
            }
            return ("000" + s).slice(l * -1);
        };

    /**
     * Converts a PHP format string to Java/.NET format string.
     * A PHP format string can be used with .$format or .format.
     * A Java/.NET format string can be used with .toString().
     * The .parseExact function will only accept a Java/.NET format string
     *
     * Example
     <pre>
     var f1 = "%m/%d/%y"
     var f2 = Date.normalizeFormat(f1); // "MM/dd/yy"

     new Date().format(f1);    // "04/13/08"
     new Date().$format(f1);   // "04/13/08"
     new Date().toString(f2);  // "04/13/08"

     var date = Date.parseExact("04/13/08", f2); // Sun Apr 13 2008
     </pre>
     * @param {String}   A PHP format string consisting of one or more format spcifiers.
     * @return {String}  The PHP format converted to a Java/.NET format string.
     */
    $D.normalizeFormat = function (format) {
        $f = [];
        var t = new Date().$format(format);
        return $f.join("");
    };

    /**
     * Format a local Unix timestamp according to locale settings
     *
     * Example
     <pre>
     Date.strftime("%m/%d/%y", new Date());       // "04/13/08"
     Date.strftime("c", "2008-04-13T17:52:03Z");  // "04/13/08"
     </pre>
     * @param {String}   A format string consisting of one or more format spcifiers [Optional].
     * @param {Number}   The number representing the number of seconds that have elapsed since January 1, 1970 (local time).
     * @return {String}  A string representation of the current Date object.
     */
    $D.strftime = function (format, time) {
        return new Date(time * 1000).$format(format);
    };

    /**
     * Parse any textual datetime description into a Unix timestamp.
     * A Unix timestamp is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT).
     *
     * Example
     <pre>
     Date.strtotime("04/13/08");              // 1208044800
     Date.strtotime("1970-01-01T00:00:00Z");  // 0
     </pre>
     * @param {String}   A format string consisting of one or more format spcifiers [Optional].
     * @param {Object}   A string or date object.
     * @return {String}  A string representation of the current Date object.
     */
    $D.strtotime = function (time) {
        var d = $D.parse(time);
        d.addMinutes(d.getTimezoneOffset() * -1);
        return Math.round($D.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds()) / 1000);
    };

    /**
     * Converts the value of the current Date object to its equivalent string representation using a PHP/Unix style of date format specifiers.
     *
     * The following descriptions are from http://www.php.net/strftime and http://www.php.net/manual/en/function.date.php.
     * Copyright � 2001-2008 The PHP Group
     *
     * Format Specifiers
     <pre>
    Format  Description                                                                  Example
    ------  ---------------------------------------------------------------------------  -----------------------
     %a     abbreviated weekday name according to the current localed                    "Mon" through "Sun"
     %A     full weekday name according to the current locale                            "Sunday" through "Saturday"
     %b     abbreviated month name according to the current locale                       "Jan" through "Dec"
     %B     full month name according to the current locale                              "January" through "December"
     %c     preferred date and time representation for the current locale                "4/13/2008 12:33 PM"
     %C     century number (the year divided by 100 and truncated to an integer)         "00" to "99"
     %d     day of the month as a decimal number                                         "01" to "31"
     %D     same as %m/%d/%y                                                             "04/13/08"
     %e     day of the month as a decimal number, a single digit is preceded by a space  "1" to "31"
     %g     like %G, but without the century                                             "08"
     %G     The 4-digit year corresponding to the ISO week number (see %V).              "2008"
            This has the same format and value as %Y, except that if the ISO week number
            belongs to the previous or next year, that year is used instead.
     %h     same as %b                                                                   "Jan" through "Dec"
     %H     hour as a decimal number using a 24-hour clock                               "00" to "23"
     %I     hour as a decimal number using a 12-hour clock                               "01" to "12"
     %j     day of the year as a decimal number                                          "001" to "366"
     %m     month as a decimal number                                                    "01" to "12"
     %M     minute as a decimal number                                                   "00" to "59"
     %n     newline character                                                            "\n"
     %p     either "am" or "pm" according to the given time value, or the                "am" or "pm"
            corresponding strings for the current locale
     %r     time in a.m. and p.m. notation                                               "8:44 PM"
     %R     time in 24 hour notation                                                     "20:44"
     %S     second as a decimal number                                                   "00" to "59"
     %t     tab character                                                                "\t"
     %T     current time, equal to %H:%M:%S                                              "12:49:11"
     %u     weekday as a decimal number ["1", "7"], with "1" representing Monday         "1" to "7"
     %U     week number of the current year as a decimal number, starting with the       "0" to ("52" or "53")
            first Sunday as the first day of the first week
     %V     The ISO 8601:1988 week number of the current year as a decimal number,       "00" to ("52" or "53")
            range 01 to 53, where week 1 is the first week that has at least 4 days
            in the current year, and with Monday as the first day of the week.
            (Use %G or %g for the year component that corresponds to the week number
            for the specified timestamp.)
     %W     week number of the current year as a decimal number, starting with the       "00" to ("52" or "53")
            first Monday as the first day of the first week
     %w     day of the week as a decimal, Sunday being "0"                               "0" to "6"
     %x     preferred date representation for the current locale without the time        "4/13/2008"
     %X     preferred time representation for the current locale without the date        "12:53:05"
     %y     year as a decimal number without a century                                   "00" "99"
     %Y     year as a decimal number including the century                               "2008"
     %Z     time zone or name or abbreviation                                            "UTC", "EST", "PST"
     %z     same as %Z
     %%     a literal "%" character                                                      "%"

     d      Day of the month, 2 digits with leading zeros                                "01" to "31"
     D      A textual representation of a day, three letters                             "Mon" through "Sun"
     j      Day of the month without leading zeros                                       "1" to "31"
     l      A full textual representation of the day of the week (lowercase "L")         "Sunday" through "Saturday"
     N      ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0)  "1" (for Monday) through "7" (for Sunday)
     S      English ordinal suffix for the day of the month, 2 characters                "st", "nd", "rd" or "th". Works well with j
     w      Numeric representation of the day of the week                                "0" (for Sunday) through "6" (for Saturday)
     z      The day of the year (starting from "0")                                      "0" through "365"
     W      ISO-8601 week number of year, weeks starting on Monday                       "00" to ("52" or "53")
     F      A full textual representation of a month, such as January or March           "January" through "December"
     m      Numeric representation of a month, with leading zeros                        "01" through "12"
     M      A short textual representation of a month, three letters                     "Jan" through "Dec"
     n      Numeric representation of a month, without leading zeros                     "1" through "12"
     t      Number of days in the given month                                            "28" through "31"
     L      Whether it's a leap year                                                     "1" if it is a leap year, "0" otherwise
     o      ISO-8601 year number. This has the same value as Y, except that if the       "2008"
            ISO week number (W) belongs to the previous or next year, that year
            is used instead.
     Y      A full numeric representation of a year, 4 digits                            "2008"
     y      A two digit representation of a year                                         "08"
     a      Lowercase Ante meridiem and Post meridiem                                    "am" or "pm"
     A      Uppercase Ante meridiem and Post meridiem                                    "AM" or "PM"
     B      Swatch Internet time                                                         "000" through "999"
     g      12-hour format of an hour without leading zeros                              "1" through "12"
     G      24-hour format of an hour without leading zeros                              "0" through "23"
     h      12-hour format of an hour with leading zeros                                 "01" through "12"
     H      24-hour format of an hour with leading zeros                                 "00" through "23"
     i      Minutes with leading zeros                                                   "00" to "59"
     s      Seconds, with leading zeros                                                  "00" through "59"
     u      Milliseconds                                                                 "54321"
     e      Timezone identifier                                                          "UTC", "EST", "PST"
     I      Whether or not the date is in daylight saving time (uppercase i)             "1" if Daylight Saving Time, "0" otherwise
     O      Difference to Greenwich time (GMT) in hours                                  "+0200", "-0600"
     P      Difference to Greenwich time (GMT) with colon between hours and minutes      "+02:00", "-06:00"
     T      Timezone abbreviation                                                        "UTC", "EST", "PST"
     Z      Timezone offset in seconds. The offset for timezones west of UTC is          "-43200" through "50400"
            always negative, and for those east of UTC is always positive.
     c      ISO 8601 date                                                                "2004-02-12T15:19:21+00:00"
     r      RFC 2822 formatted date                                                      "Thu, 21 Dec 2000 16:01:07 +0200"
     U      Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)                   "0"
     </pre>
     * @param {String}   A format string consisting of one or more format spcifiers [Optional].
     * @return {String}  A string representation of the current Date object.
     */
    $P.$format = function (format) {
        var x = this,
            y,
            t = function (v) {
                $f.push(v);
                return x.toString(v);
            };

        return format ? format.replace(/(%|\\)?.|%%/g,
        function (m) {
            if (m.charAt(0) === "\\" || m.substring(0, 2) === "%%") {
                return m.replace("\\", "").replace("%%", "%");
            }
            switch (m) {
            case "d":
            case "%d":
                return t("dd");
            case "D":
            case "%a":
                return t("ddd");
            case "j":
            case "%e":
                return t("d");
            case "l":
            case "%A":
                return t("dddd");
            case "N":
            case "%u":
                return x.getDay() + 1;
            case "S":
                return t("S");
            case "w":
            case "%w":
                return x.getDay();
            case "z":
                return x.getOrdinalNumber();
            case "%j":
                return p(x.getOrdinalNumber(), 3);
            case "%U":
                var d1 = x.clone().set({month: 0, day: 1}).addDays(-1).moveToDayOfWeek(0),
                    d2 = x.clone().addDays(1).moveToDayOfWeek(0, -1);
                return (d2 < d1) ? "00" : p((d2.getOrdinalNumber() - d1.getOrdinalNumber()) / 7 + 1);
            case "W":
            case "%V":
                return x.getISOWeek();
            case "%W":
                return p(x.getWeek());
            case "F":
            case "%B":
                return t("MMMM");
            case "m":
            case "%m":
                return t("MM");
            case "M":
            case "%b":
            case "%h":
                return t("MMM");
            case "n":
                return t("M");
            case "t":
                return $D.getDaysInMonth(x.getFullYear(), x.getMonth());
            case "L":
                return ($D.isLeapYear(x.getFullYear())) ? 1 : 0;
            case "o":
            case "%G":
                return x.setWeek(x.getISOWeek()).toString("yyyy");
            case "%g":
                return x.$format("%G").slice(-2);
            case "Y":
            case "%Y":
                return t("yyyy");
            case "y":
            case "%y":
                return t("yy");
            case "a":
            case "%p":
                return t("tt").toLowerCase();
            case "A":
                return t("tt").toUpperCase();
            case "g":
            case "%I":
                return t("h");
            case "G":
                return t("H");
            case "h":
                return t("hh");
            case "H":
            case "%H":
                return t("HH");
            case "i":
            case "%M":
                return t("mm");
            case "s":
            case "%S":
                return t("ss");
            case "u":
                return p(x.getMilliseconds(), 3);
            case "I":
                return (x.isDaylightSavingTime()) ? 1 : 0;
            case "O":
                return x.getUTCOffset();
            case "P":
                y = x.getUTCOffset();
                return y.substring(0, y.length - 2) + ":" + y.substring(y.length - 2);
            case "e":
            case "T":
            case "%z":
            case "%Z":
                return x.getTimezone();
            case "Z":
                return x.getTimezoneOffset() * -60;
            case "B":
                var now = new Date();
                return Math.floor(((now.getHours() * 3600) + (now.getMinutes() * 60) + now.getSeconds() + (now.getTimezoneOffset() + 60) * 60) / 86.4);
            case "c":
                return x.toISOString().replace(/\"/g, "");
            case "U":
                return $D.strtotime("now");
            case "%c":
                return t("d") + " " + t("t");
            case "%C":
                return Math.floor(x.getFullYear() / 100 + 1);
            case "%D":
                return t("MM/dd/yy");
            case "%n":
                return "\\n";
            case "%t":
                return "\\t";
            case "%r":
                return t("hh:mm tt");
            case "%R":
                return t("H:mm");
            case "%T":
                return t("H:mm:ss");
            case "%x":
                return t("d");
            case "%X":
                return t("t");
            default:
                $f.push(m);
                return m;
            }
        }
        ) : this._toString();
    };

    if (!$P.format) {
        $P.format = $P.$format;
    }
}());

    /*
    Copyright (c) 2009 Justin Donato (http://www.justindonato.com)

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.

    MTMultiSelect: An widget to make more user friendly interfaces
    for a multiselect box, using Mootools

    Usage:

    Link to this file, then add

    window.addEvent('domready', function (){
         $$('.multiselect').each(function(multiselect){
            new MTMultiWidget({'datasrc': multiselect});
        });

    });

    to your page, where '.multiselect' is a selector that picks out a class of
    <select MULTIPLE> elements. This element acts as the data source for the
    widget. Then create a css file and style the widget however you'd like.

    Options: add these to the object you pass to the MTMultiWidget constructor.
    Only datasrc is required.

    widgetcls:
    The css class applied to your final widget.
    Default is 'mtmultiselect'

    datasrc:
    A select multiple dom object

    selectedcls:
    The css class of the selected list item.
    Default is  'selected'

    paginator_on_bottom:
    Determines placement of paginator, true or false.
    Default is true

    items_per_page:
    Determines how many items to show on a single page.
    Default is 10.

    case_sensitive:
    Determines if the filter form is case_sensitive or not
    Default is False

    */

    var MTMultiWidget = new Class({

        Implements: [Options],

        options: {
            'widgetcls': 'mtmultiselect', // the class for your final widget
            'datasrc': null  // a select multiple dom object
        },

        handleDisplayEvent: function(numselected){this.filterform.update(numselected);},

        handleFilterEvent: function(list){
            this.curlist = list;
            this.paginator.setpagenum(1);
            var page = this.paginator.getpage(list);
            this.displaylist.build(page);
        },

        handlePaginatorEvent: function(){
            var page = this.paginator.getpage(this.curlist);
            this.displaylist.build(page);
        },

        handleSelectAll: function (){
            this.curlist.each(function (item)
            {
                item.selected = true;
            });

            var page = this.paginator.getpage(this.curlist);
            this.displaylist.build(page);
            this.filterform.update(this.displaylist.numselected());
        },

        handleSelectNone: function (){
            this.curlist.each(function (item)
            {
                item.selected = false;
            });

            var page = this.paginator.getpage(this.curlist);
            this.displaylist.build(page);
            this.filterform.update(this.displaylist.numselected());
        },

        initialize: function(options){
            this.setOptions(options);
            // Hide the original data source and create a new div for the widget
            // and inect this new widget into the Dom.
            options.datasrc.setStyles({'display': 'None'});
            var view = new Element('div', {'class': this.options.widgetcls});
            view.injectAfter(options.datasrc);
            //options.datasrc.getParent().grab(view);
            // Add the widget to the options. Pass them into a new DisplayList
            options.view = view;

            this.displaylist = new DisplayList(options);
            options.numselected = this.displaylist.numselected();
            this.filterform = new FilterForm(options);
            this.paginator = new Paginator(options);
            this.toolbox = new Toolbox(options);

            this.curlist = this.options.datasrc.getChildren();

            this.displaylist.addEvent('rebuild', this.handleDisplayEvent.bind(this));
            this.filterform.addEvent('rebuild', this.handleFilterEvent.bind(this));
            this.paginator.addEvent('rebuild', this.handlePaginatorEvent.bind(this));

            this.toolbox.addEvent('select_all', this.handleSelectAll.bind(this));
            this.toolbox.addEvent('select_none', this.handleSelectNone.bind(this));

            var page = this.paginator.getpage(this.curlist);
            this.toolbox.build();
            this.filterform.build();
            this.displaylist.build(page);
        }
    });

    /*
        DisplayList
    */

    var DisplayList = new Class({

        Implements: [Options, Events],

        options: {
            selectedcls: 'selected', // class of the item when its selected
            datasrc: null, // a multiple select dom elemenet
            view: null, // A parent or wrapper dom element where this element lives
            paginator_on_bottom: true
        },

        initialize: function(options){this.setOptions(options);},

        build: function(opts){

            // If there's already an ol, remove it.
            var old = this.options.view.getElement('ol');
            if(old !== null) old.destroy();

            // create the list to hold the visible elements
            list = new Element('ol');
            place = this.options.paginator_on_bottom ? 'before' : 'after';
            list.inject(this.options.view.getLast(), place);
            //this.options.view.grab(list);

            opts.each(function(item){
                    var li = new Element('li',{
                        'class': item.selected ? this.options.selectedcls : null,
                        'text': item.get('text')
                    });
                    li.store('select', item);
                    list.grab(li);

                    li.addEvent('click', function(evt){
                        evt.target.toggleClass('selected');
                        evt.target.retrieve('select').selected = evt.target.hasClass('selected');
                        this.fireEvent('rebuild', this.numselected());
                    }.bind(this));
                }.bind(this));
        },

        total: function(){
            return this.options.datasrc.getChildren().length;
        },

        numselected: function(){
            var numselected = 0;
            this.options.datasrc.getChildren().each(function(item){
                if(item.selected) numselected++;
            });
            return numselected;
        }

    });

    /*
        Paginator
    */

    var Paginator = new Class({
        Implements: [Options, Events],

        /* Paginator might have to look at weather an item is hidden or not */

        options: {
            'items_per_page': 10,
            'list': [], // the list the paginator will use
            'displaylist': null // the view element for the results
        },

        initialize: function(options){
            this.setOptions(options);
            this.items_per_page = this.options.items_per_page;
            this.page = 1;
            // create the view element
            this.controls = new Element('div', {'class':'mtms_paginator'});
            this.options.view.grab(this.controls);
        },

        numpages: function(list){
            return Math.ceil(list.length / this.items_per_page );
        },

        getpage: function(list){
            var start = ((this.page - 1) * this.items_per_page);
            var end = start + this.items_per_page;
            this.updateControls(list);
            return list.slice(start, end);
        },

        pageup: function(){this.page++;},

        pagedown: function(){this.page--;},

        updateControls: function(list){

            var numpages = this.numpages(list);
            this.controls.empty();

            var prevbtn = new Element('a', {'text':'prev',
                                            'href':'#cpcspswdnbd'});
            this.controls.grab(prevbtn, 'top');
            prevbtn.addClass('disabled');

            if(this.page > 1){
                prevbtn.removeClass('disabled');
                prevbtn.addEvent('click', function(evt){
                    this.pagedown();
                    this.fireEvent('rebuild', list);
                }.bind(this));
            }

            for(var i = 1; i <= numpages; i++){
                this.controls.grab(new Element('a', {'text': i,
                                                     'href': '#cpcspswdnbd',
                                                     'class': (i  == this.page) ? 'selected' : '',
                                                     'events': {
                                                        'click': function(evt){
                                                            this.setpagenum(evt.target.innerHTML);
                                                            this.fireEvent('rebuild', [list]); // wrapped list
                                                        }.bind(this)}
                                               }), 'bottom');
            }

            var nextbtn = new Element('a', {'text':'next',
                                            'href':'#cpcspswdnbd'});
            this.controls.grab(nextbtn);
            nextbtn.addClass('disabled');

            if(this.page < numpages){
                nextbtn.removeClass('disabled');
                nextbtn.addEvent('click', function(evt){
                    this.pageup();
                    this.fireEvent('rebuild');
                }.bind(this));
            }


        },

        setpagenum: function(pagenum){
            this.page = Number(pagenum);
        }
    });

    /*
        FilterForm
    */

    var FilterForm = new Class({

        RESETINPUT: true,

        Implements: [Options, Events],

        options: {
            view: null,
            case_sensitive: false,
            displaylist: null,
            inputpos: 'top',
            labels: {'total': 'total',
                     'selected': 'selected',
                     'unselected': 'unselected',
                     'filter': 'filter',
                     'in': 'in',
                     'out': 'out',
                     'page': 'page'
                    },
            classes: {
                'total': 'mttotal',
                'selected': 'mtselected'
            }
        },

        initialize: function(options){
            this.setOptions(options);
            this.numselected = options.numselected;
        },

        build: function(){
            // infofilter bar is made out of a u list
            var ul = new Element('ul', {'class': 'mtms_filtercontrols'});
            this.options.view.grab(ul, this.options.inputpos);

            this.totalbtn = this.makebtn(this.options.labels.total,
                         this.showtotal,
                         this.options.datasrc.getChildren().length);
            ul.grab(this.totalbtn);

            this.selectedbtn = this.makebtn(this.options.labels.selected,
                                    this.showselected,
                                    this.numselected);
            ul.grab(this.selectedbtn);

            this.unselectedbtn = this.makebtn(this.options.labels.unselected,
                                    this.showunselected,
                                    this.options.datasrc.getChildren().length - this.numselected);
            ul.grab(this.unselectedbtn);

            // Make text field for filter
            // On keyup, the displaylist.filter is called with a function
            // that filters based on what's been entered in the textfield
            filterbox_container = new Element('div', {'class': 'mtms_filterbox'});
            this.filterbox = new Element('input', {
                'events': {
                    'keyup': function(evt){
                        if(this.options.case_sensitive){
                            filter_by_text = function(item){ return item.text.contains(evt.target.value)};
                        } else {
                            filter_by_text = function(item){ return item.text.toLowerCase().contains(evt.target.value.toLowerCase()) };
                        }
                        this.filter(this.options.datasrc.getChildren(), filter_by_text);
                    }.bind(this)
                },
                value: 'Search',
                'class': 'inputfocus'
            });
            filterbox_container.grab(this.filterbox);

            this.options.view.grab(filterbox_container, this.options.inputpos);
        },

        /*
           label: clickable link text
           func: the function that is called when clicked
           prefix: some bit of text that precedes the label. (Used to show
           counts here.)

        */
        makebtn: function(label, func, prefix){
            var li = new Element('li');
            var btn = new Element('a', {'html': label,
                                        'href': '#cpcspswdnbd',
                                        'events': {
                                             // You might have to bind this differently
                                            'click': func.bind(this)
                                        }
                                    });
            li.grab(btn);
            if(prefix !== undefined){
                prefix = new Element('span', {'text': prefix});
                li.grab(prefix);
            }
            return li;
        },

        showtotal: function(){
            ('show total called');
            // return true for every item in the datasrc
            this.filter(this.options.datasrc.getChildren(),
                function(item){
                    return true;
                },
                this.RESETINPUT
            );
        },
        showselected: function(){
            this.filter(this.options.datasrc.getChildren(),
                function(item){
                    return (item.selected === true);
                },
                this.RESETINPUT
            );
        },
        showunselected:function(){
            this.filter(this.options.datasrc.getChildren(),
                function(item){
                    return (item.selected !== true);
                },
                this.RESETINPUT
            );
        },
        // list is the list of option dom elements from the select elem
        // test is a function that gets used in the filter
        filter: function(list, test, reset){
            results = list.filter(function(item, index){
                return test(item);
            });

            if(reset){
                this.filterbox.value = "";
            }
            this.fireEvent('rebuild', [results]);
        },
        update: function(numselected){
            var total = this.options.datasrc.getChildren().length;
            this.totalbtn.getElement('span').set('text', total);
            this.selectedbtn.getElement('span').set('text', numselected);
            this.unselectedbtn.getElement('span').set('text', total - numselected);
        }
    });

    var Toolbox = new Class
    ({
        Implements: [Options, Events],

        options: {
            view: null,
            displaylist: null,
        },

        initialize: function (options)
        {this.setOptions(options);},

        build: function ()
        {
            var div = new Element('div', {
                'class': 'toolbox'
            });
            var all = new Element('a', {href: '#', text: 'select all'});
            var none = new Element('a', {href: '#', text: 'select none'});

            all.addEvent('click', function (event)
            {
               event.stop();
               this.fireEvent('select_all', this);
            }.bind(this));

            none.addEvent('click', function (event)
            {
                event.stop();
                this.fireEvent('select_none', this);
            }.bind(this));

            div.grab(all);
            div.grab(none);
            this.options.view.grab(div, 'top');
        },
    })

    Element.Events.rebuild = {
        'base': 'change',
        'condition': function(evt){return;}
    };

/* $Id: moo.meiomask.js 52 2008-12-08 02:09:39Z fabiomcosta $ */
/**
 * @version 1.0.0 $Rev: 52 $
 * The MIT License
 * Copyright (c) 2008 Fabio M. Costa http://www.meiocodigo.com
 */
/**
 * moo.meiomask.js
 * $URL: http://svn.assembla.com/svn/meiomask/moo.meiomask.js $
 * @author: $Author: fabiomcosta $
 * @version 1.0.0 $Rev: 52 $
 * @lastchange: $Date: 2008-12-08 00:09:39 -0200 (Mon, 08 Dec 2008) $
 *
 * Created by Fabio M. Costa on 2008-09-16. Please report any bug at http://www.meiocodigo.com
 *
 * Copyright (c) 2008 Fabio M. Costa http://www.meiocodigo.com
 *
 * The MIT License
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

if (!$defined(meio)) var meio = {};

// add the paste event
// browsers like firefox2 and before and opera doenst have the onPaste event, but the paste feature can be done with the onInput event.
$extend(Element.NativeEvents,{
    'paste' : 2, 'input' : 2
});
Element.Events.paste = {
    base : ( Browser.Engine.presto || ( Browser.Engine.gecko && Browser.Engine.version < 19 ))?'input':'paste',
    condition: function(e){
        // because of a ie bug this event needs this delay so i can access the value ofthe input that we are pasting
        // thanks Jan Kassens
        this.fireEvent('paste', e, 1);
        return false;
    }
};

// this is the class that will contain all the
meio.MaskGlobals = new Hash({

    init : function(){

        if(!this.inited){
            var self = this,i,
                keyRep = ( Browser.Platform.ipod ) ? this.iphoneKeyRepresentation : this.keyRepresentation;

            this.setFixedChars(this.fixedChars);

            // constructs number rules
            for(i=0; i<=9; i++) this.rules[i] = new RegExp('[0-'+i+']');

            this.keyRep = keyRep;
            this.ignoreKeys = [];
            // ignore keys array creation for iphone or the normal ones
            Hash.each(keyRep,function(val,key){
                self.ignoreKeys.push( key.toInt() );
            });
            this.inited = true;
        }
        return this;

    },

    reInit : function(){
        this.inited = false;
        return this.init();
    },

    setFixedChars : function(fixedChars){
        this.fixedCharsReg = new RegExp(this.fixedChars);
        this.fixedCharsRegG = new RegExp(this.fixedChars,'g');
        return this;
    },

    // the mask rules. You may add yours!
    // number rules will be overwritten
    rules : {
        'z': /[a-z]/,
        'Z': /[A-Z]/,
        'a': /[a-zA-Z]/,
        '*': /[0-9a-zA-Z]/,
        '@': /[0-9a-zA-ZçÇáàãéèíìóòõúùü]/
    },

    // fixed chars to be used on the masks. You may change it for your needs!
    fixedChars : '[(),.:/ -]',

    // these keys will be ignored by the mask.
    // all these numbers where obtained on the keydown event
    keyRepresentation : {
        8   : 'backspace',
        9   : 'tab',
        13  : 'enter',
        16  : 'shift',
        17  : 'control',
        18  : 'alt',
        27  : 'esc',
        33  : 'page up',
        34  : 'page down',
        35  : 'end',
        36  : 'home',
        37  : 'left',
        38  : 'up',
        39  : 'right',
        40  : 'down',
        45  : 'insert',
        46  : 'delete',
        116 : 'f5',
        224 : 'command'
    },

    iphoneKeyRepresentation : {
        10  : 'go',
        127 : 'delete'
    },

    signals : {
        '+' : '',
        '-' : '-'
    },

    // masks. You may add yours!
    // Ex: $.fn.setMask.masks.msk = {mask: '999'}
    // and then if the 'attr' options value is 'alt', your input should look like:
    // <input type="text" name="some_name" id="some_name" alt="msk" />
    masks : {
        'phone'             : { mask : '(99) 9999-9999' },
        'phone-us'          : { mask : '(999) 999-9999' },
        'cpf'               : { mask : '999.999.999-99' }, // cadastro nacional de pessoa fisica
        'cnpj'              : { mask : '99.999.999/9999-99' },
        'date'              : { mask : '39/19/9999' }, //uk date
        'date-us'           : { mask : '19/39/9999' },
        'cep'               : { mask : '99999-999' },
        'time'              : { mask : '29:69' },
        'cc'                : { mask : '9999 9999 9999 9999' }, //credit card mask
        'integer'           : { mask : '999.999.999.999', type : 'reverse' },
        'decimal'           : { mask : '99,999.999.999.999', type : 'reverse', defaultValue : '000' },
        'decimal-us'        : { mask : '99.999,999,999,999', type : 'reverse', defaultValue : '000' },
        'signed-decimal'    : { mask : '99,999.999.999.999', type : 'reverse', defaultValue : '+000' },
        'signed-decimal-us' : { mask : '99,999.999.999.999', type : 'reverse', defaultValue : '+000' },
        'zip'                 : { mask : '99999' }
    }

});

// nwhite's post at moootools forum
// http://forum.mootools.net/viewtopic.php?id=6409
// emulates singleton pattern
/*meio.MaskGlobals.getInstance = (function(){
    var instance = undefined;
    return function(){
        if(!$defined(instance)) instance = new this();
        return instance;
    };
})();*/


meio.Mask = new Class({

    Implements : [Options,Events],

    // default settings for the plugin
    options : {
        attr : 'alt', // an attr to look for the mask name or the mask itself
        mask : null, // the mask to be used on the input
        type : 'fixed', // the mask of this mask
        defaultValue : '', // the default value for this input
        signal : false  // this should not be set, to use signal at masks put the signal you want ('-' or '+') at the default value of this mask.
                        // See the defined masks for a better understanding.
        //onInvalid : $empty,
        //onValid : $empty,
        //onOverflow : $empty
    },

    initialize : function(el,options){

        this.$el = $(el);
        // verify if the el is a text input element, if its not the case this class doenst work for it
        if( this.$el.get('tag')!='input' || this.$el.get('type')!='text' ) return;
        this.ignore = false;
        this.globals = meio.MaskGlobals.init();

        //event creation
        this.eventsToBind = ['keydown','keypress','keyup','paste'];

        /*this.keydownEvent = this._onMask.bindWithEvent(this,this._keydown);
        this.keypressEvent = this._onMask.bindWithEvent(this,this._keypress);
        this.keyupEvent = this._onMask.bindWithEvent(this,this._keyup);
        this.pasteEvent = this._onMask.bindWithEvent(this,this._paste);*/
        this.eventsToBind.each(function(evt){
            this[evt+'Event'] = this._onMask.bindWithEvent(this,this['_'+evt]);
        }.bind(this));

        //apply the mask
        this.change(options);

    },

    change : function(options){

        // merge so we can see whats the attr that we have to look
        if( $type(options) == 'object' ) this.setOptions(options);

        var mlStr = 'maxLength',
            attrValue = this.$el.get(this.options.attr),
            tmpMask;

        // then we look for the 'attr' option
        tmpMask = ( $type(options) == 'string' ) ? options : (attrValue) ? attrValue : null;
        if(tmpMask) this.options.mask = tmpMask;

        // then we see if it's a defined mask
        if(this.globals.masks[this.options.mask])
            this.setOptions(this.globals.masks[this.options.mask]);

        // apply the json options if any
        if( JSON ) this.setOptions( JSON.decode(tmpMask,true) );

        if( this.options.mask ){

            if(this.$el.retrieve('mask')) this.remove();

            var defaultValue = this.options.defaultValue,
                mlValue = this.$el.get(mlStr);

            this.setOptions({
                maxlength : mlValue,
                maskArray : this.options.mask.split(''),
                maskNonFixedChars : this.options.mask.replace(this.globals.fixedCharsRegG,'')
            });

            //sets text-align right for reverse masks
            if(this.options.type=='reverse') this.$el.setStyle('text-align','right');

            // apply mask to the current value of the input
            if(this.$el.get('value')!='') this.$el.set('value', this.$el.get('value').mask(this.options) );

            // apply the default value of the mask to the input
            else if(defaultValue!='') this.$el.set('value', defaultValue.mask(this.options) );

            this.$el.store('mask',this);

            // removes the maxlength attribute (it will be set again if you use the unset method)
            this.$el.erase(mlStr);

            // setting the input events
            /*this.$el.addEvents({
                'keydown'   : this.keydownEvent,
                'keypress'  : this.keypressEvent,
                'keyup'     : this.keyupEvent,
                'paste'     : this.pasteEvent
            });*/

            this.eventsToBind.each(function(evt){this.$el.addEvent(evt,this[evt+'Event']);}.bind(this));
        }
        return this;

    },

    remove : function(){
        var mask = this.$el.retrieve('mask');
        if(mask){
            var maxLength = this.$el.retrieve('mask').options.maxlength;
            if(maxLength != -1) this.$el.set('maxLength',maxLength);

            /*this.$el.removeEvent('keydown',this.keydownEvent)
                .removeEvent('keypress',this.keypressEvent)
                .removeEvent('keyup',this.keyupEvent)
                .removeEvent('paste',this.pasteEvent);*/

            this.eventsToBind.each(function(evt){this.$el.removeEvent(evt,this[evt+'Event']);}.bind(this));
        }
        return this;
    },

    _onMask : function(e,func){
        var o = {};
        e = new Event(e);
        // if the input is readonly it does nothing
        if( this.$el.get('readonly') ) return true;
        o.value = this.$el.get('value');
        o.range = this.$el.getRange();
        o.valueArray = o.value.split('');
        o[this.options.type] = true;
        return func.call(this,e,o);
    },

    _keydown : function(e,o){
        // lets say keypress at desktop == keydown at iphone (theres no keypress at iphone)
        this.ignore = this.globals.ignoreKeys.contains(e.code);
        if( this.ignore ){
            var rep = this.globals.keyRep[e.code];
            this.fireEvent('valid',[this.$el,rep?rep:'',e.code]);
        }
        return Browser.Platform.ipod ? this._keypress(e,o) : true;
    },

    _keyup : function(e,o){
        //9=TAB_KEY
        //this is a little bug, when you go to an input with tab key
        //it would remove the range selected by default, and that's not a desired behavior
        if(e.code==9 && (Browser.Engine.webkit || Browser.Engine.trident)) return true;
        return (!o.infinite) ? this._paste(e,o) : true;
    },

    _paste : function(e,o){
        var opt = this.options;
        // changes the signal at the data obj from the input
        if(o.reverse) this.__changeSignal(e,o);

        this.$el.set('value', o.valueArray.__mask(
            this.globals.rules,
            this.globals.fixedCharsReg,
            opt
        ));

        // this makes the caret stay at first position when
        // the user removes all values in an input and the plugin adds the default value to it (if it haves one).
        if( !o.reverse && opt.defaultValue.length && (o.range.start==o.range.end) )
            this.$el.setRange(o.range.start,o.range.end);

        //fix so ie's caret won't go to the end of the input value.
        if( (Browser.Engine.trident || Browser.Engine.webkit) && !o.reverse) this.$el.setRange(o.range.start,o.range.end);

        return true;
    },


    _keypress: function(e,o){

        if( this.ignore || e.control || e.meta || e.alt ) return true;

        // changes the signal at the data obj from the input
        if(o.reverse) this.__changeSignal(e,o);

        var c = String.fromCharCode(e.code),
            rangeStart = o.range.start,
            rawValue = o.value,
            maskArray = this.options.maskArray,
            opt = this.options;

        if(o.reverse){
                // the input value from the range start to the value start
            var valueStart = rawValue.substr(0,rangeStart),
                // the input value from the range end to the value end
                valueEnd = rawValue.substr(o.range.end,rawValue.length);

            rawValue = (valueStart+c+valueEnd);
            //necessary, if not decremented you will be able to input just the mask.length-1 if signal!=''
            //ex: mask:99,999.999.999 you will be able to input 99,999.999.99
            if( opt.signal && (rangeStart-opt.signal.length > 0 ) ) rangeStart -= opt.signal.length;
        }

        var valueArray = rawValue.replace(this.globals.fixedCharsRegG,'').split(''),
            // searches for fixed chars begining from the range start position, till it finds a non fixed
            extraPos = this.__extraPositionsTill(rangeStart,maskArray,this.globals.fixedCharsReg),
            rules = this.globals.rules;

        o.rsEp = rangeStart+extraPos;

        if( o.infinite ) o.rsEp = 0;

        // if the rule for this character doesnt exist (value.length is bigger than mask.length)
        if( !rules[maskArray[o.rsEp]] ){
            this.fireEvent('overflow',[this.$el,c,e.code]);
            return false;
        }
        // if the new character is not obeying the law... :P
        else if( !rules[maskArray[o.rsEp]].test( c ) ){
            this.fireEvent('invalid',[this.$el,c,e.code]);
            return false;
        }
        else
            this.fireEvent('valid',[this.$el,c,e.code]);

        this.$el.set('value', valueArray.__mask(
            rules,
            this.globals.fixedCharsReg,
            opt,
            extraPos
        ));

        return (o.reverse)?this._keypressReverse(e,o):(o.fixed)?this._keypressFixed(e,o):true;

    },

    _keypressFixed : function(e,o){
        if(o.range.start==o.range.end){
            // the 0 thing is cause theres a particular behavior i wasnt liking when you put a default
            // value on a fixed mask and you select the value from the input the range would go to the
            // end of the string when you enter a char. with this it will overwrite the first char wich is a better behavior.
            // opera fix, cant have range value bigger than value length, i think it loops thought the input value...
            if( (o.rsEp==0 && o.value.length==0) || o.rsEp < o.value.length )
                this.$el.setRange(o.rsEp,o.rsEp+1);
        }
        else
            this.$el.setRange(o.range.start,o.range.end);

        return true;
    },

    _keypressReverse : function(e,o){
        //fix for ie
        //this bug was pointed by Pedro Martins
        //it fixes a strange behavior that ie was having after a char was inputted in a text input that
        //had its content selected by any range
        if(Browser.Engine.trident && ( (o.rangeStart==0 && o.range.end==0) || o.rangeStart != o.range.end ) )
            this.$el.setRange(o.value.length);
        return false;
    },

    // changes the signal at the data obj from the input
    __changeSignal : function(e,o){
        if(this.options.signal!==false){
            var inputChar = (o.paste)?o.value.charAt(0):e.key;
            if( $defined(this.globals.signals[inputChar]) )
                this.options.signal = this.globals.signals[inputChar];
        }
    },

    // searches for fixed chars begining from the range start position, till it finds a non fixed
    __extraPositionsTill : function(rangeStart,maskArray,fixedCharsReg){
        var extraPos = 0;
        while( fixedCharsReg.test(maskArray[rangeStart]) ){
            rangeStart++;
            extraPos++;
        }
        return extraPos;
    }
});

Array.implement({

    // this function is totaly specific to be used with this plugin, youll never need it
    // it gets the array representing an unmasked string and masks it depending on the type of the mask
    __mask : function(rules,fixedCharsReg,o,extraPos){
        if(o.type == 'reverse') this.reverse();
        this.__removeInvalidChars(o.maskNonFixedChars,rules);
        if(o.defaultValue) this.__applyDefaultValue(o.defaultValue);
        this.__applyMask(o.maskArray,fixedCharsReg,extraPos);
        switch(o.type){
            case 'reverse':
                this.reverse();
                return (o.signal || '')+this.join('').substring(this.length-o.maskArray.length);
            case 'infinite':
                return this.join('');
            default:
                return this.join('').substring(0,o.maskArray.length);
        }
        // just because i hate warnings, but this code will never be executed
        return '';
    },

    // applyes the default value to the result string
    __applyDefaultValue : function(defaultValue){
        var defLen = defaultValue.length,thisLen = this.length,i;
        //removes the leading chars
        for(i=thisLen-1;i>=0;i--){
            if(this[i]==defaultValue.charAt(0)) this.pop();
            else break;
        }
        // apply the default value
        for(i=0;i<defLen;i++) if(!this[i])
            this[i] = defaultValue.charAt(i);

        return this;
    },

    // Removes values that doesnt match the mask from the valueArray
    // Returns the array without the invalid chars.
    __removeInvalidChars : function(maskNonFixedChars,rules){
        // removes invalid chars
        for(var i=0; i<this.length; i++){
            if( maskNonFixedChars.charAt(i)
                && rules[maskNonFixedChars.charAt(i)]
                && !rules[maskNonFixedChars.charAt(i)].test(this[i]) ){
                    this.splice(i,1);
                    i--;
            }
        }
        return this;
    },

    // Apply the current input mask to the valueArray and returns it.
    __applyMask : function(maskArray,fixedCharsReg,plus){
        plus = $pick(plus,0);
        // apply the current mask to the array of chars
        for(var i=0; i<this.length+plus; i++ ){
            if( maskArray[i] && fixedCharsReg.test(maskArray[i]) )
                this.splice(i,0,maskArray[i]);
        }
        return this;
    }

});

Element.implement({

    unmaskedVal : function(){
        return this.get('value').replace(meio.MaskGlobals.init().fixedCharsRegG,'');
    },

    // http://www.bazon.net/mishoo/articles.epl?art_id=1292
    setRange : function(start,end) {
        end = $pick(end,start);
        if (this.setSelectionRange) {
            this.setSelectionRange(start, end);
        } else {
            var range = this.createTextRange();
            range.collapse();
            range.moveStart('character', start);
            range.moveEnd('character', end - start);
            range.select();
        }
    },

    // adaptation from http://digitarald.de/project/autocompleter/
    getRange : function(){
        if (!Browser.Engine.trident) return {start: this.selectionStart, end: this.selectionEnd};
        var pos = {start: 0, end: 0},
            range = document.selection.createRange();
        pos.start = 0 - range.duplicate().moveStart('character', -100000);
        pos.end = pos.start + range.text.length;
        return pos;
    }
});

Element.Properties.mask = {
    // sets mask to this input and returns this input
    set : function(options){
        options = $pick(options,{});
        var mask = this.retrieve('mask');
        return this.store('mask' , mask ? mask.change(options) : new meio.Mask(this,options) );
    },
    // sets the mask and return the mask object
    get : function(options){
        this.set('mask',options);
        return this.retrieve('mask');
    },
    // removes the mask from this input but maintain the mask object stored at its hash
    erase : function(){
        var mask = this.retrieve('mask');
        if(mask) mask.remove();
        return this;
    }

};

String.implement({
    mask : function(options){
        var globals = meio.MaskGlobals.init(),o = {};
        switch( $type(options) ){
            case 'string':
                // then we see if it's a defined mask
                if(globals.masks[options]) $extend(o,globals.masks[options]);
                else o.mask = options;
                break;
            case 'object':
                $extend(o,options);
        }

        //insert signal if any
        if( (o.type=='reverse') && o.defaultValue ){
            var signals = globals.signals;
            // typeof signals[o.defaultValue.charAt(0)] != 'undefined'
            // thats the only way i found to not see warnings on firefox
            if( typeof signals[o.defaultValue.charAt(0)] != 'undefined' ){
                var maybeASignal = this.charAt(0);
                o.signal = options.signal = signals[maybeASignal] ? signals[maybeASignal] : signals[o.defaultValue.charAt(0)];
                o.defaultValue = options.defaultValue = o.defaultValue.substring(1);
            }
        }

        o.maskNonFixedChars = o.mask.replace(globals.fixedCharsRegG,'');
        o.maskArray = o.mask.split('');
        return this.split('').__mask(
            globals.rules,
            globals.fixedCharsReg,
            o
        );
    }
});

/**
 * Roar - Notifications
 *
 * Inspired by Growl
 *
 * @version     1.0.1
 *
 * @license     MIT-style license
 * @author      Harald Kirschner <mail [at] digitarald.de>
 * @copyright   Author
 */

var Roar = new Class({

    Implements: [Options, Events, Chain],

    options: {
        duration: 3000,
        position: 'upperLeft',
        container: null,
        bodyFx: null,
        itemFx: null,
        margin: {x: 10, y: 10},
        offset: 10,
        className: 'roar',
        onShow: $empty,
        onHide: $empty,
        onRender: $empty
    },

    initialize: function(options) {
        this.setOptions(options);
        this.items = [];
        this.container = $(this.options.container) || document;
    },

    alert: function(title, message, options) {
        var params = Array.link(arguments, {title: String.type, message: String.type, options: Object.type});
        var items = [new Element('h3', {'html': $pick(params.title, '')})];
        if (params.message) items.push(new Element('p', {'html': params.message}));
        return this.inject(items, params.options);
    },

    inject: function(elements, options) {
        if (!this.body) this.render();
        options = options || {};

        var offset = [-this.options.offset, 0];
        var last = this.items.getLast();
        if (last) {
            offset[0] = last.retrieve('roar:offset');
            offset[1] = offset[0] + last.offsetHeight + this.options.offset;
        }
        var to = {'opacity': 1};
        to[this.align.y] = offset;

        var item = new Element('div', {
            'class': this.options.className,
            'opacity': 0
        }).adopt(
            new Element('div', {
                'class': 'roar-bg',
                'opacity': 0.7
            }),
            elements
        );

        item.setStyle(this.align.x, 0).store('roar:offset', offset[1]).set('morph', $merge({
            unit: 'px',
            link: 'cancel',
            onStart: Chain.prototype.clearChain,
            transition: Fx.Transitions.Back.easeOut
        }, this.options.itemFx));

        var remove = this.remove.create({
            bind: this,
            arguments: [item],
            delay: 10
        });
        this.items.push(item.addEvent('click', remove));

        if (this.options.duration) {
            var over = false;
            var trigger = (function() {
                trigger = null;
                if (!over) remove();
            }).delay(this.options.duration);
            item.addEvents({
                mouseover: function() {
                    over = true;
                },
                mouseout: function() {
                    over = false;
                    if (!trigger) remove();
                }
            });
        }
        item.inject(this.body).morph(to);
        return this.fireEvent('onShow', [item, this.items.length]);
    },

    remove: function(item) {
        var index = this.items.indexOf(item);
        if (index == -1) return this;
        this.items.splice(index, 1);
        item.removeEvents();
        var to = {opacity: 0};
        to[this.align.y] = item.getStyle(this.align.y).toInt() - item.offsetHeight - this.options.offset;
        item.morph(to).get('morph').chain(item.destroy.bind(item));
        return this.fireEvent('onHide', [item, this.items.length]).callChain(item);
    },

    empty: function() {
        while (this.items.length) this.remove(this.items[0]);
        return this;
    },

    render: function() {
        this.position = this.options.position;
        if ($type(this.position) == 'string') {
            var position = {x: 'center', y: 'center'};
            this.align = {x: 'left', y: 'top'};
            if ((/left|west/i).test(this.position)) position.x = 'left';
            else if ((/right|east/i).test(this.position)) this.align.x = position.x = 'right';
            if ((/upper|top|north/i).test(this.position)) position.y = 'top';
            else if ((/bottom|lower|south/i).test(this.position)) this.align.y = position.y = 'bottom';
            this.position = position;
        }
        this.body = new Element('div', {'class': 'roar-body'}).inject(document.body);
        if (Browser.Engine.trident4) this.body.addClass('roar-body-ugly');
        this.moveTo = this.body.setStyles.bind(this.body);
        this.reposition();
        if (this.options.bodyFx) {
            var morph = new Fx.Morph(this.body, $merge({
                unit: 'px',
                chain: 'cancel',
                transition: Fx.Transitions.Circ.easeOut
            }, this.options.bodyFx));
            this.moveTo = morph.start.bind(morph);
        }
        var repos = this.reposition.bind(this);
        window.addEvents({
            scroll: repos,
            resize: repos
        });
        this.fireEvent('onRender', this.body);
    },

    reposition: function() {
        var max = document.getCoordinates(), scroll = document.getScroll(), margin = this.options.margin;
        max.left += scroll.x;
        max.right += scroll.x;
        max.top += scroll.y;
        max.bottom += scroll.y;
        var rel = ($type(this.container) == 'element') ? this.container.getCoordinates() : max;
        this.moveTo({
            left: (this.position.x == 'right')
                ? (Math.min(rel.right, max.right) - margin.x)
                : (Math.max(rel.left, max.left) + margin.x),
            top: (this.position.y == 'bottom')
                ? (Math.min(rel.bottom, max.bottom) - margin.y)
                : (Math.max(rel.top, max.top) + margin.y)
        });
    }

});

/**
 * Swiff.Uploader - Flash FileReference Control
 *
 * @version     3.0
 *
 * @license     MIT License
 *
 * @author      Harald Kirschner <http://digitarald.de>
 * @author      Valerio Proietti, <http://mad4milk.net>
 * @copyright   Authors
 */

Swiff.Uploader = new Class({

    Extends: Swiff,

    Implements: Events,

    options: {
        path: 'Swiff.Uploader.swf',

        target: null,
        zIndex: 9999,

        height: 30,
        width: 100,
        callBacks: null,
        params: {
            wMode: 'opaque',
            menu: 'false',
            allowScriptAccess: 'always'
        },

        typeFilter: null,
        multiple: true,
        queued: true,
        verbose: false,

        url: null,
        method: null,
        data: null,
        mergeData: true,
        fieldName: null,

        fileSizeMin: 1,
        fileSizeMax: null, // Official limit is 100 MB for FileReference, but I tested up to 2Gb!
        allowDuplicates: false,
        timeLimit: (Browser.Platform.linux) ? 0 : 30,

        buttonImage: null,
        policyFile: null,

        fileListMax: 0,
        fileListSizeMax: 0,

        instantStart: false,
        appendCookieData: false,

        fileClass: null
        /*
        onLoad: $empty,
        onFail: $empty,
        onStart: $empty,
        onQueue: $empty,
        onComplete: $empty,
        onBrowse: $empty,
        onDisabledBrowse: $empty,
        onCancel: $empty,
        onSelect: $empty,
        onSelectSuccess: $empty,
        onSelectFail: $empty,

        onButtonEnter: $empty,
        onButtonLeave: $empty,
        onButtonDown: $empty,
        onButtonDisable: $empty,

        onFileStart: $empty,
        onFileStop: $empty,
        onFileRequeue: $empty,
        onFileOpen: $empty,
        onFileProgress: $empty,
        onFileComplete: $empty,
        onFileRemove: $empty,

        onBeforeStart: $empty,
        onBeforeStop: $empty,
        onBeforeRemove: $empty
        */
    },

    initialize: function(options) {
        // protected events to control the class, added
        // before setting options (which adds own events)
        this.addEvent('load', this.initializeSwiff, true)
            .addEvent('select', this.processFiles, true)
            .addEvent('complete', this.update, true)
            .addEvent('fileRemove', function(file) {this.fileList.erase(file);}.bind(this), true);

        this.setOptions(options);

        // callbacks are no longer in the options, every callback
        // is fired as event, this is just compat
        if (this.options.callBacks) {
            Hash.each(this.options.callBacks, function(fn, name) {
                this.addEvent(name, fn);
            }, this);
        }

        this.options.callBacks = {
            fireCallback: this.fireCallback.bind(this)
        };

        var path = this.options.path;
        if (!path.contains('?')) path += '?noCache=' + $time(); // cache in IE

        // container options for Swiff class
        this.options.container = this.box = new Element('span', {'class': 'swiff-uploader-box'}).inject($(this.options.container) || document.body);

        // target
        this.target = $(this.options.target);
        if (this.target) {
            var scroll = window.getScroll();
            this.box.setStyles({
                position: 'absolute',
                visibility: 'visible',
                zIndex: this.options.zIndex,
                overflow: 'hidden',
                height: 1, width: 1,
                top: scroll.y, left: scroll.x
            });

            // we force wMode to transparent for the overlay effect
            this.parent(path, {
                params: {
                    wMode: 'transparent'
                },
                height: '100%',
                width: '100%'
            });

            this.target.addEvent('mouseenter', this.reposition.bind(this, []));

            // button interactions, relayed to to the target
            this.addEvents({
                buttonEnter: this.targetRelay.bind(this, ['mouseenter']),
                buttonLeave: this.targetRelay.bind(this, ['mouseleave']),
                buttonDown: this.targetRelay.bind(this, ['mousedown']),
                buttonDisable: this.targetRelay.bind(this, ['disable'])
            });

            this.reposition();
            window.addEvent('resize', this.reposition.bind(this, []));
        } else {this.parent(path);}

        this.inject(this.box);

        this.fileList = [];

        this.size = this.uploading = this.bytesLoaded = this.percentLoaded = 0;

        if (Browser.Plugins.Flash.version < 9) {
            this.fireEvent('fail', ['flash']);
        } else {
            this.verifyLoad.delay(1000, this);
        }
    },

    verifyLoad: function() {
        if (this.loaded) return;
        if (!this.object.parentNode) {
            this.fireEvent('fail', ['disabled']);
        } else if (this.object.style.display == 'none') {
            this.fireEvent('fail', ['hidden']);
        } else if (!this.object.offsetWidth) {
            this.fireEvent('fail', ['empty']);
        }
    },

    fireCallback: function(name, args) {
        // file* callbacks are relayed to the specific file
        if (name.substr(0, 4) == 'file') {
            // updated queue data is the second argument
            if (args.length > 1) this.update(args[1]);
            var data = args[0];

            var file = this.findFile(data.id);
            this.fireEvent(name, file || data, 5);
            if (file) {
                var fire = name.replace(/^file([A-Z])/, function($0, $1) {
                    return $1.toLowerCase();
                });
                file.update(data).fireEvent(fire, [data], 10);
            }
        } else {
            this.fireEvent(name, args, 5);
        }
    },

    update: function(data) {
        // the data is saved right to the instance
        $extend(this, data);
        this.fireEvent('queue', [this], 10);
        return this;
    },

    findFile: function(id) {
        for (var i = 0; i < this.fileList.length; i++) {
            if (this.fileList[i].id == id) return this.fileList[i];
        }
        return null;
    },

    initializeSwiff: function() {
        // extracted options for the swf
        this.remote('initialize', {
            width: this.options.width,
            height: this.options.height,
            typeFilter: this.options.typeFilter,
            multiple: this.options.multiple,
            queued: this.options.queued,
            url: this.options.url,
            method: this.options.method,
            data: this.options.data,
            mergeData: this.options.mergeData,
            fieldName: this.options.fieldName,
            verbose: this.options.verbose,
            fileSizeMin: this.options.fileSizeMin,
            fileSizeMax: this.options.fileSizeMax,
            allowDuplicates: this.options.allowDuplicates,
            timeLimit: this.options.timeLimit,
            buttonImage: this.options.buttonImage,
            policyFile: this.options.policyFile
        });

        this.loaded = true;

        this.appendCookieData();
    },

    targetRelay: function(name) {
        if (this.target) this.target.fireEvent(name);
    },

    reposition: function(coords) {
        // update coordinates, manual or automatically
        coords = coords || (this.target && this.target.offsetHeight)
            ? this.target.getCoordinates(this.box.getOffsetParent())
            : {top: window.getScrollTop(), left: 0, width: 40, height: 40}
        this.box.setStyles(coords);
        this.fireEvent('reposition', [coords, this.box, this.target]);
    },

    setOptions: function(options) {
        if (options) {
            if (options.url) options.url = Swiff.Uploader.qualifyPath(options.url);
            if (options.buttonImage) options.buttonImage = Swiff.Uploader.qualifyPath(options.buttonImage);
            this.parent(options);
            if (this.loaded) this.remote('setOptions', options);
        }
        return this;
    },

    setEnabled: function(status) {
        this.remote('setEnabled', status);
    },

    start: function() {
        this.fireEvent('beforeStart');
        this.remote('start');
    },

    stop: function() {
        this.fireEvent('beforeStop');
        this.remote('stop');
    },

    remove: function() {
        this.fireEvent('beforeRemove');
        this.remote('remove');
    },

    fileStart: function(file) {
        this.remote('fileStart', file.id);
    },

    fileStop: function(file) {
        this.remote('fileStop', file.id);
    },

    fileRemove: function(file) {
        this.remote('fileRemove', file.id);
    },

    fileRequeue: function(file) {
        this.remote('fileRequeue', file.id);
    },

    appendCookieData: function() {
        var append = this.options.appendCookieData;
        if (!append) return;

        var hash = {};
        document.cookie.split(/;\s*/).each(function(cookie) {
            cookie = cookie.split('=');
            if (cookie.length == 2) {
                hash[decodeURIComponent(cookie[0])] = decodeURIComponent(cookie[1]);
            }
        });

        var data = this.options.data || {};
        if ($type(append) == 'string') data[append] = hash;
        else $extend(data, hash);

        this.setOptions({data: data});
    },

    processFiles: function(successraw, failraw, queue) {
        var cls = this.options.fileClass || Swiff.Uploader.File;

        var fail = [], success = [];

        if (successraw) {
            successraw.each(function(data) {
                var ret = new cls(this, data);
                if (!ret.validate()) {
                    ret.remove.delay(10, ret);
                    fail.push(ret);
                } else {
                    this.size += data.size;
                    this.fileList.push(ret);
                    success.push(ret);
                    ret.render();
                }
            }, this);

            this.fireEvent('selectSuccess', [success], 10);
        }

        if (failraw || fail.length) {
            fail.extend((failraw) ? failraw.map(function(data) {
                return new cls(this, data);
            }, this) : []).each(function(file) {file.invalidate().render();});

            this.fireEvent('selectFail', [fail], 10);
        }

        this.update(queue);

        if (this.options.instantStart && success.length) this.start();
    }

});

$extend(Swiff.Uploader, {

    STATUS_QUEUED: 0,
    STATUS_RUNNING: 1,
    STATUS_ERROR: 2,
    STATUS_COMPLETE: 3,
    STATUS_STOPPED: 4,

    log: function() {
        if (window.console && console.info) console.info.apply(console, arguments);
    },

    unitLabels: {
        b: [{min: 1, unit: 'B'}, {min: 1024, unit: 'kB'}, {min: 1048576, unit: 'MB'}, {min: 1073741824, unit: 'GB'}],
        s: [{min: 1, unit: 's'}, {min: 60, unit: 'm'}, {min: 3600, unit: 'h'}, {min: 86400, unit: 'd'}]
    },

    formatUnit: function(base, type, join) {
        var labels = Swiff.Uploader.unitLabels[(type == 'bps') ? 'b' : type];
        var append = (type == 'bps') ? '/s' : '';
        var i, l = labels.length, value;

        if (base < 1) return '0 ' + labels[0].unit + append;

        if (type == 's') {
            var units = [];

            for (i = l - 1; i >= 0; i--) {
                value = Math.floor(base / labels[i].min);
                if (value) {
                    units.push(value + ' ' + labels[i].unit);
                    base -= value * labels[i].min;
                    if (!base) break;
                }
            }

            return (join === false) ? units : units.join(join || ', ');
        }

        for (i = l - 1; i >= 0; i--) {
            value = labels[i].min;
            if (base >= value) break;
        }

        return (base / value).toFixed(1) + ' ' + labels[i].unit + append;
    }

});

Swiff.Uploader.qualifyPath = (function() {

    var anchor;

    return function(path) {
        (anchor || (anchor = new Element('a'))).href = path;
        return anchor.href;
    };

})();

Swiff.Uploader.File = new Class({

    Implements: Events,

    initialize: function(base, data) {
        this.base = base;
        this.update(data);
    },

    update: function(data) {
        return $extend(this, data);
    },

    validate: function() {
        var options = this.base.options;

        if (options.fileListMax && this.base.fileList.length >= options.fileListMax) {
            this.validationError = 'fileListMax';
            return false;
        }

        if (options.fileListSizeMax && (this.base.size + this.size) > options.fileListSizeMax) {
            this.validationError = 'fileListSizeMax';
            return false;
        }

        return true;
    },

    invalidate: function() {
        this.invalid = true;
        this.base.fireEvent('fileInvalid', this, 10);
        return this.fireEvent('invalid', this, 10);
    },

    render: function() {
        return this;
    },

    setOptions: function(options) {
        if (options) {
            if (options.url) options.url = Swiff.Uploader.qualifyPath(options.url);
            this.base.remote('fileSetOptions', this.id, options);
            this.options = $merge(this.options, options);
        }
        return this;
    },

    start: function() {
        this.base.fileStart(this);
        return this;
    },

    stop: function() {
        this.base.fileStop(this);
        return this;
    },

    remove: function() {
        this.base.fileRemove(this);
        return this;
    },

    requeue: function() {this.base.fileRequeue(this);}

});

/**
 * Fx.ProgressBar
 *
 * @version     1.1
 *
 * @license     MIT License
 *
 * @author      Harald Kirschner <mail [at] digitarald [dot] de>
 * @copyright   Authors
 */

Fx.ProgressBar = new Class({

    Extends: Fx,

    options: {
        text: null,
        url: null,
        transition: Fx.Transitions.Circ.easeOut,
        fit: true,
        link: 'cancel'
    },

    initialize: function(element, options) {
        this.element = $(element);
        this.parent(options);

        var url = this.options.url;
        if (url) {
            this.element.setStyles({
                'background-image': 'url(' + url + ')',
                'background-repeat': 'no-repeat'
            });
        }

        if (this.options.fit) {
            url = url || this.element.getStyle('background-image').replace(/^url\(["']?|["']?\)$/g, '');
            if (url) {
                var fill = new Image();
                fill.onload = function() {
                    this.fill = fill.width;
                    fill = fill.onload = null;
                    this.set(this.now || 0);
                }.bind(this);
                fill.src = url;
                if (!this.fill && fill.width) fill.onload();
            }
        } else {this.set(0);}
    },

    start: function(to, total) {
        return this.parent(this.now, (arguments.length == 1) ? to.limit(0, 100) : to / total * 100);
    },

    set: function(to) {
        this.now = to;
        var css = (this.fill)
            ? (((this.fill / -2) + (to / 100) * (this.element.width || 1) || 0).round() + 'px')
            : ((100 - to) + '%');

        this.element.setStyle('backgroundPosition', css + ' 0px').title = Math.round(to) + '%';

        var text = $(this.options.text);
        if (text) text.set('text', Math.round(to) + '%');

        return this;
    }

});

/**
 * Observer - Observe formelements for changes
 *
 * - Additional code from clientside.cnet.com
 *
 * @version     1.1
 *
 * @license     MIT-style license
 * @author      Harald Kirschner <mail [at] digitarald.de>
 * @copyright   Author
 */
var Observer = new Class({

    Implements: [Options, Events],

    options: {
        periodical: false,
        delay: 1000
    },

    initialize: function(el, onFired, options){
        this.element = $(el) || $$(el);
        this.addEvent('onFired', onFired);
        this.setOptions(options);
        this.bound = this.changed.bind(this);
        this.resume();
    },

    changed: function() {
        var value = this.element.get('value');
        if ($equals(this.value, value)) return;
        this.clear();
        this.value = value;
        this.timeout = this.onFired.delay(this.options.delay, this);
    },

    setValue: function(value) {
        this.value = value;
        this.element.set('value', value);
        return this.clear();
    },

    onFired: function() {
        this.fireEvent('onFired', [this.value, this.element]);
    },

    clear: function() {
        $clear(this.timeout || null);
        return this;
    },

    pause: function(){
        if (this.timer) $clear(this.timer);
        else this.element.removeEvent('keyup', this.bound);
        return this.clear();
    },

    resume: function(){
        this.value = this.element.get('value');
        if (this.options.periodical) this.timer = this.changed.periodical(this.options.periodical, this);
        else this.element.addEvent('keyup', this.bound);
        return this;
    }

});

var $equals = function(obj1, obj2) {
    return (obj1 == obj2 || JSON.encode(obj1) == JSON.encode(obj2));
};

/**
 * Autocompleter
 *
 * http://digitarald.de/project/autocompleter/
 *
 * @version     1.1.2
 *
 * @license     MIT-style license
 * @author      Harald Kirschner <mail [at] digitarald.de>
 * @copyright   Author
 */

var Autocompleter = new Class({

    Implements: [Options, Events],

    options: {/*
        onOver: $empty,
        onSelect: $empty,
        onSelection: $empty,
        onShow: $empty,
        onHide: $empty,
        onBlur: $empty,
        onFocus: $empty,*/
        minLength: 1,
        markQuery: true,
        width: 'inherit',
        maxChoices: 10,
        injectChoice: null,
        customChoices: null,
        emptyChoices: null,
        visibleChoices: true,
        className: 'autocompleter-choices',
        zIndex: 42,
        delay: 100,
        observerOptions: {},
        fxOptions: {},

        autoSubmit: false,
        overflow: false,
        overflowMargin: 25,
        selectFirst: false,
        filter: null,
        filterCase: false,
        filterSubset: false,
        forceSelect: false,
        selectMode: true,
        choicesMatch: null,

        multiple: false,
        separator: ', ',
        separatorSplit: /\s*[,;]\s*/,
        autoTrim: false,
        allowDupes: false,

        cache: true,
        relative: false
    },

    initialize: function(element, options) {
        this.element = $(element);
        this.setOptions(options);
        this.build();
        this.observer = new Observer(this.element, this.prefetch.bind(this), $merge({
            'delay': this.options.delay
        }, this.options.observerOptions));
        this.queryValue = null;
        if (this.options.filter) this.filter = this.options.filter.bind(this);
        var mode = this.options.selectMode;
        this.typeAhead = (mode == 'type-ahead');
        this.selectMode = (mode === true) ? 'selection' : mode;
        this.cached = [];
    },

    /**
     * build - Initialize DOM
     *
     * Builds the html structure for choices and appends the events to the element.
     * Override this function to modify the html generation.
     */
    build: function() {
        if ($(this.options.customChoices)) {
            this.choices = this.options.customChoices;
        } else {
            this.choices = new Element('ul', {
                'class': this.options.className,
                'styles': {
                    'zIndex': this.options.zIndex
                }
            }).inject(document.body);
            this.relative = false;
            if (this.options.relative) {
                this.choices.inject(this.element, 'after');
                this.relative = this.element.getOffsetParent();
            }
            this.fix = new OverlayFix(this.choices);
        }
        if (!this.options.separator.test(this.options.separatorSplit)) {
            this.options.separatorSplit = this.options.separator;
        }
        this.fx = (!this.options.fxOptions) ? null : new Fx.Tween(this.choices, $merge({
            'property': 'opacity',
            'link': 'cancel',
            'duration': 200
        }, this.options.fxOptions)).addEvent('onStart', Chain.prototype.clearChain).set(0);
        this.element.setProperty('autocomplete', 'off')
            .addEvent((Browser.Engine.trident || Browser.Engine.webkit) ? 'keydown' : 'keypress', this.onCommand.bind(this))
            .addEvent('click', this.onCommand.bind(this, [false]))
            .addEvent('focus', this.toggleFocus.create({bind: this, arguments: true, delay: 100}))
            .addEvent('blur', this.toggleFocus.create({bind: this, arguments: false, delay: 100}));
    },

    destroy: function() {
        if (this.fix) this.fix.destroy();
        this.choices = this.selected = this.choices.destroy();
    },

    toggleFocus: function(state) {
        this.focussed = state;
        if (!state) this.hideChoices(true);
        this.fireEvent((state) ? 'onFocus' : 'onBlur', [this.element]);
    },

    onCommand: function(e) {
        if (!e && this.focussed) return this.prefetch();
        if (e && e.key && !e.shift) {
            switch (e.key) {
                case 'enter':
                    if (this.element.value != this.opted) return true;
                    if (this.selected && this.visible) {
                        this.choiceSelect(this.selected);
                        return !!(this.options.autoSubmit);
                    }
                    break;
                case 'up': case 'down':
                    if (!this.prefetch() && this.queryValue !== null) {
                        var up = (e.key == 'up');
                        this.choiceOver((this.selected || this.choices)[
                            (this.selected) ? ((up) ? 'getPrevious' : 'getNext') : ((up) ? 'getLast' : 'getFirst')
                        ](this.options.choicesMatch), true);
                    }
                    return false;
                case 'esc': case 'tab':
                    this.hideChoices(true);
                    break;
            }
        }
        return true;
    },

    setSelection: function(finish) {
        var input = this.selected.inputValue, value = input;
        var start = this.queryValue.length, end = input.length;
        if (input.substr(0, start).toLowerCase() != this.queryValue.toLowerCase()) start = 0;
        if (this.options.multiple) {
            var split = this.options.separatorSplit;
            value = this.element.value;
            start += this.queryIndex;
            end += this.queryIndex;
            var old = value.substr(this.queryIndex).split(split, 1)[0];
            value = value.substr(0, this.queryIndex) + input + value.substr(this.queryIndex + old.length);
            if (finish) {
                var tokens = value.split(this.options.separatorSplit).filter(function(entry) {
                    return this.test(entry);
                }, /[^\s,]+/);
                if (!this.options.allowDupes) tokens = [].combine(tokens);
                var sep = this.options.separator;
                value = tokens.join(sep) + sep;
                end = value.length;
            }
        }
        this.observer.setValue(value);
        this.opted = value;
        if (finish || this.selectMode == 'pick') start = end;
        this.element.selectRange(start, end);
        this.fireEvent('onSelection', [this.element, this.selected, value, input]);
    },

    showChoices: function() {
        var match = this.options.choicesMatch, first = this.choices.getFirst(match);
        this.selected = this.selectedValue = null;
        if (this.fix) {
            var pos = this.element.getCoordinates(this.relative), width = this.options.width || 'auto';
            this.choices.setStyles({
                'left': pos.left,
                'top': pos.bottom,
                'width': (width === true || width == 'inherit') ? pos.width : width
            });
        }
        if (!first) return;
        if (!this.visible) {
            this.visible = true;
            this.choices.setStyle('display', '');
            if (this.fx) this.fx.start(1);
            this.fireEvent('onShow', [this.element, this.choices]);
        }
        if (this.options.selectFirst || this.typeAhead || first.inputValue == this.queryValue) this.choiceOver(first, this.typeAhead);
        var items = this.choices.getChildren(match), max = this.options.maxChoices;
        var styles = {'overflowY': 'hidden', 'height': ''};
        this.overflown = false;
        if (items.length > max) {
            var item = items[max - 1];
            styles.overflowY = 'scroll';
            styles.height = item.getCoordinates(this.choices).bottom;
            this.overflown = true;
        };
        this.choices.setStyles(styles);
        this.fix.show();
        if (this.options.visibleChoices) {
            var scroll = document.getScroll(),
            size = document.getSize(),
            coords = this.choices.getCoordinates();
            if (coords.right > scroll.x + size.x) scroll.x = coords.right - size.x;
            if (coords.bottom > scroll.y + size.y) scroll.y = coords.bottom - size.y;
            window.scrollTo(Math.min(scroll.x, coords.left), Math.min(scroll.y, coords.top));
        }
    },

    hideChoices: function(clear) {
        if (clear) {
            var value = this.element.value;
            if (this.options.forceSelect) value = this.opted;
            if (this.options.autoTrim) {
                value = value.split(this.options.separatorSplit).filter($arguments(0)).join(this.options.separator);
            }
            this.observer.setValue(value);
        }
        if (!this.visible) return;
        this.visible = false;
        if (this.selected) this.selected.removeClass('autocompleter-selected');
        this.observer.clear();
        var hide = function(){
            this.choices.setStyle('display', 'none');
            this.fix.hide();
        }.bind(this);
        if (this.fx) this.fx.start(0).chain(hide);
        else hide();
        this.fireEvent('onHide', [this.element, this.choices]);
    },

    prefetch: function() {
        var value = this.element.value, query = value;
        if (this.options.multiple) {
            var split = this.options.separatorSplit;
            var values = value.split(split);
            var index = this.element.getSelectedRange().start;
            var toIndex = value.substr(0, index).split(split);
            var last = toIndex.length - 1;
            index -= toIndex[last].length;
            query = values[last];
        }
        if (query.length < this.options.minLength) {this.hideChoices();} else {
            if (query === this.queryValue || (this.visible && query == this.selectedValue)) {
                if (this.visible) return false;
                this.showChoices();
            } else {
                this.queryValue = query;
                this.queryIndex = index;
                if (!this.fetchCached()) this.query();
            }
        }
        return true;
    },

    fetchCached: function() {
        return false;
        if (!this.options.cache
            || !this.cached
            || !this.cached.length
            || this.cached.length >= this.options.maxChoices
            || this.queryValue) return false;
        this.update(this.filter(this.cached));
        return true;
    },

    update: function(tokens) {
        this.choices.empty();
        this.cached = tokens;
        var type = tokens && $type(tokens);
        if (!type || (type == 'array' && !tokens.length) || (type == 'hash' && !tokens.getLength())) {
            (this.options.emptyChoices || this.hideChoices).call(this);
        } else {
            if (this.options.maxChoices < tokens.length && !this.options.overflow) tokens.length = this.options.maxChoices;
            tokens.each(this.options.injectChoice || function(token){
                var choice = new Element('li', {'html': this.markQueryValue(token)});
                choice.inputValue = token;
                this.addChoiceEvents(choice).inject(this.choices);
            }, this);
            this.showChoices();
        }
    },

    choiceOver: function(choice, selection) {
        if (!choice || choice == this.selected) return;
        if (this.selected) this.selected.removeClass('autocompleter-selected');
        this.selected = choice.addClass('autocompleter-selected');
        this.fireEvent('onSelect', [this.element, this.selected, selection]);
        if (!this.selectMode) this.opted = this.element.value;
        if (!selection) return;
        this.selectedValue = this.selected.inputValue;
        if (this.overflown) {
            var coords = this.selected.getCoordinates(this.choices), margin = this.options.overflowMargin,
                top = this.choices.scrollTop, height = this.choices.offsetHeight, bottom = top + height;
            if (coords.top - margin < top && top) this.choices.scrollTop = Math.max(coords.top - margin, 0);
            else if (coords.bottom + margin > bottom) this.choices.scrollTop = Math.min(coords.bottom - height + margin, bottom);
        }
        if (this.selectMode) this.setSelection();
    },

    choiceSelect: function(choice) {
        if (choice) this.choiceOver(choice);
        this.setSelection(true);
        this.queryValue = false;
        this.hideChoices();
    },

    filter: function(tokens) {
        return (tokens || this.tokens).filter(function(token) {
            return this.test(token);
        }, new RegExp(((this.options.filterSubset) ? '' : '^') + this.queryValue.escapeRegExp(), (this.options.filterCase) ? '' : 'i'));
    },

    /**
     * markQueryValue
     *
     * Marks the queried word in the given string with <span class="autocompleter-queried">*</span>
     * Call this i.e. from your custom parseChoices, same for addChoiceEvents
     *
     * @param       {String} Text
     * @return      {String} Text
     */
    markQueryValue: function(str) {
        /*
        return (!this.options.markQuery || !this.queryValue) ? str
            : str.replace(new RegExp('(' + ((this.options.filterSubset) ? '' : '^') + this.queryValue.escapeRegExp() + ')', (this.options.filterCase) ? '' : 'i'), '<span class="autocompleter-queried">$1</span>');
        */
        var reg = new RegExp("(" + this.queryValue + ")", "i");
        str = str.replace(reg, '<span class="autocompleter-queried">$1</span>');

        return str;
    },

    /**
     * addChoiceEvents
     *
     * Appends the needed event handlers for a choice-entry to the given element.
     *
     * @param       {Element} Choice entry
     * @return      {Element} Choice entry
     */
    addChoiceEvents: function(el) {
        return el.addEvents({
            'mouseover': this.choiceOver.bind(this, [el]),
            'click': this.choiceSelect.bind(this, [el])
        });
    }
});

var OverlayFix = new Class({

    initialize: function(el) {
        if (Browser.Engine.trident) {
            this.element = $(el);
            this.relative = this.element.getOffsetParent();
            this.fix = new Element('iframe', {
                'frameborder': '0',
                'scrolling': 'no',
                'src': 'javascript:false;',
                'styles': {
                    'position': 'absolute',
                    'border': 'none',
                    'display': 'none',
                    'filter': 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)'
                }
            }).inject(this.element, 'after');
        }
    },

    show: function() {
        if (this.fix) {
            var coords = this.element.getCoordinates(this.relative);
            delete coords.right;
            delete coords.bottom;
            this.fix.setStyles($extend(coords, {
                'display': '',
                'zIndex': (this.element.getStyle('zIndex') || 1) - 1
            }));
        }
        return this;
    },

    hide: function() {
        if (this.fix) this.fix.setStyle('display', 'none');
        return this;
    },

    destroy: function() {
        if (this.fix) this.fix = this.fix.destroy();
    }

});

Element.implement({

    getSelectedRange: function() {
        if (!Browser.Engine.trident) return {start: this.selectionStart, end: this.selectionEnd};
        var pos = {start: 0, end: 0};
        var range = this.getDocument().selection.createRange();
        if (!range || range.parentElement() != this) return pos;
        var dup = range.duplicate();
        if (this.type == 'text') {
            pos.start = 0 - dup.moveStart('character', -100000);
            pos.end = pos.start + range.text.length;
        } else {
            var value = this.value;
            var offset = value.length - value.match(/[\n\r]*$/)[0].length;
            dup.moveToElementText(this);
            dup.setEndPoint('StartToEnd', range);
            pos.end = offset - dup.text.length;
            dup.setEndPoint('StartToStart', range);
            pos.start = offset - dup.text.length;
        }
        return pos;
    },

    selectRange: function(start, end) {
        if (Browser.Engine.trident) {
            var diff = this.value.substr(start, end - start).replace(/\r/g, '').length;
            start = this.value.substr(0, start).replace(/\r/g, '').length;
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', start + diff);
            range.moveStart('character', start);
            range.select();
        } else {
            this.focus();
            this.setSelectionRange(start, end);
        }
        return this;
    }

});

/* compatibility */

Autocompleter.Base = Autocompleter;

/**
 * Autocompleter.Request
 *
 * http://digitarald.de/project/autocompleter/
 *
 * @version     1.1.2
 *
 * @license     MIT-style license
 * @author      Harald Kirschner <mail [at] digitarald.de>
 * @copyright   Author
 */

Autocompleter.Request = new Class({

    Extends: Autocompleter,

    options: {/*
        indicator: null,
        indicatorClass: null,
        onRequest: $empty,
        onComplete: $empty,*/
        postData: {},
        ajaxOptions: {},
        postVar: 'value'

    },

    query: function(){
        var data = $unlink(this.options.postData) || {};
        data[this.options.postVar] = this.queryValue;
        var indicator = $(this.options.indicator);
        if (indicator) indicator.setStyle('display', '');
        var cls = this.options.indicatorClass;
        if (cls) this.element.addClass(cls);
        this.fireEvent('onRequest', [this.element, this.request, data, this.queryValue]);
        this.request.send({'data': data});
    },

    /**
     * queryResponse - abstract
     *
     * Inherated classes have to extend this function and use this.parent()
     */
    queryResponse: function() {
        var indicator = $(this.options.indicator);
        if (indicator) indicator.setStyle('display', 'none');
        var cls = this.options.indicatorClass;
        if (cls) this.element.removeClass(cls);
        return this.fireEvent('onComplete', [this.element, this.request]);
    }

});

Autocompleter.Request.JSON = new Class({

    Extends: Autocompleter.Request,

    initialize: function(el, url, options) {
        this.parent(el, options);
        this.request = new Request.JSON($merge({
            'url': url,
            'link': 'cancel'
        }, this.options.ajaxOptions)).addEvent('onComplete', this.queryResponse.bind(this));
    },

    queryResponse: function(response) {
        this.parent();
        this.update(response);
    }

});

Autocompleter.Request.HTML = new Class({

    Extends: Autocompleter.Request,

    initialize: function(el, url, options) {
        this.parent(el, options);
        this.request = new Request.HTML($merge({
            'url': url,
            'link': 'cancel',
            'update': this.choices
        }, this.options.ajaxOptions)).addEvent('onComplete', this.queryResponse.bind(this));
    },

    queryResponse: function(tree, elements) {
        this.parent();
        if (!elements || !elements.length) {this.hideChoices();} else {
            this.choices.getChildren(this.options.choicesMatch).each(this.options.injectChoice || function(choice) {
                var value = choice.innerHTML;
                choice.inputValue = value;
                this.addChoiceEvents(choice.set('html', this.markQueryValue(value)));
            }, this);
            this.showChoices();
        }

    }

});

/* compatibility */

Autocompleter.Ajax = {
    Base: Autocompleter.Request,
    Json: Autocompleter.Request.JSON,
    Xhtml: Autocompleter.Request.HTML
};

MooTools.lang.set('en-US', 'watchlist', {
    add_bill_error: 'Oops, some thing went wrong! Please try again.'
});

MooTools.lang.set('ESP', 'watchlist', {
    add_bill_error: '¡Uy, algo salió mal! Por favor, inténtelo de nuevo.'
});

var com = {};
com.tuitive = {};
com.californiavotes = {};

var AjaxCover = {};

window.addEvent('domready', function() {
    AjaxCover = new com.tuitive.AjaxCover({backgroundColor: '#ffffff'});
    new com.tuitive.Pages();

    $$("a.addbill").addEvent('click', function(e) {

        // add progress indicator
        $('progress_msg').set('text', '').addClass('inProgress');

        CV.Watchlist.addBill(e);
        return false;
    });

    $$("a.addlegislator").addEvent('click', function(e) {

        // add progress indicator
        $('progress_msg').set('text', '').addClass('inProgress');

        CV.Watchlist.addLegislator(e);
        return false;
    });

    $$("a.addtopic").addEvent('click', function(e) {

        // add progress indicator
        $('topics_progress_msg').set('text', '').addClass('inProgress');

        CV.Watchlist.addTopic(e);
        return false;
    });

    $$("a.deletebill").addEvent('click', function(e) {
        CV.Watchlist.deleteBill(e);

        // add progress indicator
        var select = 'a#'+ e.target.get('id');
        $$(select)[0].addClass('inProgress');

        return false;
    });

    $$("a.deletelegislator").addEvent('click', function(e) {

        // add progress indicator
        var select = 'a#'+ e.target.get('id');
        $$(select)[0].addClass('inProgress');

        CV.Watchlist.deleteLegislator(e);

        return false;
    });

    $$("a.deletetopic").addEvent('click', function(e) {
        CV.Watchlist.deleteTopic(e);

        // add progress indicator
        var select = 'a#'+ e.target.get('id');
        $$(select)[0].addClass('inProgress');

        return false;
    });

    $$("input#searchBillsBtn").addEvent('click', function(e) {
        CV.Watchlist.searchBills(e);
        return false;
    });

    $$("input#searchLegisBtn").addEvent('click', function(e) {
        CV.Watchlist.searchLegislators(e);
        return false;
    });

    $$("div.noti_freq_menu").addEvent('mouseleave', function(e) {this.hide();});

    $$("a.legis_dropdown").addEvent('click', function(e) {

        // hide any other menus that are open
        $$("div.noti_freq_menu").hide();

        var id = e.target.get('id').split('_')[2];

        // remove any progress indicator
        var select = "div#legis_" + id + " .notif_msg";
        $$(select)[0].removeClass('inProgress');

        // show the menu for the correct item
        select = 'div#noti_freq_menu_' + id;
        $$(select)[0].show();

        e.preventDefault();
    });

    $$("input.legis_freq_radio").addEvent('click', function(e) {

        var input = $(e.target);
        var watchlistitem = input.getParent('.watchlistitem');
        var select = watchlistitem.getElement('.noti_freq_menu');
        var val = input.get('value');
        var id = watchlistitem.get('data');
        var label = watchlistitem.getElement('a.dropdown');
        var notification = watchlistitem.getElement('.notif_msg');

        notification.addClass('inProgress').set('text', '');
        label.set('text', val);
        select.hide();

        CV.Watchlist.updateLegisFreq(id, val);
    });

    $$("a.topic_dropdown").addEvent('click', function(e) {
        var watchlistitem = $(e.target).getParent('.watchlistitem');
        var id = watchlistitem.get('data');
        var notification = watchlistitem.getElement('.notif_msg');
        var select = watchlistitem.getElement('.noti_freq_menu');

        notification.removeClass('inProgress');
        select.show();

        e.preventDefault();
    });

    $$("input.topic_freq_radio").addEvent('click', function(e) {
        var input = $(e.target);
        var watchlistitem = input.getParent('.watchlistitem');
        var select = watchlistitem.getElement('.noti_freq_menu');
        var label = watchlistitem.getElement('a.dropdown');
        var notification = watchlistitem.getElement('.notif_msg');
        var val = input.get('value');
        var id = watchlistitem.get('data');

        select.hide();
        label.set('text', val);
        notification.addClass('inProgress').set('text', '');

        CV.Watchlist.updateTopicFreq(id, val);
    });

});

com.tuitive.Pages = new Class
({
    initialize: function ()
    {
        this.global();
        $$('body').getProperty('class').each( function (item)
        {
            if (this[item]) this[item]();
        }.bind(this));
    },

    global: function ()
    {
        new com.tuitive.ExternalLinks();
        new com.tuitive.More();
        new com.californiavotes.DataFilter({className: 'dropdown'});

        SqueezeBox.initialize({
            size: {x: 730, y: 500}
        });
        SqueezeBox.assign($$('a.addwatchlist'), {
            handler: 'iframe',
            iframePreload:false
        });

        $$('.datepicker').each
        (
            function (item)
            {
                new com.tuitive.DatePicker(item);
            }
        );

        $$('.multiselect').each
        (
            function (multiselect)
            {
                new MTMultiWidget({'datasrc': multiselect});
            }
        );

        new com.tuitive.InputFocus('input.inputfocus');
        new com.californiavotes.Watchlist.AddButton({element: 'addbill'});
        new com.californiavotes.Watchlist.AddButton({element: 'addlegislator'});
    },

    home: function ()
    {
        new com.tuitive.Tabs('findit');
        new com.californiavotes.FindItBill();
    },

    blog: function ()
    {
        new FormCheck('comment_form', { display : { addClassErrorToField : 1 } });
    },

    admin: function ()
    {
        $$('input.mask').each
        (
            function (item)
            {
                new meio.Mask(item);
            }
        );

        var input = document.getElement('[rel=focus]');
        if (input)
        {input.focus();}

        $$('.uploader').each
        (
            function (item)
            {
                new com.tuitive.Upload(item, {maxFileSize: 10});
            }
        );

        new com.californiavotes.BillForm();
        new com.californiavotes.ChamberVoteForm($('chamber_vote_form'));
        new com.californiavotes.MotionForm($('motion_form'));
        new com.californiavotes.LegislatorForm();
        new com.tuitive.TextileFields();
        new com.tuitive.Notifications();
    }
})

com.tuitive.DatePicker = new Class
({
    initialize: function (elm)
    {
        this.container = $(elm);
        this.hidden = this.container.getElement('input.date');
        this.input = this.container.getElement('input.datejs');
        this.date_string = this.container.getElement('.your_date');
        this.messages = ["Nope", "Keep Trying", "Nadda", "Sorry", "No one\'s home", "Arg", "Bummer", "Faux pas", "Whoops", "Snafu", "Blunder"];
        this.input_empty = "Type a date above";
        this.input.addEvent('keyup', this.keyupHandler.bindWithEvent(this));
        this.input.addEvent('blur', this.blurHandler.bindWithEvent(this));

        if (this.hidden.value.length > 0)
        {this.setInitialValue();}
    },

    keyupHandler: function (event)
    {
        var value = this.input.value;

        date = this.parseDate(value);
        this.reset();
        this.setNotification(date);
        this.setHiddenInputValue(date);
    },

    blurHandler: function (event)
    {
        var value = this.input.value;
        date = this.parseDate(value);

        if (date)
        {this.setInputValue(date);}
    },

    setInitialValue: function ()
    {
        var value = this.hidden.value;

        date = this.parseDate('1/1/1970');
        date.addSeconds(value);
        this.reset();
        this.setNotification(date);
        this.setInputValue(date);
    },

    reset: function ()
    {
        this.date_string.removeClass('empty');
        this.date_string.removeClass('error');
        this.date_string.removeClass('accept');
    },

    parseDate: function (value)
    {
        return Date.parse(value);
    },

    setNotification: function (date)
    {
        if (date)
        {
            this.date_string.addClass('accept').set('html', date.toString("dddd, MMMM dd, yyyy"));
        }
        else
        {
            this.date_string.addClass("error").set('html', (this.messages[Math.round(this.messages.length * Math.random())] + "..."));
        }
    },

    setHiddenInputValue: function (date)
    {
        if (date)
        {
            var u = Date.strtotime(date.toString('yyyy-MM-ddTHH:mm:ss'));
            this.hidden.set('value', u);
        }
        else
        {
            this.hidden.set('value', '');
        }
    },

    setInputValue: function (date)
    {
        this.input.set('value', date.toString('MMMM dd, yyyy'));
    }
})

com.tuitive.ExternalLinks = new Class
({
    initialize: function ()
    {
        $$('a').each( function (item) {
            if (item.getProperty('rel') == "external") item.setProperty('target', '_blank');
        });
    }
})
com.tuitive.Tabs = new Class
({
    initialize: function (target)
    {
        this.container = $(target);
        this.tabs = this.container.getElements('ul#' + target + '-tabs li a');

        this.tabs.each(
            function (item)
            {
                var id = item.get('href');
                item.tabContent = document.getElement(id);
            }.bind(this)
        );

        this.setupTabContent();
        this.setTabEvents();
    },

    setupTabContent: function ()
    {
        this.hideTabs();
        this.showTab(this.tabs[0]);
    },

    hideTabs: function ()
    {
        this.tabs.each
        (
            function (item)
            {
                item.removeClass('selected');
                item.tabContent.setStyle('display', 'none');
            }
        );
    },

    showTab: function (tab)
    {
        tab.addClass('selected');
        tab.tabContent.setStyle('display', 'block');
    },

    setTabEvents: function ()
    {
        this.tabs.each(
            function (item)
            {
                item.addEvent('click', this.tabClickHandler.bindWithEvent(this));
            }.bind(this)
        );
    },

    tabClickHandler: function (event)
    {
        event.stop();
        this.swaptabs(event.target);
    },

    swaptabs: function (tab)
    {
        this.hideTabs();
        this.showTab(tab);
    }
})

com.tuitive.More = new Class
({
    initialize: function ()
    {this.getActuators();},

    getActuators: function ()
    {
        var list = new Array();
        document.getElements('a.tuitive-more').each
        (
            function (item)
            {
                var actuator = new com.tuitive.More.Actuator(item);
                actuator.addEvent('click', this.actuatorClickHandler.bindWithEvent(this));
                list.push(actuator);
            }.bind(this)
        );

        return list;
    },

    actuatorClickHandler: function (actuator)
    {
        var content = document.getElement(actuator.getId());
        var parent = content.getParent();
        var size = parent.getSize();
        var sizeHeightDiff = size.y - parent.getStyle('height').toInt();

        parent.setStyle('height', size.y + actuator.sizeDiff - sizeHeightDiff - actuator.height);
        content.setStyle('display', 'block');
        actuator.remove();
    }
})

com.tuitive.More.Actuator = new Class
({
    Implements: Events,
    initialize: function (target)
    {
        this.target = $(target);
        this.height = this.target.getSize().y;
        this.addEvents();
        this.hideContent();
    },

    addEvents: function ()
    {
        this.target.addEvent('click', this.clickHandler.bindWithEvent(this));
    },

    hideContent: function ()
    {
        var content = document.getElement(this.getId());
        this.contentHeight = content.getStyle('height').toInt();
        var parent = content.getParent();
        var initSize = parent.getSize();

        content.setStyle('display', 'none');

        var newSize = parent.getSize();
        this.sizeDiff = initSize.y - newSize.y;
    },

    clickHandler: function (event)
    {
        event.stop();
        this.fireEvent('click', this);
    },

    getId: function ()
    {
        return this.target.get('href');
    },

    remove: function ()
    {this.target.destroy();}
})

com.tuitive.Upload = new Class
({
    Implements : [Options, Events],
    options : {
        maxFileSize: 2, // mb
        ajaxPath: '/ajax/avatar-thumb/'
    },
    initialize: function (container, options)
    {
        try
        {
            this.setOptions(options);
            this.container = $(container);
            this.initLogger();
            this.initElements();
            this.initEvents();
            this.initSwffUploader();
            this.initImage();
        }
        catch (error)
        {alert(error);}
    },

    initLogger: function ()
    {
        this.log = new Roar
        (
            {
                container: $('roar'),
                position: 'topRight',
                duration: 4000,
                margin: {x: -64, y: 0}
            }
        );
    },

    initElements: function ()
    {
        this.button = this.container.getElement('input[type=button]');
        this.deleteButton = this.container.getElement('.delete');
        this.avatar = this.container.getElement('.avatar');
        this.progressBar = this.container.getElement('.progress');
        this.indicator = this.container.getElement('.indicator');
        this.progressBarWidth = this.progressBar.getStyle('width').toInt();
        this.urlField = this.container.getElement('input.url');

        this.avatar.set('load', {onComplete: this.updateImageComplete.bind(this)});
        this.avatarHTML = this.avatar.get('html');

        this.resetProgressBar();
        this.hideDeleteButton();
    },

    initEvents: function ()
    {
        this.deleteButton.addEvent('click', this.deleteButtonClickHandler.bindWithEvent(this));
    },

    initSwffUploader: function ()
    {
        this.swf = new Swiff.Uploader
        (
            {
                path: '/assets/flash/Swiff.Uploader.swf',
                url: '/admin/upload/',
                verbose: false,
                queued: false,
                multiple: false,
                target: this.button,
                instantStart: true,
                typeFilter:
                {
                    'Images (*.jpg, *.jpeg, *.gif, *.png)': '*.jpg; *.jpeg; *.gif; *.png'
                },
                fileSizeMax: this.options.maxFileSize * 1024 * 1024,
                appendCookieData: true,
                onSelectSuccess: this.selectSuccessHandler.bindWithEvent(this),
                onSelectFail: this.selectFailHandler.bindWithEvent(this),
                onQueue: this.queueHandler.bindWithEvent(this),
                onFileComplete: this.fileCompleteHandler.bindWithEvent(this),
                onComplete: this.completeHandler.bindWithEvent(this)
            }
        );
    },

    initImage: function ()
    {
        var value = this.urlField.get('value');
        if (value.length > 0)
        {
            var index = value.lastIndexOf('/') + 1;
            var file = value.slice(index)
            var parts = file.split('.');
            var url = parts[1] + '/' + parts[0] + '/';
            this.updateImage(url);
        }
    },

    resetProgressBar: function ()
    {
        this.progressBar.fade('hide');
        this.indicator.setStyle('left', -this.progressBarWidth);
    },

    showProgressBar: function ()
    {
        this.resetProgressBar();
        this.progressBar.fade('in');
    },

    hideProgressBar: function ()
    {this.progressBar.fade('out');},

    setProgress: function (percent)
    {
        var left = (this.progressBarWidth * (percent / 100)) - this.progressBarWidth;
        this.indicator.setStyle('left', left);
    },

    selectSuccessHandler: function (files)
    {
        this.log.empty();
        this.log.alert('Starting Upload', 'Uploading <em>' + files[0].name + '</em> (' + Swiff.Uploader.formatUnit(files[0].size, 'b') + ')');
        this.swf.setEnabled(false);
        this.hideDeleteButton();
        this.showProgressBar();
        this.urlField.set('value', '');
    },

    selectFailHandler: function (files)
    {
        this.log.alert('<em>' + files[0].name + '</em> was not added!', 'Please select an image smaller than 2 Mb. (Error: #' + files[0].validationError + ')');
    },

    queueHandler: function ()
    {
        if (!this.swf.uploading) return;
        this.setProgress(this.swf.percentLoaded);
    },

    fileCompleteHandler: function (file)
    {
        var error = JSON.decode(file.response.text, true).error;

        if (error)
        {
            ///this.log.alert('Failed Upload', 'Uploading <em>' + this.swf.fileList[0].name + '</em> failed, please try again. (Error: #' + this.swf.fileList[0].response.code + ' ' + this.swf.fileList[0].response.error + ')');
            this.log.alert('Failed Upload', error);
            this.avatar.set('html', this.avatarHTML);
        }
        else
        {
            this.log.alert('Upload Complete', 'File <em>' + this.swf.fileList[0].name + '</em> (' + Swiff.Uploader.formatUnit(this.swf.fileList[0].size, 'b') + ')');
            var url = JSON.decode(file.response.text, true).link;

            var thumb = JSON.decode(file.response.text, true).thumb;
            this.updateImage(thumb);
            this.urlField.set('value', url);
        }

        file.remove();
        this.swf.setEnabled(true);
    },

    completeHandler: function ()
    {this.hideProgressBar();},

    showDeleteButton: function ()
    {this.deleteButton.fade('in');},

    hideDeleteButton: function ()
    {this.deleteButton.fade('hide');},

    updateImage: function (url)
    {
        this.avatar.load(this.options.ajaxPath + url);
    },

    updateImageComplete: function ()
    {this.showDeleteButton();},

    deleteButtonClickHandler: function (event)
    {
        this.avatar.set('html', this.avatarHTML);
        this.hideDeleteButton();
        this.urlField.set('value', '');
    }
})

com.tuitive.AjaxCover = new Class
({
    Implements: Options,
    options:
    {
        backgroundColor: '#ffffff',
        backgroundOpacity: .5,
        id: 'ajaxcover'
    },

    initialize: function (options)
    {
        this.setOptions(options);
        this.html = this.getHtml();
    },

    getHtml: function ()
    {
        var outerDiv = new Element('div', {id: this.options.id});
        var innerDiv = new Element('div', {id: this.options.id + 'inner'});

        outerDiv.adopt(innerDiv);

        outerDiv.setStyles
        ({
            height: '100%',
            width: '100%',
            position: 'fixed',
            top: 0,
            left: 0,
            zIndex: 65000,
            display: 'none'
        });

        innerDiv.setStyles
        ({
            backgroundColor: this.options.backgroundColor,
            height: '100%',
            width: '100%',
            textAlign: 'center',
            opacity: this.options.backgroundOpacity
        });

        outerDiv.inject($(document.body), 'top');

        this.cover = outerDiv;
    },

    show: function ()
    {
        this.cover.set('opacity', 0);
        this.cover.setStyle('display', 'block');
        this.cover.fade('in');
    },

    hide: function ()
    {
        var tween = this.cover.get('tween');
        tween.start('opacity', 0).chain(
            function () { this.setStyle('display', 'none'); }.bind(this.cover)
        );
    }
})

com.tuitive.TextileFields = new Class
({
    Implements: Options,
    options:
    {
        selector: '.textile'
    },
    initialize: function(options)
    {
        this.setOptions(options);
        var fields = $$('textarea' + this.options.selector);

        fields.each
        (
            function (item)
            {
                new com.tuitive.TextileField(item);
            }.bind(this)
        );
    }
})

com.tuitive.TextileField = new Class
({
    initialize: function (field)
    {
        this.helpURL = '/ajax/textile-help/';
        this.field = $(field);
        this.label = this.getLabel();
        this.preview = this.createPreviewButton();

        this.initLabel();
        this.initPreview();
    },

    getLabel: function ()
    {
        var id = $(this.field).get('id');
        var label = document.getElement('label[for=' + id + ']');

        return label;
    },

    createPreviewButton: function ()
    {
        var br = new Element('br');
        var input = new Element('input').setProperties
        (
            {
                id: 'preview',
                type: 'button',
                value: 'Preview'
            }
        );

        br.inject(this.field, 'after');
        input.inject(br, 'after');

        return input;
    },

    initLabel: function ()
    {
        this.label.addClass('help');
        this.label.addEvent('click', this.labelClickHandler.bindWithEvent(this));
    },

    labelClickHandler: function (event)
    {
        event.stop();
        SqueezeBox.open(this.helpURL, {handler: 'iframe'});
    },

    initPreview: function ()
    {
        this.preview.addEvent('click', this.previewClickHandler.bindWithEvent(this));
    },

    previewClickHandler: function (event)
    {
        event.stop();

        var text = this.field.get('value');
        var html = convert(text);

        var h = new Element('h1').set('text', 'Preview');
        h.setStyles
        (
            {
                borderBottom: '1px solid #cccccc',
                paddingBottom: '12px',
                marginBottom: '10px'
            }
        );
        var p = new Element('p').set('html', html);
        var div = new Element('div').adopt(h).adopt(p);

        SqueezeBox.open(div, {handler: 'adopt'});
    }
})

com.tuitive.Notifications = new Class
({
    Implements: Options,
    options:
    {
        duration: '5000',
        position: 'uppperRight'
    },
    initialize: function(options)
    {
        this.setOptions(options);
        this.notifications = this.getNotifications();
        this.roar = this.initRoar();
        this.notify();
    },

    initRoar: function ()
    {
        var roar = new Roar({container: $('body'), position: this.options.position, duration: this.options.duration});

        return roar;
    },

    getNotifications: function ()
    {
        var container = $('notifications');

        if (! container)
        {
            return new Array();
        }

        var dataAtt = container.get('data');

        if (dataAtt)
        {
            var dataArray = dataAtt.split(',');
        }

        dataArray.each
        (
            function (item)
            {
                var option = item.split('=');
                this.options[option[0]] = option[1];
            }.bind(this)
        );

        var notifications = new Array();
        var divs = container.getElements('div');
        divs.each
        (
            function (item)
            {
                var params = new Hash();

                params.title = item.getElement('h1').get('text');
                params.message = item.getElement('p').get('text');
                notifications.push(params);
            }.bind(this)
        );

        return notifications;
    },

    notify: function ()
    {
        for (var i = 0; i < this.notifications.length; i++)
        {
            this.show.delay(300 * (i + 1), this, this.notifications[i]);
        }
    },

    show: function (params)
    {
        this.roar.alert(params.title, params.message);
    }
})

com.tuitive.InputFocus = new Class
({
    initialize: function (selector) {
        this.elements = $$(selector);

        this.elements.each
        (
            function (item)
            {
                if (item.get('type') == 'password')
                {
                    item.store('password', true);
                    item.set('type', 'text');
                }

                item.store('blurText', item.get('value'));
                item.addEvent('focus', this.focusHandler);
                item.addEvent('blur', this.blurHandler);
            }.bind(this)
        )
    },

    focusHandler: function (event)
    {
        var value = event.target.get('value');
        var blurText = event.target.retrieve('blurText');

        event.target.addClass('focused');

        if (event.target.retrieve('password'))
        {
            event.target.set('type', 'password');
        }

        if (value == blurText)
        {
            event.target.set('value', '');
        }
    },

    blurHandler: function (event)
    {
        var value = event.target.get('value');
        var blurText = event.target.retrieve('blurText');

        value = value.trim();

        if (value.length == 0)
        {
            event.target.set('value', blurText);
            event.target.removeClass('focused');
            event.target.set('type', 'text');
        }
    }
})

com.californiavotes.FindItBill = new Class
({
    initialize: function ()
    {
        $('expandlink').addEvent('click', this.expandLinkClickHandler.bindWithEvent(this));

        var inputWord = $('findbill');
        new Autocompleter.Request.HTML
        (
            inputWord,
            '/ajax/bill-search-suggestions/',
            {
                'injectChoice': this.injectChoice,
                'onSelection': this.selectHandler.bindWithEvent(this)
            }
        );

        var inputWord = $('findlegislator');
        new Autocompleter.Request.HTML
        (
            inputWord,
            '/ajax/legislator-search-suggestions/',
            {
                'onSelection': this.selectHandler.bindWithEvent(this)
                //'injectChoice': this.injectChoice
            }
        );
    },

    expandLinkClickHandler: function (event)
    {
        event.stop();
        $('topiccontainer').setStyles({overflow: 'hidden'});
        var url = event.target.get('href');
        var request = new Request({method: 'get', url: url, onSuccess: this.requestCompleteHandler.bind(this)});
        request.send();
    },

    requestCompleteHandler: function (responseText, responseXML)
    {
        var container = $('topiccontainer');
        var topics = $('topiccontainer').getElement('div.topics');
        var newTopics = topics.clone();

        $('expandlink').destroy();

        newTopics.set('html', responseText);
        newTopics.setStyle('display', 'none');
        newTopics.setStyle('opacity', 0);
        newTopics.inject(container);

        var size = newTopics.measure
        (
            function()
            {
                return this.getSize();
            }
        );

        var fadeOutTopics = function ()
        {topics.fade('out').get('tween').chain(fadeInTopics);}

        var fadeInTopics = function ()
        {
            topics.destroy();
            newTopics.setStyle('display', 'block');
            newTopics.fade('in');
        }

        topics.set('tween', {duration: 'short'});
        newTopics.set('tween', {duration: 'short'});
        container.set('tween', {duration: 'short'});

        container.tween('height', size.y).get('tween').chain(fadeOutTopics);
    },

    injectChoice: function (choice)
    {
        var dormant = choice.getElement('.dormant');
        var active = choice.getElement('.active');
        var marked = this.markQueryValue(active.get('text'));
        var text = dormant.get('text') + ' ' + marked;
        var value = choice.get('data') + ' ' + active.get('text');

        choice.inputValue = value;

        this.addChoiceEvents(choice.set('html', text));
    },

    selectHandler: function (event)
    {
        var form = event.getParent('form');

        if (form)
        {form.submit();}
    }
})

com.californiavotes.DataFilter = new Class
({
    Implements: Options,
    initialize: function (options)
    {
        this.setOptions(options);
        this.filters = this.getFilters();
    },

    getFilters: function ()
    {
        var filters = new Array();

        $$('.' + this.options.className).each
        (
            function (item)
            {
                filters.push(new com.californiavotes.DataFilter.Filter(item));
            }.bind(this)
        );
    }
})

com.californiavotes.DataFilter.Filter = new Class
({
    initialize: function (target)
    {
        try
        {
            this.target = target;
            this.validate();
            this.setContent();
            this.setEvents();
        }
        catch (error)
        {return;}
    },

    validate: function ()
    {
        var content = document.getElement(this.target.get('href'));
        if (! content)
        {
            throw new Error("Error: content not valid element");
        }

        this.content = content;
    },

    setContent: function ()
    {
        this.grabContent();
        this.positionContent();
    },

    grabContent: function ()
    {
        this.target.getParent().setStyle('position', 'relative');
        this.target.getParent().grab(this.content);
    },

    positionContent: function ()
    {
        this.content.setPosition({x: 0, y: 0});

        var targetSize = this.target.getSize();
        var contentPosition = this.content.getPosition(this.target);

        var x = Math.abs(contentPosition.x);
        var y = targetSize.y - 1;
        var position = {x: x, y: y};

        this.content.setPosition(position);
        this.content.setStyle('display', 'none');
    },

    setEvents: function ()
    {
        this.target.addEvent('mouseenter', this.mouseOverHandler.bindWithEvent(this));
        this.target.addEvent('mouseleave', this.mouseOutHandler.bindWithEvent(this));
        this.content.addEvent('mouseleave', this.mouseOutHandler.bindWithEvent(this));
    },

    mouseOverHandler: function (event)
    {
        this.content.setStyle('display', 'block');
    },

    mouseOutHandler: function (event)
    {
        if (this.shouldClose(event.relatedTarget))
        {
            this.content.setStyle('display', 'none');
        }
    },

    shouldClose: function (relatedTarget)
    {
        if (relatedTarget == this.content)
        {
            return false;
        }

        if (relatedTarget == this.target)
        {
            return false;
        }

        if (this.content.hasChild(relatedTarget))
        {
            return false;
        }

        return true;
    }
})

com.californiavotes.AdminForm = new Class
({
    initialize: function (form)
    {
        this.form = $(form);

        if (! this.form)
        {return;}

        this.initForm();
        this.addEvents();
    },

    initForm: function ()
    {
        this.cover = AjaxCover;
    },

    addEvents: function ()
    {
        if ($('saveandadd'))
        {
            $('saveandadd').addEvent('click', this.saveandaddClickHandler.bindWithEvent(this));
        }
    },

    saveandaddClickHandler: function (event)
    {
        var input = document.getElement('input[name=saveandadd]');

        if (input)
        {
            input.set('value', 1);
        }
    },

    disable: function (element)
    {
        var inputs = element.getElements('input');

        element.addClass('disabled');
        inputs.each(function (item) { item.set('disabled', true).set('checked', 0) });
    },

    enable: function (element)
    {
        var inputs = element.getElements('input');

        element.removeClass('disabled');
        inputs.each(function (item) { item.set('disabled', false) });
    }
});

com.californiavotes.RollCallForm = new Class
({
    Extends: com.californiavotes.AdminForm,

    initForm: function ()
    {
        this.parent();

        this.voteTypeRollCall = $('vote_type_roll_call');
        this.chamberSession = $('chamber_session');
        this.rollCall = $('rollcall');
        this.chamberVote = $('chambervote');
        this.voteType = $('votetype');
        this.voteResultProgress = $('vote_result_progress');

        FancyForm.start($$('#chambervote input'));

        this.initStates();
    },

    initStates: function ()
    {
        if (this.rollCall.hasClass('hidden'))
        {
            this.rollCall.slide('hide').store('state', 'off');
            this.chamberVote.slide('hide').store('state', 'off');
        }
        else
        {
            this.rollCall.store('state', 'on');
            this.chamberVote.store('state', 'on');
        }

        if (this.voteResultProgress.get('checked'))
        {this.disable(this.voteType);}
        else
        {this.enable(this.voteType);}
    },

    addEvents: function ()
    {
        this.parent();

        $$('input[name=vote_result]').addEvent('click', this.voteResultClickHandler.bindWithEvent(this));
        $('vote_type_voice').addEvent('click', this.voteTypeClickHandler.bindWithEvent(this));
        $$('input[name=all]').addEvent('click', this.selectAllClickHandler.bindWithEvent(this));
        this.voteTypeRollCall.addEvent('click', this.voteTypeClickHandler.bindWithEvent(this));
        this.chamberSession.addEvent('change', this.chamberSessionChangeHandler.bindWithEvent(this));
    },

    voteResultClickHandler: function (event)
    {
        if (event.target.get('value') == 3)
        {
            this.voteType.removeClass('error');
            this.disable(this.voteType);
            this.hideRollCall();
        }
        else
        {
            this.enable(this.voteType);

            if (this.voteTypeRollCall.get('checked'))
            {this.showRollCall();}
        }
    },

    voteTypeClickHandler: function (event)
    {
        if (event.target.get('value') == 2)
        {
            this.rollCall.removeClass('hidden');
            this.showRollCall();
        }
        else
        {this.hideRollCall();}
    },

    chamberSessionChangeHandler: function (event)
    {
        var value = event.target.get('value');

        if (Number(value))
        {this.updateChamberVote(event.target.get('value'));}
        else
        {
            this.chamberVote.slide('out').addClass('hidden');
            this.updateSubmitButton();
        }
    },

    updateChamberVote: function (chamberSessionID)
    {
        var url = '/ajax/chamber-vote/' + chamberSessionID + '/';
        $('chambervotereplace').set('load',
        {
                onComplete: this.chamberSessionLoadComplete.bind(this),
                onRequest: this.chamberSessionRequstHandler.bind(this)
        });
        $('chambervotereplace').load(url);
    },

    chamberSessionRequstHandler: function ()
    {this.cover.show();},

    chamberSessionLoadComplete: function ()
    {
        FancyForm.add($$('#chambervotereplace input'));
        this.chamberVote.removeClass('hidden');
        if (this.chamberVote.retrieve('state') == 'on')
        {this.updateSubmitButton();}

        this.cover.hide();
    },

    selectAllClickHandler: function (event)
    {
        var val = event.target.firstElementChild.get('value');

        $$('input[value=' + val + ']').each
        (
            function (item)
            {
                item.checked = true;
            }
        );

        this.updateFancyForm();
    },

    showRollCall: function ()
    {
        this.updateSubmitButton();
        this.rollCall.slide('in').store('state', 'on');
        this.chamberVote.slide('in').store('state', 'on');
    },

    hideRollCall: function ()
    {
        this.updateSubmitButton();
        this.rollCall.slide('out').store('state', 'off');
        this.chamberVote.slide('out').store('state', 'off');
    },

    updateSubmitButton: function ()
    {
        if (this.voteResultProgress.get('checked'))
        {
            this.firstBox.grab($('submit'));
            return;
        }
        else if (this.voteTypeRollCall.get('checked') && this.chamberSession.get('value'))
        {
            this.chamberVote.grab($('submit'));
            this.chamberVote.slide('in');
        }
        else if (this.voteTypeRollCall.get('checked'))
        {
            this.rollCall.grab($('submit'));
            this.rollCall.slide('in');
        }
        else
        {this.firstBox.grab($('submit'));}
    },

    updateFancyForm: function ()
    {
        if (FancyForm)
        {
            FancyForm.initing = true;
            FancyForm.chks.each
            (
                function (chk)
                {FancyForm.update(chk);}
            );
            FancyForm.initing = false;
        }
    }
});

com.californiavotes.BillForm = new Class
({
    initialize: function ()
    {
        this.form = $('billform');

        if (this.form)
        {this.addEvents();}

        this.cover = AjaxCover;
    },

    addEvents: function ()
    {
        $('chamber_session').addEvent('change', this.billTypeChangeHandler.bindWithEvent(this));
        $('saveandadd').addEvent('click', this.saveandaddClickHandler.bindWithEvent(this));
    },

    billTypeChangeHandler: function (event)
    {
        var id = event.target.options[event.target.selectedIndex].value;
        $('legislatorsselect').set
        (
            'load',
            {
                onComplete: function ()
                {
                    new MTMultiWidget({'datasrc': $('legislators')});
                    this.cover.hide();
                }.bind(this),

                onRequest: this.onRequstHandler.bind(this)
            }
        );
        $('legislatorsselect').load('/ajax/legislator-options-by-bill-type/' + id);
    },

    onRequstHandler: function ()
    {this.cover.show();},

    saveandaddClickHandler: function (event)
    {
        var input = document.getElement('input[name=saveandadd]');

        if (input)
        {
            input.set('value', 1);
        }
    }
})

com.californiavotes.ChamberVoteForm = new Class
({
    Extends: com.californiavotes.RollCallForm,

    initForm: function ()
    {
        this.parent();

        this.firstBox = $('chamber');
    }
})

com.californiavotes.MotionForm = new Class
({
    Extends: com.californiavotes.RollCallForm,

    initForm: function ()
    {
        this.motion_type = $('motion_type');
        this.firstBox = $('motion');

        this.parent();
    },

    initStates: function ()
    {
        this.parent();

        this.setVotesState();
    },

    addEvents: function ()
    {
        this.parent();

        this.motion_type.addEvent('change', this.motionTypeChangeHandler.bindWithEvent(this));
    },

    motionTypeChangeHandler: function (event)
    {this.setVotesState();},

    setVotesState: function ()
    {
        var option = this.motion_type.options[this.motion_type.selectedIndex];

        if (option.get('value') == 19)
        {this.enable($('voteresults'));}
        else
        {
            this.disable($('voteresults'));
            this.disable($('votetype'));
            this.hideRollCall();
        }
    }
})

com.californiavotes.LegislatorForm = new Class
({
    initialize: function ()
    {
        this.form = $('legislatorform');

        if (this.form)
        {this.addEvents();}
    },

    addEvents: function ()
    {
        $('saveandadd').addEvent('click', this.saveandaddClickHandler.bindWithEvent(this));
    },

    saveandaddClickHandler: function (event)
    {
        var input = document.getElement('input[name=saveandadd]');

        if (input)
        {
            input.set('value', 1);
        }
    }
})

var CV = (window.CV || {});
CV.Watchlist = (function() {

    return {

        addBill: function(e) {
            var url = e.target.getParent('a').get('href');
            var id = e.target.getParent('a').get('id');
            var data = "id="+id;

            var request = new Request({
                method: 'post',
                url: url,
                data: data,
                onSuccess: function(responseText, responseXML) {
                    if(responseText) {
                        $('progress_msg').removeClass('inProgress').addClass('success').set('text', 'Bill Added!');
                    }
                },
                onFailure: function(xhr) {
                    $('progress_msg').removeClass('inProgress');
                    $('progress_msg').set('text', 'Error adding bill.');
                    $('progress_msg').removeClass('success').addClass('failure');
                }
            });
            request.send();
        },

        addLegislator: function(e) {
            var url = e.target.getParent('a').get('href');
            var id = e.target.getParent('a').get('id');
            var data = "id="+id;

            var request = new Request({
                method: 'post',
                url: url,
                data: data,
                onSuccess: function(responseText, responseXML) {
                    if(responseText) {
                        $('progress_msg').removeClass('inProgress').addClass('success').set('text', 'Legislator Added!');
                    }
                },
                onFailure: function(xhr) {
                    $('progress_msg').removeClass('inProgress');
                    $('progress_msg').set('text', 'Error adding legislator.');
                    $('progress_msg').removeClass('success').addClass('failure');
                }
            });
            request.send();
        },

        addTopic: function(e) {
            var url = e.target.getParent('a').get('href');
            var id = e.target.getParent('a').get('id');
            var data = "id="+id;

            var request = new Request({
                method: 'post',
                url: url,
                data: data,
                onSuccess: function(responseText, responseXML) {
                    if(responseText) {
                        $('topics_progress_msg').removeClass('inProgress').addClass('success').set('text', 'Topic Added!');
                    }
                },
                onFailure: function(xhr) {
                    $('topics_progress_msg').removeClass('inProgress');
                    $('topics_progress_msg').set('text', 'Error adding topic');
                    $('topics_progress_msg').removeClass('success').addClass('failure');
                }
            });
            request.send();
        },

        deleteBill: function(e) {
            var url = e.target.get('href');
            var id = e.target.get('id');
            var data = "id="+id;

            var request = new Request({
                method: 'post',
                url: url,
                data: data,
                onSuccess: function(responseText, responseXML) {
                    if(responseText) {
                        var select = 'a#'+id;
                        var el = $$(select)[0];
                        el.removeClass('inProgress');
                        new Fx.Reveal(el.getParent().getParent()).dissolve();
                    }
                },
                onFailure: function(responseText) {
                    var select = 'a#'+ id;
                    $$(select)[0].removeClass('inProgress');
                }
            });
            request.send();
        },

        deleteLegislator: function(e) {
            var url = e.target.get('href');
            var id = e.target.get('id');
            var data = "id="+id;

            var request = new Request({
                method: 'post',
                url: url,
                data: data,
                onSuccess: function(responseText, responseXML) {
                    if(responseText) {
                        var select = 'a#'+id;
                        var el = $$(select)[0];
                        el.removeClass('inProgress');
                        new Fx.Reveal(el.getParent().getParent()).dissolve();
                    }
                },
                onFailure: function(responseText) {
                    var select = 'a#'+ id;
                    $$(select)[0].removeClass('inProgress');
                }
            });
            request.send();
        },

        deleteTopic: function(e) {
            var url = e.target.get('href');
            var id = e.target.get('id');
            var data = "id="+id;

            var request = new Request({
                method: 'post',
                url: url,
                data: data,
                onSuccess: function(responseText, responseXML) {
                    if(responseText) {
                        var select = 'a#'+id;
                        var el = $$(select)[0];
                        el.removeClass('inProgress');
                        new Fx.Reveal(el.getParent().getParent()).dissolve();
                    }
                },
                onFailure: function(responseText) {
                    var select = 'a#'+ id;
                    $$(select)[0].removeClass('inProgress');
                }
            });
            request.send();
        },

        searchBills: function(e) {
            var url = "/ajax/watchlist_billsearch/";
            var searchTerm = $('findbill').get('value');
            var data = "value="+searchTerm;

            var request = new Request({
                method: 'post',
                url: url,
                data: data,
                onSuccess: function(responseTree, responseElements, responseHTML, responseJavascript) {
                    // replace the HTMl of 'billResultsUl'
                    $('billResultsUl').set('html', responseTree);

                    // attach event handlers for 'add bill' clicks
                    $$("a.addbill").addEvent('click', function(e) {
                        CV.Watchlist.addBill(e);
                        return false;
                    });
                }
            });
            request.send();
        },

        searchLegislators: function(e) {
            var url = "/ajax/watchlist_legislatorsearch";
            var searchTerm = $('findlegislator').get('value');
            var data = "value="+searchTerm;

            var request = new Request({
                method: 'post',
                url: url,
                data: data,
                onSuccess: function(responseTree, responseElements, responseHTML, responseJavascript) {
                    // replace the HTMl of 'billResultsUl'
                    $('legislatorResultsUl').set('html', responseTree);

                    // attach event handlers for 'add bill' clicks
                    $$("a.addlegislator").addEvent('click', function(e) {
                        CV.Watchlist.addLegislator(e);
                        return false;
                    });
                }
            });
            request.send();
        },

        updateLegisFreq: function(id, val) {
            var url = "/ajax/watchlist_updatelegisfreq/";
            var data = "value="+val+"&id="+id;

            var request = new Request({
                method: 'post',
                url: url,
                data: data,
                onSuccess: function(responseText, responseXML) {
                    // remove progress indicator
                    var select = "div#legis_" + id + " .notif_msg";
                    var el = $$(select)[0];
                    el.removeClass('inProgress');

                    if(responseText) {
                        el.set('text', 'Updated!');
                    } else {
                        el.set('text', 'An error occurred processing your request.');
                    }

                    el.get('tween', {
                        property: 'opacity',
                        duration: 2000,
                        link: 'wait',
                        transition: Fx.Transitions.Quint.easeIn
                        }).start(0).chain(function(e) {
                            el.set('text', '').set('opacity', 1);
                        });
                },
                onFailure: function(responseText, responseXML) {
                    // remove progress indicator for ajax call and set error text
                    var select = "div#legis_" + id + " .notif_msg";
                    $$(select)[0].removeClass('inProgress').set('text', 'An error occurred processing your request.');
                }
            });
            request.send();
        },

        updateTopicFreq: function(id, val) {
            var url = "/ajax/watchlist_updatetopicfreq/";
            var data = "value="+val+"&id="+id;

            var request = new Request({
                method: 'post',
                url: url,
                data: data,
                onSuccess: function(responseText, responseXML) {
                    var select = "div#topic_" + id + " .notif_msg";
                    var el = $$(select)[0];
                    el.removeClass('inProgress');

                    if(responseText) {
                        el.set('text', 'Updated!');
                    } else {
                        el.set('text', 'An error occurred processing your request.');
                    }

                    el.get('tween', {
                        property: 'opacity',
                        duration: 2000,
                        link: 'wait',
                        transition: Fx.Transitions.Quint.easeIn
                        }).start(0).chain(function(e) {
                            el.set('text', '').set('opacity', 1);
                        });
                },
                onFailure: function(responseText, responseXML) {
                    // remove progress indicator for ajax call and set error text
                    var select = "div#topic_" + id + " .notif_msg";
                    $$(select)[0].removeClass('inProgress').set('text', 'An error occurred processing your request.');
                }
            });
            request.send();
        }
    };

})();

com.californiavotes.Watchlist = {};

com.californiavotes.Watchlist.AddButton = new Class
({
    Implements: Options,

    options:
    {
        // element: ,
    },

    initialize: function (options)
    {
        this.setOptions(options);
        this.element = $(options.element);

        if (! this.element)
        {return;}

        this.img = this.element.getElement('img');
        this.element.addEvent('click', this.clickHandler.bindWithEvent(this));
        this.error_message = new Element('p', {'class': 'error'}).appendText(MooTools.lang.get('watchlist', 'add_bill_error'));
    },

    clickHandler: function (event)
    {
        event.stop();

        var url = this.element.get('href');
        var data = this.element.get('data');
        var id = JSON.decode(data).id;

        var post = "id=" + id;
        var request = new Request(
        {
            method: 'post',
            data: post,
            url: url,
            onRequest: this.requestStartHandler.bind(this),
            onFailure: this.requestFailHandler.bind(this),
            onComplete: this.requestCompleteHandler.bind(this),
            onSuccess: this.requestSuccessHandler.bind(this)
        });
        request.send();
    },

    requestStartHandler: function ()
    {AjaxCover.show();},

    requestFailHandler: function (xhr)
    {this.fail();},

    requestCompleteHandler: function ()
    {AjaxCover.hide();},

    requestSuccessHandler: function (responseText, responseXML)
    {
        if (Boolean(responseText))
        {this.success();}
        else
        {this.fail();}
    },

    success: function ()
    {
        this.img.set('src', 'http://c0027394.cdn1.cloudfiles.rackspacecloud.com/images/global/watchlist-added.png');
    },

    fail: function ()
    {
        this.error_message.setStyle('display', 'none');
        this.error_message.inject(this.element, 'after');
        this.error_message.wink(5000);
    }
})


