var MooTools={version:'1.11'};function $defined(obj){return(obj!=undefined);};function $type(obj){if(!$defined(obj))return false;if(obj.htmlElement)return'element';var type=typeof obj;if(type=='object'&&obj.nodeName){switch(obj.nodeType){case 1:return'element';case 3:return(/\S/).test(obj.nodeValue)?'textnode':'whitespace';}}
if(type=='object'||type=='function'){switch(obj.constructor){case Array:return'array';case RegExp:return'regexp';case Class:return'class';}
if(typeof obj.length=='number'){if(obj.item)return'collection';if(obj.callee)return'arguments';}}
return type;};function $merge(){var mix={};for(var i=0;i<arguments.length;i++){for(var property in arguments[i]){var ap=arguments[i][property];var mp=mix[property];if(mp&&$type(ap)=='object'&&$type(mp)=='object')mix[property]=$merge(mp,ap);else mix[property]=ap;}}
return mix;};var $extend=function(){var args=arguments;if(!args[1])args=[this,args[0]];for(var property in args[1])args[0][property]=args[1][property];return args[0];};var $native=function(){for(var i=0,l=arguments.length;i<l;i++){arguments[i].extend=function(props){for(var prop in props){if(!this.prototype[prop])this.prototype[prop]=props[prop];if(!this[prop])this[prop]=$native.generic(prop);}};}};$native.generic=function(prop){return function(bind){return this.prototype[prop].apply(bind,Array.prototype.slice.call(arguments,1));};};$native(Function,Array,String,Number);function $chk(obj){return!!(obj||obj===0);};function $pick(obj,picked){return $defined(obj)?obj:picked;};function $random(min,max){return Math.floor(Math.random()*(max-min+1)+min);};function $time(){return new Date().getTime();};function $clear(timer){clearTimeout(timer);clearInterval(timer);return null;};var Abstract=function(obj){obj=obj||{};obj.extend=$extend;return obj;};var Window=new Abstract(window);var Document=new Abstract(document);document.head=document.getElementsByTagName('head')[0];window.xpath=!!(document.evaluate);if(window.ActiveXObject)window.ie=window[window.XMLHttpRequest?'ie7':'ie6']=true;else if(document.childNodes&&!document.all&&!navigator.taintEnabled)window.webkit=window[window.xpath?'webkit420':'webkit419']=true;else if(window.navigator.userAgent.toString().toLowerCase().indexOf("firefox")>=0)window.gecko=true;window.khtml=window.webkit;Object.extend=$extend;if(typeof HTMLElement=='undefined'){var HTMLElement=function(){};if(window.webkit)document.createElement("iframe");HTMLElement.prototype=(window.webkit)?window["[[DOMElement.prototype]]"]:{};}
HTMLElement.prototype.htmlElement=function(){};if(window.ie6)try{document.execCommand("BackgroundImageCache",false,true);}catch(e){};var Class=function(properties){var klass=function(){return(arguments[0]!==null&&this.initialize&&$type(this.initialize)=='function')?this.initialize.apply(this,arguments):this;};$extend(klass,this);klass.prototype=properties;klass.constructor=Class;return klass;};Class.empty=function(){};Class.prototype={extend:function(properties){var proto=new this(null);for(var property in properties){var pp=proto[property];proto[property]=Class.Merge(pp,properties[property]);}
return new Class(proto);},implement:function(){for(var i=0,l=arguments.length;i<l;i++)$extend(this.prototype,arguments[i]);}};Class.Merge=function(previous,current){if(previous&&previous!=current){var type=$type(current);if(type!=$type(previous))return current;switch(type){case'function':var merged=function(){this.parent=arguments.callee.parent;return current.apply(this,arguments);};merged.parent=previous;return merged;case'object':return $merge(previous,current);}}
return current;};var Chain=new Class({chain:function(fn){this.chains=this.chains||[];this.chains.push(fn);return this;},callChain:function(){if(this.chains&&this.chains.length)this.chains.shift().delay(10,this);},clearChain:function(){this.chains=[];}});var Events=new Class({addEvent:function(type,fn){if(fn!=Class.empty){this.$events=this.$events||{};this.$events[type]=this.$events[type]||[];this.$events[type].include(fn);}
return this;},fireEvent:function(type,args,delay){if(this.$events&&this.$events[type]){this.$events[type].each(function(fn){fn.create({'bind':this,'delay':delay,'arguments':args})();},this);}
return this;},removeEvent:function(type,fn){if(this.$events&&this.$events[type])this.$events[type].remove(fn);return this;}});var Options=new Class({setOptions:function(){this.options=$merge.apply(null,[this.options].extend(arguments));if(this.addEvent){for(var option in this.options){if($type(this.options[option]=='function')&&(/^on[A-Z]/).test(option))this.addEvent(option,this.options[option]);}}
return this;}});Array.extend({forEach:function(fn,bind){for(var i=0,j=this.length;i<j;i++)fn.call(bind,this[i],i,this);},filter:function(fn,bind){var results=[];for(var i=0,j=this.length;i<j;i++){if(fn.call(bind,this[i],i,this))results.push(this[i]);}
return results;},map:function(fn,bind){var results=[];for(var i=0,j=this.length;i<j;i++)results[i]=fn.call(bind,this[i],i,this);return results;},every:function(fn,bind){for(var i=0,j=this.length;i<j;i++){if(!fn.call(bind,this[i],i,this))return false;}
return true;},some:function(fn,bind){for(var i=0,j=this.length;i<j;i++){if(fn.call(bind,this[i],i,this))return true;}
return false;},indexOf:function(item,from){var len=this.length;for(var i=(from<0)?Math.max(0,len+from):from||0;i<len;i++){if(this[i]===item)return i;}
return-1;},copy:function(start,length){start=start||0;if(start<0)start=this.length+start;length=length||(this.length-start);var newArray=[];for(var i=0;i<length;i++)newArray[i]=this[start++];return newArray;},remove:function(item){var i=0;var len=this.length;while(i<len){if(this[i]===item){this.splice(i,1);len--;}else{i++;}}
return this;},contains:function(item,from){return this.indexOf(item,from)!=-1;},associate:function(keys){var obj={},length=Math.min(this.length,keys.length);for(var i=0;i<length;i++)obj[keys[i]]=this[i];return obj;},extend:function(array){for(var i=0,j=array.length;i<j;i++)this.push(array[i]);return this;},merge:function(array){for(var i=0,l=array.length;i<l;i++)this.include(array[i]);return this;},include:function(item){if(!this.contains(item))this.push(item);return this;},getRandom:function(){return this[$random(0,this.length-1)]||null;},getLast:function(){return this[this.length-1]||null;}});Array.prototype.each=Array.prototype.forEach;Array.each=Array.forEach;function $A(array){return Array.copy(array);};function $each(iterable,fn,bind){if(iterable&&typeof iterable.length=='number'&&$type(iterable)!='object'){Array.forEach(iterable,fn,bind);}else{for(var name in iterable)fn.call(bind||iterable,iterable[name],name);}};Array.prototype.test=Array.prototype.contains;String.extend({test:function(regex,params){return(($type(regex)=='string')?new RegExp(regex,params):regex).test(this);},toInt:function(){return parseInt(this,10);},toFloat:function(){return parseFloat(this);},camelCase:function(){return this.replace(/-\D/g,function(match){return match.charAt(1).toUpperCase();});},hyphenate:function(){return this.replace(/\w[A-Z]/g,function(match){return(match.charAt(0)+'-'+match.charAt(1).toLowerCase());});},capitalize:function(){return this.replace(/\b[a-z]/g,function(match){return match.toUpperCase();});},trim:function(){return this.replace(/^\s+|\s+$/g,'');},clean:function(){return this.replace(/\s{2,}/g,' ').trim();},rgbToHex:function(array){var rgb=this.match(/\d{1,3}/g);return(rgb)?rgb.rgbToHex(array):false;},hexToRgb:function(array){var hex=this.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);return(hex)?hex.slice(1).hexToRgb(array):false;},contains:function(string,s){return(s)?(s+this+s).indexOf(s+string+s)>-1:this.indexOf(string)>-1;},escapeRegExp:function(){return this.replace(/([.*+?^${}()|[\]\/\\])/g,'\\$1');}});Array.extend({rgbToHex:function(array){if(this.length<3)return false;if(this.length==4&&this[3]==0&&!array)return'transparent';var hex=[];for(var i=0;i<3;i++){var bit=(this[i]-0).toString(16);hex.push((bit.length==1)?'0'+bit:bit);}
return array?hex:'#'+hex.join('');},hexToRgb:function(array){if(this.length!=3)return false;var rgb=[];for(var i=0;i<3;i++){rgb.push(parseInt((this[i].length==1)?this[i]+this[i]:this[i],16));}
return array?rgb:'rgb('+rgb.join(',')+')';}});Function.extend({create:function(options){var fn=this;options=$merge({'bind':fn,'event':false,'arguments':null,'delay':false,'periodical':false,'attempt':false},options);if($chk(options.arguments)&&$type(options.arguments)!='array')options.arguments=[options.arguments];return function(event){var args;if(options.event){event=event||window.event;args=[(options.event===true)?event:new options.event(event)];if(options.arguments)args.extend(options.arguments);}
else args=options.arguments||arguments;var returns=function(){return fn.apply((options.bind||fn),args);};if(options.delay)return setTimeout(returns,options.delay);if(options.periodical)return setInterval(returns,options.periodical);if(options.attempt)try{return returns();}catch(err){return false;};return returns();};},pass:function(args,bind){return this.create({'arguments':args,'bind':bind});},attempt:function(args,bind){return this.create({'arguments':args,'bind':bind,'attempt':true})();},bind:function(bind,args){return this.create({'bind':bind,'arguments':args});},bindAsEventListener:function(bind,args){return this.create({'bind':bind,'event':true,'arguments':args});},delay:function(delay,bind,args){return this.create({'delay':delay,'bind':bind,'arguments':args})();},periodical:function(interval,bind,args){return this.create({'periodical':interval,'bind':bind,'arguments':args})();}});Number.extend({toInt:function(){return parseInt(this);},toFloat:function(){return parseFloat(this);},limit:function(min,max){return Math.min(max,Math.max(min,this));},round:function(precision){precision=Math.pow(10,precision||0);return Math.round(this*precision)/precision;},times:function(fn){for(var i=0;i<this;i++)fn(i);}});var Element=new Class({initialize:function(el,props){if($type(el)=='string'){if(window.ie&&props&&(props.name||props.type)){var name=(props.name)?' name="'+props.name+'"':'';var type=(props.type)?' type="'+props.type+'"':'';delete props.name;delete props.type;el='<'+el+name+type+'>';}
el=document.createElement(el);}
el=$(el);return(!props||!el)?el:el.set(props);}});var Elements=new Class({initialize:function(elements){return(elements)?$extend(elements,this):this;}});Elements.extend=function(props){for(var prop in props){this.prototype[prop]=props[prop];this[prop]=$native.generic(prop);}};function $(el){if(!el)return null;if(el.htmlElement)return Garbage.collect(el);if([window,document].contains(el))return el;var type=$type(el);if(type=='string'){el=document.getElementById(el);type=(el)?'element':false;}
if(type!='element')return null;if(el.htmlElement)return Garbage.collect(el);if(['object','embed'].contains(el.tagName.toLowerCase()))return el;$extend(el,Element.prototype);el.htmlElement=function(){};return Garbage.collect(el);};document.getElementsBySelector=document.getElementsByTagName;function $$(){var elements=[];for(var i=0,j=arguments.length;i<j;i++){var selector=arguments[i];switch($type(selector)){case'element':elements.push(selector);case'boolean':break;case false:break;case'string':selector=document.getElementsBySelector(selector,true);default:elements.extend(selector);}}
return $$.unique(elements);};$$.unique=function(array){var elements=[];for(var i=0,l=array.length;i<l;i++){if(array[i].$included)continue;var element=$(array[i]);if(element&&!element.$included){element.$included=true;elements.push(element);}}
for(var n=0,d=elements.length;n<d;n++)elements[n].$included=null;return new Elements(elements);};Elements.Multi=function(property){return function(){var args=arguments;var items=[];var elements=true;for(var i=0,j=this.length,returns;i<j;i++){returns=this[i][property].apply(this[i],args);if($type(returns)!='element')elements=false;items.push(returns);};return(elements)?$$.unique(items):items;};};Element.extend=function(properties){for(var property in properties){HTMLElement.prototype[property]=properties[property];Element.prototype[property]=properties[property];Element[property]=$native.generic(property);var elementsProperty=(Array.prototype[property])?property+'Elements':property;Elements.prototype[elementsProperty]=Elements.Multi(property);}};Element.extend({set:function(props){for(var prop in props){var val=props[prop];switch(prop){case'styles':this.setStyles(val);break;case'events':if(this.addEvents)this.addEvents(val);break;case'properties':this.setProperties(val);break;default:this.setProperty(prop,val);}}
return this;},inject:function(el,where){el=$(el);switch(where){case'before':el.parentNode.insertBefore(this,el);break;case'after':var next=el.getNext();if(!next)el.parentNode.appendChild(this);else el.parentNode.insertBefore(this,next);break;case'top':var first=el.firstChild;if(first){el.insertBefore(this,first);break;}
default:el.appendChild(this);}
return this;},injectBefore:function(el){return this.inject(el,'before');},injectAfter:function(el){return this.inject(el,'after');},injectInside:function(el){return this.inject(el,'bottom');},injectTop:function(el){return this.inject(el,'top');},adopt:function(){var elements=[];$each(arguments,function(argument){elements=elements.concat(argument);});$$(elements).inject(this);return this;},remove:function(){return this.parentNode.removeChild(this);},clone:function(contents){var el=$(this.cloneNode(contents!==false));if(!el.$events)return el;el.$events={};for(var type in this.$events)el.$events[type]={'keys':$A(this.$events[type].keys),'values':$A(this.$events[type].values)};return el.removeEvents();},replaceWith:function(el){el=$(el);this.parentNode.replaceChild(el,this);return el;},appendText:function(text){this.appendChild(document.createTextNode(text));return this;},hasClass:function(className){return this.className.contains(className,' ');},addClass:function(className){if(!this.hasClass(className))this.className=(this.className+' '+className).clean();return this;},removeClass:function(className){this.className=this.className.replace(new RegExp('(^|\\s)'+className+'(?:\\s|$)'),'$1').clean();return this;},toggleClass:function(className){return this.hasClass(className)?this.removeClass(className):this.addClass(className);},setStyle:function(property,value){switch(property){case'opacity':return this.setOpacity(parseFloat(value));case'float':property=(window.ie)?'styleFloat':'cssFloat';}
property=property.camelCase();switch($type(value)){case'number':if(!['zIndex','zoom'].contains(property))value+='px';break;case'array':value='rgb('+value.join(',')+')';}
this.style[property]=value;return this;},setStyles:function(source){switch($type(source)){case'object':Element.setMany(this,'setStyle',source);break;case'string':this.style.cssText=source;}
return this;},setOpacity:function(opacity){if(opacity==0){if(this.style.visibility!="hidden")this.style.visibility="hidden";}else{if(this.style.visibility!="visible")this.style.visibility="visible";}
if(!this.currentStyle||!this.currentStyle.hasLayout)this.style.zoom=1;if(window.ie)this.style.filter=(opacity==1)?'':"alpha(opacity="+opacity*100+")";this.style.opacity=this.$tmp.opacity=opacity;return this;},getStyle:function(property){property=property.camelCase();var result=this.style[property];if(!$chk(result)){if(property=='opacity')return this.$tmp.opacity;result=[];for(var style in Element.Styles){if(property==style){Element.Styles[style].each(function(s){var style=this.getStyle(s);result.push(parseInt(style)?style:'0px');},this);if(property=='border'){var every=result.every(function(bit){return(bit==result[0]);});return(every)?result[0]:false;}
return result.join(' ');}}
if(property.contains('border')){if(Element.Styles.border.contains(property)){return['Width','Style','Color'].map(function(p){return this.getStyle(property+p);},this).join(' ');}else if(Element.borderShort.contains(property)){return['Top','Right','Bottom','Left'].map(function(p){return this.getStyle('border'+p+property.replace('border',''));},this).join(' ');}}
if(document.defaultView)result=document.defaultView.getComputedStyle(this,null).getPropertyValue(property.hyphenate());else if(this.currentStyle)result=this.currentStyle[property];}
if(window.ie)result=Element.fixStyle(property,result,this);if(result&&property.test(/color/i)&&result.contains('rgb')){return result.split('rgb').splice(1,4).map(function(color){return color.rgbToHex();}).join(' ');}
return result;},getStyles:function(){return Element.getMany(this,'getStyle',arguments);},walk:function(brother,start){brother+='Sibling';var el=(start)?this[start]:this[brother];while(el&&$type(el)!='element')el=el[brother];return $(el);},getPrevious:function(){return this.walk('previous');},getNext:function(){return this.walk('next');},getFirst:function(){return this.walk('next','firstChild');},getLast:function(){return this.walk('previous','lastChild');},getParent:function(){return $(this.parentNode);},getChildren:function(){return $$(this.childNodes);},hasChild:function(el){return!!$A(this.getElementsByTagName('*')).contains(el);},getProperty:function(property){var index=Element.Properties[property];if(index)return this[index];var flag=Element.PropertiesIFlag[property]||0;if(!window.ie||flag)return this.getAttribute(property,flag);var node=this.attributes[property];return(node)?node.nodeValue:null;},removeProperty:function(property){var index=Element.Properties[property];if(index)this[index]='';else this.removeAttribute(property);return this;},getProperties:function(){return Element.getMany(this,'getProperty',arguments);},setProperty:function(property,value){var index=Element.Properties[property];if(index)this[index]=value;else this.setAttribute(property,value);return this;},setProperties:function(source){return Element.setMany(this,'setProperty',source);},setHTML:function(){this.innerHTML=$A(arguments).join('');return this;},setText:function(text){var tag=this.getTag();if(['style','script'].contains(tag)){if(window.ie){if(tag=='style')this.styleSheet.cssText=text;else if(tag=='script')this.setProperty('text',text);return this;}else{this.removeChild(this.firstChild);return this.appendText(text);}}
this[$defined(this.innerText)?'innerText':'textContent']=text;return this;},getText:function(){var tag=this.getTag();if(['style','script'].contains(tag)){if(window.ie){if(tag=='style')return this.styleSheet.cssText;else if(tag=='script')return this.getProperty('text');}else{return this.innerHTML;}}
return($pick(this.innerText,this.textContent));},getTag:function(){return this.tagName.toLowerCase();},empty:function(){Garbage.trash(this.getElementsByTagName('*'));return this.setHTML('');}});Element.fixStyle=function(property,result,element){if($chk(parseInt(result)))return result;if(['height','width'].contains(property)){var values=(property=='width')?['left','right']:['top','bottom'];var size=0;values.each(function(value){size+=element.getStyle('border-'+value+'-width').toInt()+element.getStyle('padding-'+value).toInt();});return element['offset'+property.capitalize()]-size+'px';}else if(property.test(/border(.+)Width|margin|padding/)){return'0px';}
return result;};Element.Styles={'border':[],'padding':[],'margin':[]};['Top','Right','Bottom','Left'].each(function(direction){for(var style in Element.Styles)Element.Styles[style].push(style+direction);});Element.borderShort=['borderWidth','borderStyle','borderColor'];Element.getMany=function(el,method,keys){var result={};$each(keys,function(key){result[key]=el[method](key);});return result;};Element.setMany=function(el,method,pairs){for(var key in pairs)el[method](key,pairs[key]);return el;};Element.Properties=new Abstract({'class':'className','for':'htmlFor','colspan':'colSpan','rowspan':'rowSpan','accesskey':'accessKey','tabindex':'tabIndex','maxlength':'maxLength','readonly':'readOnly','frameborder':'frameBorder','value':'value','disabled':'disabled','checked':'checked','multiple':'multiple','selected':'selected'});Element.PropertiesIFlag={'href':2,'src':2};Element.Methods={Listeners:{addListener:function(type,fn){if(this.addEventListener)this.addEventListener(type,fn,false);else this.attachEvent('on'+type,fn);return this;},removeListener:function(type,fn){if(this.removeEventListener)this.removeEventListener(type,fn,false);else this.detachEvent('on'+type,fn);return this;}}};window.extend(Element.Methods.Listeners);document.extend(Element.Methods.Listeners);Element.extend(Element.Methods.Listeners);var Garbage={elements:[],collect:function(el){if(!el.$tmp){Garbage.elements.push(el);el.$tmp={'opacity':1};}
return el;},trash:function(elements){for(var i=0,j=elements.length,el;i<j;i++){if(!(el=elements[i])||!el.$tmp)continue;if(el.$events)el.fireEvent('trash').removeEvents();for(var p in el.$tmp)el.$tmp[p]=null;for(var d in Element.prototype)el[d]=null;Garbage.elements[Garbage.elements.indexOf(el)]=null;el.htmlElement=el.$tmp=el=null;}
Garbage.elements.remove(null);},empty:function(){Garbage.collect(window);Garbage.collect(document);Garbage.trash(Garbage.elements);}};window.addListener('beforeunload',function(){window.addListener('unload',Garbage.empty);if(window.ie)window.addListener('unload',CollectGarbage);});var Event=new Class({initialize:function(event){if(event&&event.$extended)return event;this.$extended=true;event=event||window.event;this.event=event;this.type=event.type;this.target=event.target||event.srcElement;if(this.target.nodeType==3)this.target=this.target.parentNode;this.shift=event.shiftKey;this.control=event.ctrlKey;this.alt=event.altKey;this.meta=event.metaKey;if(['DOMMouseScroll','mousewheel'].contains(this.type)){this.wheel=(event.wheelDelta)?event.wheelDelta/120:-(event.detail||0)/3;}else if(this.type.contains('key')){this.code=event.which||event.keyCode;for(var name in Event.keys){if(Event.keys[name]==this.code){this.key=name;break;}}
if(this.type=='keydown'){var fKey=this.code-111;if(fKey>0&&fKey<13)this.key='f'+fKey;}
this.key=this.key||String.fromCharCode(this.code).toLowerCase();}else if(this.type.test(/(click|mouse|menu)/)){this.page={'x':event.pageX||event.clientX+document.documentElement.scrollLeft,'y':event.pageY||event.clientY+document.documentElement.scrollTop};this.client={'x':event.pageX?event.pageX-window.pageXOffset:event.clientX,'y':event.pageY?event.pageY-window.pageYOffset:event.clientY};this.rightClick=(event.which==3)||(event.button==2);switch(this.type){case'mouseover':this.relatedTarget=event.relatedTarget||event.fromElement;break;case'mouseout':this.relatedTarget=event.relatedTarget||event.toElement;}
this.fixRelatedTarget();}
return this;},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;}});Event.fix={relatedTarget:function(){if(this.relatedTarget&&this.relatedTarget.nodeType==3)this.relatedTarget=this.relatedTarget.parentNode;},relatedTargetGecko:function(){try{Event.fix.relatedTarget.call(this);}catch(e){this.relatedTarget=this.target;}}};Event.prototype.fixRelatedTarget=(window.gecko)?Event.fix.relatedTargetGecko:Event.fix.relatedTarget;Event.keys=new Abstract({'enter':13,'up':38,'down':40,'left':37,'right':39,'esc':27,'space':32,'backspace':8,'tab':9,'delete':46});Element.Methods.Events={addEvent:function(type,fn){this.$events=this.$events||{};this.$events[type]=this.$events[type]||{'keys':[],'values':[]};if(this.$events[type].keys.contains(fn))return this;this.$events[type].keys.push(fn);var realType=type;var custom=Element.Events[type];if(custom){if(custom.add)custom.add.call(this,fn);if(custom.map)fn=custom.map;if(custom.type)realType=custom.type;}
if(!this.addEventListener)fn=fn.create({'bind':this,'event':true});this.$events[type].values.push(fn);return(Element.NativeEvents.contains(realType))?this.addListener(realType,fn):this;},removeEvent:function(type,fn){if(!this.$events||!this.$events[type])return this;var pos=this.$events[type].keys.indexOf(fn);if(pos==-1)return this;var key=this.$events[type].keys.splice(pos,1)[0];var value=this.$events[type].values.splice(pos,1)[0];var custom=Element.Events[type];if(custom){if(custom.remove)custom.remove.call(this,fn);if(custom.type)type=custom.type;}
return(Element.NativeEvents.contains(type))?this.removeListener(type,value):this;},addEvents:function(source){return Element.setMany(this,'addEvent',source);},removeEvents:function(type){if(!this.$events)return this;if(!type){for(var evType in this.$events)this.removeEvents(evType);this.$events=null;}else if(this.$events[type]){this.$events[type].keys.each(function(fn){this.removeEvent(type,fn);},this);this.$events[type]=null;}
return this;},fireEvent:function(type,args,delay){if(this.$events&&this.$events[type]){this.$events[type].keys.each(function(fn){fn.create({'bind':this,'delay':delay,'arguments':args})();},this);}
return this;},cloneEvents:function(from,type){if(!from.$events)return this;if(!type){for(var evType in from.$events)this.cloneEvents(from,evType);}else if(from.$events[type]){from.$events[type].keys.each(function(fn){this.addEvent(type,fn);},this);}
return this;}};window.extend(Element.Methods.Events);document.extend(Element.Methods.Events);Element.extend(Element.Methods.Events);Element.Events=new Abstract({'mouseenter':{type:'mouseover',map:function(event){event=new Event(event);if(event.relatedTarget!=this&&!this.hasChild(event.relatedTarget))this.fireEvent('mouseenter',event);}},'mouseleave':{type:'mouseout',map:function(event){event=new Event(event);if(event.relatedTarget!=this&&!this.hasChild(event.relatedTarget))this.fireEvent('mouseleave',event);}},'mousewheel':{type:(window.gecko)?'DOMMouseScroll':'mousewheel'}});Element.NativeEvents=['click','dblclick','mouseup','mousedown','mousewheel','DOMMouseScroll','mouseover','mouseout','mousemove','keydown','keypress','keyup','load','unload','beforeunload','resize','move','focus','blur','change','submit','reset','select','error','abort','contextmenu','scroll'];Function.extend({bindWithEvent:function(bind,args){return this.create({'bind':bind,'arguments':args,'event':Event});}});Elements.extend({filterByTag:function(tag){return new Elements(this.filter(function(el){return(Element.getTag(el)==tag);}));},filterByClass:function(className,nocash){var elements=this.filter(function(el){return(el.className&&el.className.contains(className,' '));});return(nocash)?elements:new Elements(elements);},filterById:function(id,nocash){var elements=this.filter(function(el){return(el.id==id);});return(nocash)?elements:new Elements(elements);},filterByAttribute:function(name,operator,value,nocash){var elements=this.filter(function(el){var current=Element.getProperty(el,name);if(!current)return false;if(!operator)return true;switch(operator){case'=':return(current==value);case'*=':return(current.contains(value));case'^=':return(current.substr(0,value.length)==value);case'$=':return(current.substr(current.length-value.length)==value);case'!=':return(current!=value);case'~=':return current.contains(value,' ');}
return false;});return(nocash)?elements:new Elements(elements);}});function $E(selector,filter){return($(filter)||document).getElement(selector);};function $ES(selector,filter){return($(filter)||document).getElementsBySelector(selector);};$$.shared={'regexp':/^(\w*|\*)(?:#([\w-]+)|\.([\w-]+))?(?:\[(\w+)(?:([!*^$]?=)["']?([^"'\]]*)["']?)?])?$/,'xpath':{getParam:function(items,context,param,i){var temp=[context.namespaceURI?'xhtml:':'',param[1]];if(param[2])temp.push('[@id="',param[2],'"]');if(param[3])temp.push('[contains(concat(" ", @class, " "), " ',param[3],' ")]');if(param[4]){if(param[5]&&param[6]){switch(param[5]){case'*=':temp.push('[contains(@',param[4],', "',param[6],'")]');break;case'^=':temp.push('[starts-with(@',param[4],', "',param[6],'")]');break;case'$=':temp.push('[substring(@',param[4],', string-length(@',param[4],') - ',param[6].length,' + 1) = "',param[6],'"]');break;case'=':temp.push('[@',param[4],'="',param[6],'"]');break;case'!=':temp.push('[@',param[4],'!="',param[6],'"]');}}else{temp.push('[@',param[4],']');}}
items.push(temp.join(''));return items;},getItems:function(items,context,nocash){var elements=[];var xpath=document.evaluate('.//'+items.join('//'),context,$$.shared.resolver,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);for(var i=0,j=xpath.snapshotLength;i<j;i++)elements.push(xpath.snapshotItem(i));return(nocash)?elements:new Elements(elements.map($));}},'normal':{getParam:function(items,context,param,i){if(i==0){if(param[2]){var el=context.getElementById(param[2]);if(!el||((param[1]!='*')&&(Element.getTag(el)!=param[1])))return false;items=[el];}else{items=$A(context.getElementsByTagName(param[1]));}}else{items=$$.shared.getElementsByTagName(items,param[1]);if(param[2])items=Elements.filterById(items,param[2],true);}
if(param[3])items=Elements.filterByClass(items,param[3],true);if(param[4])items=Elements.filterByAttribute(items,param[4],param[5],param[6],true);return items;},getItems:function(items,context,nocash){return(nocash)?items:$$.unique(items);}},resolver:function(prefix){return(prefix=='xhtml')?'http://www.w3.org/1999/xhtml':false;},getElementsByTagName:function(context,tagName){var found=[];for(var i=0,j=context.length;i<j;i++)found.extend(context[i].getElementsByTagName(tagName));return found;}};$$.shared.method=(window.xpath)?'xpath':'normal';Element.Methods.Dom={getElements:function(selector,nocash){var items=[];selector=selector.trim().split(' ');for(var i=0,j=selector.length;i<j;i++){var sel=selector[i];var param=sel.match($$.shared.regexp);if(!param)break;param[1]=param[1]||'*';var temp=$$.shared[$$.shared.method].getParam(items,this,param,i);if(!temp)break;items=temp;}
return $$.shared[$$.shared.method].getItems(items,this,nocash);},getElement:function(selector){return $(this.getElements(selector,true)[0]||false);},getElementsBySelector:function(selector,nocash){var elements=[];selector=selector.split(',');for(var i=0,j=selector.length;i<j;i++)elements=elements.concat(this.getElements(selector[i],true));return(nocash)?elements:$$.unique(elements);}};Element.extend({getElementById:function(id){var el=document.getElementById(id);if(!el)return false;for(var parent=el.parentNode;parent!=this;parent=parent.parentNode){if(!parent)return false;}
return el;},getElementsByClassName:function(className){return this.getElements('.'+className);}});document.extend(Element.Methods.Dom);Element.extend(Element.Methods.Dom);Element.extend({getValue:function(){switch(this.getTag()){case'select':var values=[];$each(this.options,function(option){if(option.selected)values.push($pick(option.value,option.text));});return(this.multiple)?values:values[0];case'input':if(!(this.checked&&['checkbox','radio'].contains(this.type))&&!['hidden','text','password'].contains(this.type))break;case'textarea':return this.value;}
return false;},getFormElements:function(){return $$(this.getElementsByTagName('input'),this.getElementsByTagName('select'),this.getElementsByTagName('textarea'));},toQueryString:function(){var queryString=[];this.getFormElements().each(function(el){var name=el.name;var value=el.getValue();if(value===false||!name||el.disabled)return;var qs=function(val){queryString.push(name+'='+encodeURIComponent(val));};if($type(value)=='array')value.each(qs);else qs(value);});return queryString.join('&');}});Element.extend({scrollTo:function(x,y){this.scrollLeft=x;this.scrollTop=y;},getSize:function(){return{'scroll':{'x':this.scrollLeft,'y':this.scrollTop},'size':{'x':this.offsetWidth,'y':this.offsetHeight},'scrollSize':{'x':this.scrollWidth,'y':this.scrollHeight}};},getPosition:function(overflown){overflown=overflown||[];var el=this,left=0,top=0;do{left+=el.offsetLeft||0;top+=el.offsetTop||0;el=el.offsetParent;}while(el);overflown.each(function(element){left-=element.scrollLeft||0;top-=element.scrollTop||0;});return{'x':left,'y':top};},getTop:function(overflown){return this.getPosition(overflown).y;},getLeft:function(overflown){return this.getPosition(overflown).x;},getCoordinates:function(overflown){var position=this.getPosition(overflown);var obj={'width':this.offsetWidth,'height':this.offsetHeight,'left':position.x,'top':position.y};obj.right=obj.left+obj.width;obj.bottom=obj.top+obj.height;return obj;}});Element.Events.domready={add:function(fn){if(window.loaded){fn.call(this);return;}
var domReady=function(){if(window.loaded)return;window.loaded=true;window.timer=$clear(window.timer);this.fireEvent('domready');}.bind(this);if(document.readyState&&window.webkit){window.timer=function(){if(['loaded','complete'].contains(document.readyState))domReady();}.periodical(50);}else if(document.readyState&&window.ie){if(!$('ie_ready')){var src=(window.location.protocol=='https:')?'://0':'javascript:void(0)';document.write('<script id="ie_ready" defer src="'+src+'"><\/script>');$('ie_ready').onreadystatechange=function(){if(this.readyState=='complete')domReady();};}}else{window.addListener("load",domReady);document.addListener("DOMContentLoaded",domReady);}}};window.onDomReady=function(fn){return this.addEvent('domready',fn);};window.extend({getWidth:function(){if(this.webkit419)return this.innerWidth;if(this.opera)return document.body.clientWidth;return document.documentElement.clientWidth;},getHeight:function(){if(this.webkit419)return this.innerHeight;if(this.opera)return document.body.clientHeight;return document.documentElement.clientHeight;},getScrollWidth:function(){if(this.ie)return Math.max(document.documentElement.offsetWidth,document.documentElement.scrollWidth);if(this.webkit)return document.body.scrollWidth;return document.documentElement.scrollWidth;},getScrollHeight:function(){if(this.ie)return Math.max(document.documentElement.offsetHeight,document.documentElement.scrollHeight);if(this.webkit)return document.body.scrollHeight;return document.documentElement.scrollHeight;},getScrollLeft:function(){return this.pageXOffset||document.documentElement.scrollLeft;},getScrollTop:function(){return this.pageYOffset||document.documentElement.scrollTop;},getSize:function(){return{'size':{'x':this.getWidth(),'y':this.getHeight()},'scrollSize':{'x':this.getScrollWidth(),'y':this.getScrollHeight()},'scroll':{'x':this.getScrollLeft(),'y':this.getScrollTop()}};},getPosition:function(){return{'x':0,'y':0};}});var Fx={};Fx.Base=new Class({options:{onStart:Class.empty,onComplete:Class.empty,onCancel:Class.empty,transition:function(p){return-(Math.cos(Math.PI*p)-1)/2;},duration:500,unit:'px',wait:true,fps:50},initialize:function(options){this.element=this.element||null;this.setOptions(options);if(this.options.initialize)this.options.initialize.call(this);},step:function(){var time=$time();if(time<this.time+this.options.duration){this.delta=this.options.transition((time-this.time)/this.options.duration);this.setNow();this.increase();}else{this.stop(true);this.set(this.to);this.fireEvent('onComplete',this.element,10);this.callChain();}},set:function(to){this.now=to;this.increase();return this;},setNow:function(){this.now=this.compute(this.from,this.to);},compute:function(from,to){return(to-from)*this.delta+from;},start:function(from,to){if(!this.options.wait)this.stop();else if(this.timer)return this;this.from=from;this.to=to;this.change=this.to-this.from;this.time=$time();this.timer=this.step.periodical(Math.round(1000/this.options.fps),this);this.fireEvent('onStart',this.element);return this;},stop:function(end){if(!this.timer)return this;this.timer=$clear(this.timer);if(!end)this.fireEvent('onCancel',this.element);return this;},custom:function(from,to){return this.start(from,to);},clearTimer:function(end){return this.stop(end);}});Fx.Base.implement(new Chain,new Events,new Options);Fx.CSS={select:function(property,to){if(property.test(/color/i))return this.Color;var type=$type(to);if((type=='array')||(type=='string'&&to.contains(' ')))return this.Multi;return this.Single;},parse:function(el,property,fromTo){if(!fromTo.push)fromTo=[fromTo];var from=fromTo[0],to=fromTo[1];if(!$chk(to)){to=from;from=el.getStyle(property);}
var css=this.select(property,to);return{'from':css.parse(from),'to':css.parse(to),'css':css};}};Fx.CSS.Single={parse:function(value){return parseFloat(value);},getNow:function(from,to,fx){return fx.compute(from,to);},getValue:function(value,unit,property){if(unit=='px'&&property!='opacity')value=Math.round(value);return value+unit;}};Fx.CSS.Multi={parse:function(value){return value.push?value:value.split(' ').map(function(v){return parseFloat(v);});},getNow:function(from,to,fx){var now=[];for(var i=0;i<from.length;i++)now[i]=fx.compute(from[i],to[i]);return now;},getValue:function(value,unit,property){if(unit=='px'&&property!='opacity')value=value.map(Math.round);return value.join(unit+' ')+unit;}};Fx.CSS.Color={parse:function(value){return value.push?value:value.hexToRgb(true);},getNow:function(from,to,fx){var now=[];for(var i=0;i<from.length;i++)now[i]=Math.round(fx.compute(from[i],to[i]));return now;},getValue:function(value){return'rgb('+value.join(',')+')';}};Fx.Style=Fx.Base.extend({initialize:function(el,property,options){this.element=$(el);this.property=property;this.parent(options);},hide:function(){return this.set(0);},setNow:function(){this.now=this.css.getNow(this.from,this.to,this);},set:function(to){this.css=Fx.CSS.select(this.property,to);return this.parent(this.css.parse(to));},start:function(from,to){if(this.timer&&this.options.wait)return this;var parsed=Fx.CSS.parse(this.element,this.property,[from,to]);this.css=parsed.css;return this.parent(parsed.from,parsed.to);},increase:function(){this.element.setStyle(this.property,this.css.getValue(this.now,this.options.unit,this.property));}});Element.extend({effect:function(property,options){return new Fx.Style(this,property,options);}});Fx.Scroll=Fx.Base.extend({options:{overflown:[],offset:{'x':0,'y':0},wheelStops:true},initialize:function(element,options){this.now=[];this.element=$(element);this.bound={'stop':this.stop.bind(this,false)};this.parent(options);if(this.options.wheelStops){this.addEvent('onStart',function(){document.addEvent('mousewheel',this.bound.stop);}.bind(this));this.addEvent('onComplete',function(){document.removeEvent('mousewheel',this.bound.stop);}.bind(this));}},setNow:function(){for(var i=0;i<2;i++)this.now[i]=this.compute(this.from[i],this.to[i]);},scrollTo:function(x,y){if(this.timer&&this.options.wait)return this;var el=this.element.getSize();var values={'x':x,'y':y};for(var z in el.size){var max=el.scrollSize[z]-el.size[z];if($chk(values[z]))values[z]=($type(values[z])=='number')?values[z].limit(0,max):max;else values[z]=el.scroll[z];values[z]+=this.options.offset[z];}
return this.start([el.scroll.x,el.scroll.y],[values.x,values.y]);},toTop:function(){return this.scrollTo(false,0);},toBottom:function(){return this.scrollTo(false,'full');},toLeft:function(){return this.scrollTo(0,false);},toRight:function(){return this.scrollTo('full',false);},toElement:function(el){var parent=this.element.getPosition(this.options.overflown);var target=$(el).getPosition(this.options.overflown);return this.scrollTo(target.x-parent.x,target.y-parent.y);},increase:function(){this.element.scrollTo(this.now[0],this.now[1]);}});var Drag={};Drag.Base=new Class({options:{handle:false,unit:'px',onStart:Class.empty,onBeforeStart:Class.empty,onComplete:Class.empty,onSnap:Class.empty,onDrag:Class.empty,limit:false,modifiers:{x:'left',y:'top'},grid:false,snap:6},initialize:function(el,options){this.setOptions(options);this.element=$(el);this.handle=$(this.options.handle)||this.element;this.mouse={'now':{},'pos':{}};this.value={'start':{},'now':{}};this.bound={'start':this.start.bindWithEvent(this),'check':this.check.bindWithEvent(this),'drag':this.drag.bindWithEvent(this),'stop':this.stop.bind(this)};this.attach();if(this.options.initialize)this.options.initialize.call(this);},attach:function(){this.handle.addEvent('mousedown',this.bound.start);return this;},detach:function(){this.handle.removeEvent('mousedown',this.bound.start);return this;},start:function(event){this.fireEvent('onBeforeStart',this.element);this.mouse.start=event.page;var limit=this.options.limit;this.limit={'x':[],'y':[]};for(var z in this.options.modifiers){if(!this.options.modifiers[z])continue;this.value.now[z]=this.element.getStyle(this.options.modifiers[z]).toInt();this.mouse.pos[z]=event.page[z]-this.value.now[z];if(limit&&limit[z]){for(var i=0;i<2;i++){if($chk(limit[z][i]))this.limit[z][i]=($type(limit[z][i])=='function')?limit[z][i]():limit[z][i];}}}
if($type(this.options.grid)=='number')this.options.grid={'x':this.options.grid,'y':this.options.grid};document.addListener('mousemove',this.bound.check);document.addListener('mouseup',this.bound.stop);if(this.options.editor){rte.Events.addEvent("mouseup",this.bound.stop);}
this.fireEvent('onStart',this.element);event.stop();},check:function(event){var distance=Math.round(Math.sqrt(Math.pow(event.page.x-this.mouse.start.x,2)+Math.pow(event.page.y-this.mouse.start.y,2)));if(distance>this.options.snap){document.removeListener('mousemove',this.bound.check);document.addListener('mousemove',this.bound.drag);if(this.options.editor)
rte.Events.addEvent("mousemove",this.bound.drag);this.drag(event);this.fireEvent('onSnap',this.element);}
event.stop();},drag:function(event){this.out=false;this.mouse.now=event.page;if(event.event.relativeTo&&event.event.relativeTo){var el=$(event.event.relativeTo);var pos=el.getPosition([$('note-scroll')]);this.mouse.now.x+=pos.x;this.mouse.now.y+=pos.y;}
for(var z in this.options.modifiers){if(!this.options.modifiers[z])continue;this.value.now[z]=this.mouse.now[z]-this.mouse.pos[z];if(this.limit[z]){if($chk(this.limit[z][1])&&(this.value.now[z]>this.limit[z][1])){this.value.now[z]=this.limit[z][1];this.out=true;}else if($chk(this.limit[z][0])&&(this.value.now[z]<this.limit[z][0])){this.value.now[z]=this.limit[z][0];this.out=true;}}
if(this.options.grid[z])this.value.now[z]-=(this.value.now[z]%this.options.grid[z]);this.element.setStyle(this.options.modifiers[z],this.value.now[z]+this.options.unit);}
this.fireEvent('onDrag',this.element);event.stop();},stop:function(fireComplete){document.removeListener('mousemove',this.bound.check);document.removeListener('mousemove',this.bound.drag);document.removeListener('mouseup',this.bound.stop);if(this.options.editor){rte.Events.removeEvent('mousemove',this.bound.drag);rte.Events.removeEvent("mouseup",this.bound.stop);}
if(fireComplete!=false)
this.fireEvent('onComplete',this.element);}});Drag.Base.implement(new Events,new Options);Element.extend({makeResizable:function(options){return new Drag.Base(this,$merge({modifiers:{x:'width',y:'height'}},options));}});Drag.Move=Drag.Base.extend({options:{droppables:[],container:false,overflown:[]},initialize:function(el,options){this.setOptions(options);this.element=$(el);this.droppables=$$(this.options.droppables);this.container=$(this.options.container);this.position={'element':this.element.getStyle('position'),'container':false};if(this.container)this.position.container=this.container.getStyle('position');if(!['relative','absolute','fixed'].contains(this.position.element))this.position.element='absolute';var top=this.element.getStyle('top').toInt();var left=this.element.getStyle('left').toInt();if(this.position.element=='absolute'&&!['relative','absolute','fixed'].contains(this.position.container)){top=$chk(top)?top:this.element.getTop(this.options.overflown);left=$chk(left)?left:this.element.getLeft(this.options.overflown);}else{top=$chk(top)?top:0;left=$chk(left)?left:0;}
this.parent(this.element);},start:function(event){this.overed=null;if(this.container){var cont=this.container.getCoordinates();var el=this.element.getCoordinates();if(this.position.element=='absolute'&&!['relative','absolute','fixed'].contains(this.position.container)){this.options.limit={'x':[cont.left,cont.right-el.width],'y':[cont.top,cont.bottom-el.height]};}else{this.options.limit={'y':[0,cont.height-el.height],'x':[0,cont.width-el.width]};}}
this.parent(event);},drag:function(event){this.parent(event);var overed=this.out?false:this.droppables.filter(this.checkAgainst,this).getLast();if(this.overed!=overed){if(this.overed)this.overed.fireEvent('leave',[this.element,this]);this.overed=overed?overed.fireEvent('over',[this.element,this]):null;}
return this;},checkAgainst:function(el){if(el==this.element)return false;el=el.getCoordinates(el.overflow);var now=this.mouse.now;return(now.x>el.left&&now.x<el.right&&now.y<el.bottom&&now.y>el.top);},stop:function(){if(this.overed&&!this.out)this.overed.fireEvent('drop',[this.element,this]);else this.element.fireEvent('emptydrop',this);this.parent();return this;}});Element.extend({makeDraggable:function(options){return new Drag.Move(this,options);}});var XHR=new Class({options:{method:'post',async:true,onRequest:Class.empty,onSuccess:Class.empty,onFailure:Class.empty,urlEncoded:true,encoding:'utf-8',autoCancel:false,headers:{}},setTransport:function(){this.transport=(window.XMLHttpRequest)?new XMLHttpRequest():(window.ie?new ActiveXObject('Microsoft.XMLHTTP'):false);return this;},initialize:function(options){this.setTransport().setOptions(options);this.options.isSuccess=this.options.isSuccess||this.isSuccess;this.headers={};if(this.options.urlEncoded&&this.options.method=='post'){var encoding=(this.options.encoding)?'; charset='+this.options.encoding:'';this.setHeader('Content-type','application/x-www-form-urlencoded'+encoding);}
if(this.options.initialize)this.options.initialize.call(this);},onStateChange:function(){if(this.transport.readyState!=4||!this.running)return;this.running=false;var status=0;try{status=this.transport.status;}catch(e){};if(this.options.isSuccess.call(this,status))this.onSuccess();else this.onFailure();this.transport.onreadystatechange=Class.empty;},isSuccess:function(status){return((status>=200)&&(status<300));},onSuccess:function(){this.response={'text':this.transport.responseText,'xml':this.transport.responseXML};this.fireEvent('onSuccess',[this.response.text,this.response.xml]);this.callChain();},onFailure:function(){this.fireEvent('onFailure',this.transport);},setHeader:function(name,value){this.headers[name]=value;return this;},send:function(url,data){if(this.options.autoCancel)this.cancel();else if(this.running)return this;this.running=true;if(data&&this.options.method=='get'){url=url+(url.contains('?')?'&':'?')+data;data=null;}
this.transport.open(this.options.method.toUpperCase(),url,this.options.async);this.transport.onreadystatechange=this.onStateChange.bind(this);if((this.options.method=='post')&&this.transport.overrideMimeType)this.setHeader('Connection','close');$extend(this.headers,this.options.headers);for(var type in this.headers)try{this.transport.setRequestHeader(type,this.headers[type]);}catch(e){};this.fireEvent('onRequest');this.transport.send($pick(data,null));return this;},cancel:function(){if(!this.running)return this;this.running=false;this.transport.abort();this.transport.onreadystatechange=Class.empty;this.setTransport();this.fireEvent('onCancel');return this;}});XHR.implement(new Chain,new Events,new Options);var Ajax=XHR.extend({options:{data:null,update:null,onComplete:Class.empty,evalScripts:false,evalResponse:false},initialize:function(url,options){this.addEvent('onSuccess',this.onComplete);this.setOptions(options);this.options.data=this.options.data||this.options.postBody;if(!['post','get'].contains(this.options.method)){this._method='_method='+this.options.method;this.options.method='post';}
this.parent();this.setHeader('X-Requested-With','XMLHttpRequest');this.setHeader('Accept','text/javascript, text/html, application/xml, text/xml, */*');this.url=url;},onComplete:function(){if(this.options.update)$(this.options.update).empty().setHTML(this.response.text);if(this.options.evalScripts||this.options.evalResponse)this.evalScripts();this.fireEvent('onComplete',[this.response.text,this.response.xml],20);},request:function(data){data=data||this.options.data;switch($type(data)){case'element':data=$(data).toQueryString();break;case'object':data=Object.toQueryString(data);}
if(this._method)data=(data)?[this._method,data].join('&'):this._method;return this.send(this.url,data);},evalScripts:function(){var script,scripts;if(this.options.evalResponse||(/(ecma|java)script/).test(this.getHeader('Content-type')))scripts=this.response.text;else{scripts=[];var regexp=/<script[^>]*>([\s\S]*?)<\/script>/gi;while((script=regexp.exec(this.response.text)))scripts.push(script[1]);scripts=scripts.join('\n');}
if(scripts)(window.execScript)?window.execScript(scripts):window.setTimeout(scripts,0);},getHeader:function(name){try{return this.transport.getResponseHeader(name);}catch(e){};return null;}});Object.toQueryString=function(source){var queryString=[];for(var property in source)queryString.push(encodeURIComponent(property)+'='+encodeURIComponent(source[property]));return queryString.join('&');};Element.extend({send:function(options){return new Ajax(this.getProperty('action'),$merge({data:this.toQueryString()},options,{method:'post'})).request();}});var Cookie=new Abstract({options:{domain:false,path:false,duration:false,secure:false},set:function(key,value,options){options=$merge(this.options,options);value=encodeURIComponent(value);if(options.domain)value+='; domain='+options.domain;if(options.path)value+='; path='+options.path;if(options.duration){var date=new Date();date.setTime(date.getTime()+options.duration*24*60*60*1000);value+='; expires='+date.toGMTString();}
if(options.secure)value+='; secure';document.cookie=key+'='+value;return $extend(options,{'key':key,'value':value});},get:function(key){var value=document.cookie.match('(?:^|;)\\s*'+key.escapeRegExp()+'=([^;]*)');return value?decodeURIComponent(value[1]):false;},remove:function(cookie,options){if($type(cookie)=='object')this.set(cookie.key,'',$merge(cookie,{duration:-1}));else this.set(cookie,'',$merge(options,{duration:-1}));}});var Json={toString:function(obj){switch($type(obj)){case'string':return'"'+obj.replace(/(["\\])/g,'\\$1')+'"';case'array':return'['+obj.map(Json.toString).join(',')+']';case'object':var string=[];for(var property in obj)string.push(Json.toString(property)+':'+Json.toString(obj[property]));return'{'+string.join(',')+'}';case'number':if(isFinite(obj))break;case false:return'null';}
return String(obj);},evaluate:function(str,secure){return(($type(str)!='string')||(secure&&!str.test(/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/)))?null:eval('('+str+')');}};var Scroller=new Class({options:{area:20,velocity:1,onChange:function(x,y){this.element.scrollTo(x,y);}},initialize:function(element,options){this.setOptions(options);this.element=$(element);this.mousemover=([window,document].contains(element))?$(document.body):this.element;},start:function(){this.coord=this.getCoords.bindWithEvent(this);this.mousemover.addListener('mousemove',this.coord);},stop:function(){this.mousemover.removeListener('mousemove',this.coord);this.timer=$clear(this.timer);},getCoords:function(event){this.page=(this.element==window)?event.client:event.page;if(!this.timer)this.timer=this.scroll.periodical(50,this);},scroll:function(){var el=this.element.getSize();var pos=this.element.getPosition();var change={'x':0,'y':0};for(var z in this.page){if(this.page[z]<(this.options.area+pos[z])&&el.scroll[z]!=0)
change[z]=(this.page[z]-this.options.area-pos[z])*this.options.velocity;else if(this.page[z]+this.options.area>(el.size[z]+pos[z])&&el.scroll[z]+el.size[z]!=el.scrollSize[z])
change[z]=(this.page[z]-el.size[z]+this.options.area-pos[z])*this.options.velocity;}
if(this.options.verticalOnly)
change.x=0;if(change.y||change.x)this.fireEvent('onChange',[el.scroll.x+change.x,el.scroll.y+change.y]);}});Scroller.implement(new Events,new Options);Class.prototype.extendStatic=function(methods){for(m in methods)this[m]=methods[m];};Array.extend({last:function(){return this[this.length-1];}});Array.prototype.oldMap=Array.prototype.map;Array.prototype.map=function(fn,bind){if(typeof fn=="string"){var fnName=fn;fn=function(e){return e[fnName]();};}
return this.oldMap(fn,bind);};window.extend({getCoordinates:function(){var o={'width':this.getWidth(),'height':this.getHeight(),'left':0,'top':0};o.right=o.left+o.width;o.bottom=o.top+o.height;return o;}});window.iphone=navigator.userAgent.contains('iPhone');Element.extend({getWidth:function(){return this.offsetWidth;},getHeight:function(){return this.offsetHeight;},hide:function(){this.setStyle('display','none');},show:function(){this.setStyle('display','');},toggle:function(arg){if(!this.isDisplayed()&&arg!=false)
this.show();else
this.hide();},setDisplayed:function(visible){visible?this.show():this.hide();},isDisplayed:function(){return this.style.display!="none";},focusFirstInput:function(){var f=this.getElementsByTagName("INPUT")[0];if(f)f.focus();},toggleWithFade:function(duration,display){display=display||this.hidden();duration=typeof(duration)!="number"?750:duration;display?this.fadeIn(duration):this.fadeOut(duration);return false;},hidden:function(){return this.style.display=="none";},fadeIn:function(duration){var opacity=this.getStyle("opacity");if(opacity==1){opacity=0;this.setStyle("opacity",opacity);}
this.style.display='';if(this.fade)this.fade.stop();this.fade=this.effect('opacity',{duration:duration||750,wait:false}).start(opacity,.99);},fadeOut:function(duration){if(this.fade)this.fade.stop();this.fade=this.effect('opacity',{duration:duration||750,wait:false});this.fade.start(this.style.opacity||1,0).chain(function(){this.hide();}.bind(this));},scrollUntilVisible:function(childElement,duration){childElement=$(childElement);var size=this.getSize();var top=this.getTop();var bottom=size.size.y+top+size.scroll.y;var child=childElement.getCoordinates();var clipsBottom=(bottom<child.height+child.top);var clipsTop=(top+size.scroll.y>child.top);duration=(duration==null)?300:duration;var scroller=duration==0?this:new Fx.Scroll(this,{duration:duration});if(clipsTop){scroller.toElementWithOffset(childElement,top);}else if(clipsBottom){var scrollPadding=10;if(size.size.y>child.height+scrollPadding){scroller.scrollTo(0,child.top-top-(size.size.y-child.height)+scrollPadding);}else{scroller.toElementWithOffset(childElement,top);}}},toElementWithOffset:function(el,offset){var left=this.getLeft()-$(el).getLeft();return this.scrollTo(left,$(el).getTop()-offset);}});if(Fx.Scroll){Fx.Scroll=Fx.Scroll.extend({toElementWithOffset:function(el,offset){var left=this.element.getLeft()-$(el).getLeft();return this.scrollTo(left,$(el).getTop()-offset);}});}
window.toElementWithOffset=function(element,offset){this.scrollTo(element.getLeft(),element.getTop()-offset);};Element.update=function(id,contents){$(id).innerHTML=contents;};util={timeInSeconds:function(){return Math.round((new Date()).getTime()/1000);},keys:function(obj){var a=[];for(k in obj)a.push(k);return a;},escapeHTML:function(html){return html.replace(/</g,"&lt;").replace(/>/g,'&gt;');},unescapeHTML:function(text){return text.replace(/&lt;/g,"<").replace(/&gt;/g,">");},attach:function(element,ev,fn){if(element.addEventListener)
element.addEventListener(ev,fn,false);else
element.attachEvent('on'+ev,fn);},mod:function(i,limit,amt){i+=amt;return i<0?limit+(i%limit):i%limit;},disableIECaching:function(){if(document.execCommand){try{document.execCommand("BackgroundImageCache",false,true);}
catch(e){}}}};util.disableIECaching();function extendIfAbsent(cls,methods){for(m in methods)
if(!cls[m])cls[m]=methods[m];};if(typeof console=="undefined")console={log:function(){}};log=function(){console.log.apply(console,arguments);};GC={funcs:[],run:function(func){GC.funcs.push(func);},cleanup:function(){for(var i=0;i<GC.funcs.length;i++)
GC.funcs[i].call();}};window.addEvent("unload",GC.cleanup);extendIfAbsent(String.prototype,{startsWith:function(word){return this.indexOf(word)==0;},endsWith:function(word){var i=this.indexOf(word);return(i>=0&&i>=this.length-word.length);},truncate:function(n){if(this.length<=n)return this.toString();return this.toString().substring(0,n-1)+"..";},containsAny:function(){return $A(arguments).filter(function(a){return this.indexOf(a)>=0;}.bind(this)).length>0;},empty:function(){return this.trim().length==0;}});bm=function(fn,times){times=times||1;var s=(new Date()).getTime();for(var i=0;i<times;i++)
fn();var e=(new Date()).getTime();return e-s;};RegExp.escape=function(text){if(!arguments.callee.sRE){var specials=['/','.','*','+','?','|','(',')','[',']','{','}','\\'];arguments.callee.sRE=new RegExp('(\\'+specials.join('|\\')+')','g');}
return text.replace(arguments.callee.sRE,'\\$1');};if(navigator.appVersion.contains("Win"))window.OS="Windows";else if(navigator.appVersion.contains("Mac"))window.OS="MacOS";else window.OS="Linux";var Forms={};Forms.EnhancedForm=new Class({initialize:function(form,options){this.form=$(form);this.form.onkeypress=this.keypress.bindAsEventListener(this);this.form.onkeyup=this.keyup.bindAsEventListener(this);this.options=options||{};var cancels=$ES('.cancel',form);cancels.each(function(e){e.onclick=this.cancel.bindAsEventListener(this);}.bind(this));var submits=$ES('.submit',form);submits.each(function(e){e.onclick=this.submit.bindAsEventListener(this);}.bind(this));this.submitValidators=[Forms.Validation.validateFromHtml];if(this.options.validateSubmit)
this.submitValidators.push(this.options.validateSubmit);if(this.options.cancel)
this.addEvent('cancel',this.options.cancel);if(this.options.submit)
this.addEvent('submit',this.options.submit);$ES('.form-error-message',this.form).each(function(e){var field=e.getPrevious();e.style.width=field.getStyle("width");});GC.run(function(){this.form=null;}.bind(this));},toggle:function(){if(this.form.style.display=="none")
this.show();else
this.form.hide();},show:function(){this.form.show();this.validateKeypress();this.focus();},focus:function(){var formTag=$E("form",this.form);var f=Forms.util.firstEnabledElement(formTag?formTag:this.form.getElementsByTagName("input"));if(f)f.focus();},cancel:function(){this.fireEvent('cancel');},keyup:function(ev){this.validateKeypress();},validateKeypress:function(){if(this.options.validateKeypress)
{var submitButton=$E('input[type=submit]',this.form);submitButton.disabled=!this.options.validateKeypress(this.form);}},validateSubmit:function(){var submitButton=$E('input[type=submit]',this.form);if(submitButton.disabled)
return false;var isValid=true;for(var i=0;i<this.submitValidators.length;i++){if(!this.submitValidators[i](this.form))
isValid=false;}
return isValid;},keypress:function(ev){ev=new Event(ev);if(ev.shift||ev.control||ev.alt||ev.meta)
return;var isTextarea=ev.target.tagName&&ev.target.tagName.toLowerCase()=="textarea";if(ev.key=="esc"){this.cancel();}
else if(ev.key=="enter"&&!isTextarea){log("submitting form due to enter keypress");ev.stop();this.submit(ev);}},submit:function(eventArgs){if(!this.validateSubmit())
return false;this.fireEvent('submit',eventArgs);if(this.options.submitOnSuccess){var isForm=this.form.tagName.toLowerCase()=="form";var formElement=isForm?this.form:this.form.getElementsByTagName("form")[0];if(formElement)
formElement.submit();}
return true;}});Forms.EnhancedForm.implement(new Events);Forms.Validation={noEmptyTextFields:function(form){var te=$ES('input[type=text]',form);var result=true;te.each(function(e){if(e.value.trim().length<=0)
result=false;});return result;},validateFromHtml:function(form){var isValid=true;var fields=form.getElementsByTagName('input');for(var i=0;i<fields.length;i++){if(fields[i].className.contains('form-error'))
Forms.Validation.unhighlightError(fields[i]);}
for(var i=0;i<fields.length;i++){var e=fields[i];if(e.disabled)continue;var customMessage=e.getAttribute('message');var required=e.getAttribute('required');if(required!=null&&required!="false"&&e.value.empty()){Forms.Validation.highlightError(e,customMessage);isValid=false;continue;}
if(required=="false"&&e.value.empty())continue;var v=e.getAttribute('validate');if(!v)continue;v=v.split(' ');for(var j=0;j<v.length;j++){var r=v[j].trim();if(r=="email"&&e.value.length>0){if(!e.value.match(/.+@.+\..+/))
Forms.Validation.highlightError(e,"This doesn't look like a valid email address",customMessage);}else if(r.startsWith("minLength")){var minLength=Forms.Validation.parseValue(r).toInt();if(e.value.length<minLength)
Forms.Validation.highlightError(e,"This should be at least "+minLength+" letters long");}else if(r.startsWith("regexp")){var regexp=Forms.Validation.parseValue(r);regexp=new RegExp(regexp);if(!e.value.match(regexp))
Forms.Validation.highlightError(e,customMessage?customMessage:"This is invalid");}else if(r.startsWith("sameAs")){var rel=Forms.Validation.parseValue(r).toInt();var sameAs=fields[i+rel];if(sameAs.value!=e.value){Forms.Validation.highlightError(e,"These should match",customMessage);}}
if(e.className.contains('form-error')){isValid=false;break;}};};return isValid;},parseValue:function(str){return str.match(/\((.+)\)/)[1];},unhighlightError:function(element){element.removeClass('form-error');element.parentNode.removeChild(element.getNext());},highlightError:function(element,defaultMessage,customMessage){var message=customMessage||defaultMessage;element=$(element);element.addClass('form-error');var error=new Element(document.createElement("span"));error.className="form-error-message";error.innerHTML=message;error.style.width=element.getStyle('width');error.injectAfter(element);}};Forms.EventHandlers={selectRadioChild:function(el){var i=$E("input[type=radio]",this);i.checked=true;i.focus();}};Forms.util={radioGroup:function(radio){return radio.form[radio.name];},selectedRadio:function(radioButton){var radios=this.radioGroup(radioButton);for(var i=0;i<radios.length;i++)
if(radios[i].checked)
return radios[i];},selectFirstActiveRadio:function(radio){var radios=this.radioGroup(radio);var f=this.firstEnabledElement(this.radioGroup(radio));if(f)f.checked=true;},firstEnabledElement:function(elements){if(elements.tagName&&elements.tagName=="FORM")
elements=elements.elements;return $A(elements).filter(function(e){return!e.disabled;})[0];}};util=util||{};util.dom={descendsFrom:function(node,parent){while(node!=null&&node!=parent)
node=node.parentNode;return node!=null;},findParentWithClass:function(node,className){while(node!=null&&(!node.className||!node.className.contains(className,' ')))
node=node.parentNode;return node;},indexOfChildByTagName:function(node,tagName){var firstChild=node.parentNode.firstChild;var i=0;while(firstChild!=node)
{if(!tagName||(firstChild.tagName&&firstChild.tagName==tagName))
i++;firstChild=firstChild.nextSibling;}
return i;},indexOfChild:function(node){var p=node.parentNode;for(var i=0;i<p.childNodes.length;i++)
if(p.childNodes[i]==node)return i;return null;},removeClass:function(elems,className){for(var i=0;i<elems.length;i++)
$(elems[i]).removeClass(className);},childrenWithTagName:function(parent,tagName){var kids=parent.childNodes;var results=[];for(var i=0;i<kids.length;i++)
if(kids[i].tagName==tagName)results.push(kids[i]);return results;},fragmentInnerHTML:function(df){var childNodes;try{childNodes=df.childNodes;}catch(e){return df.firstChild.nodeValue;}
var els=[];for(var i=0;i<childNodes.length;i++){var e=childNodes[i];if(this.isText(e)){els.push(e.nodeValue);continue;}
var attrString=[];if(window.ie){var props=["href","name","id","src","style","type"];for(var j=0;j<props.length;j++){var v=e.getAttribute(props[j]);if(!v||v.nodeValue==undefined)continue;if(typeof v.nodeValue=="string"||v.nodeValue!="")
attrString.push(v.nodeName+'="'+v.nodeValue+'"');}
if(e.className!="")
attrString.push("class='"+e.className+"'");}else{for(var j=0;j<e.attributes.length;j++){var v=e.attributes[j].nodeValue;if(e.attributes[j].nodeValue!="")
attrString.push(e.attributes[j].nodeName+'="'+e.attributes[j].nodeValue+'"');}}
var tag=e.tagName.toLowerCase();var html="<"+tag+" "+attrString.join(" ")
if(this.isChildless(e))
html+="/>";else
html+=">"+e.innerHTML+"</"+tag+">";els.push(html);}
return els.join("");},isChildless:function(node){switch(node.nodeName.toLowerCase()){case'img':case'br':case'hr':return true;}
return false;},isText:function(node){return node.nodeType==3;}};DomBuilder={init:function(applyTo){applyTo=applyTo||this;var els=("p|div|span|strong|em|img|table|tr|td|th|thead|tbody|tfoot|pre|code|"+"h1|h2|h3|h4|h5|h6|ul|ol|li|form|input|textarea|legend|fieldset|"+"select|option|blockquote|cite|br|hr|dd|dl|dt|address|a|button|abbr|acronym|"+"script|link|style|bdo|ins|del|object|param|col|colgroup|optgroup|caption|"+"label|dfn|kbd|samp|var").split("|");var el,i=0;while(el=els[i++])applyTo[el]=this.createFunc(el);},createFunc:function(tag){return function(){return DomBuilder.create(tag,arguments);};},create:function(tag,args){var e='<'+tag;var att="";var contents="";for(var i=0;i<args.length;i++)
{var arg=args[i];if(typeof arg=='string'||typeof arg=='number')
contents+=arg;else
att=this.keyValues(arg);}
return'<'+tag+att+'>'+contents+'</'+tag+'>';},keyValues:function(args){var str=[];for(var k in args)
str.push((k=='cls'?'class':k)+'="'+args[k]+'"');return str.length==0?"":' '+str.join(' ');}};DomBuilder.init(window);db=DomBuilder;DomBuilder.init(db);var userAgent=navigator.userAgent.toString();window.newFirefox=userAgent.indexOf("Firefox/3")>=0||userAgent.indexOf("Firefox/4")>=0?true:false;jjotutil={alterSubmitUrl:function(baseUrl,field){var f=$(field);f.form.action=baseUrl+f.value;f.form.submit();},nullClick:function(){return false;}};TableLayout={build:function(){var html="<table>";for(var i=0;i<arguments.length;i++){html+="<tr>";for(var j=0;j<arguments[i].length;j++)
html+=td(arguments[i][j]);html+"</tr>";}
html+="</table>";return html;}};HotkeyManager={keyToString:function(ev){var s="";if(ev.alt)s+="alt_";if(ev.control)s+="ctrl_";if(ev.meta)s+="meta_";if(ev.shift)s+="shift_";s+=ev.key?ev.key:ev.keyCode;return s;},add:function(evType,key,handler,options){if($type(key)!="array")key=[key];key.each(function(k){this[evType][k]={h:handler,options:options};}.bind(this));},runHandlerForKey:function(ev){var k=this.keyToString(ev);if(!this[ev.type])return;var f=this[ev.type][k];if(!f)return false;f.h(ev,arguments[1]);if(!f.options||f.options.cancel!=false)
ev.stop();return true;}};var Stylesheets={init:function(){this.rules={dragCursor:this.findRule("body.drag-cursor"),note:this.findRule(".notebox"),editor:this.findRule(".editor"),editorParent:this.findRule(".editor-parent"),textarea:this.findRule(".note textarea"),maximized:this.findRule(".maximized"),maximizedEditor:this.findRule(".maximized .editor"),maximizedEditorParent:this.findRule(".maximized .editor-parent"),ghostElementDiv:this.findRule("#ghost-element div"),note_paddingFocused:this.findRule(".focused div.note_padding"),b2Focused:this.findRule(".focused .b2"),b3Focused:this.findRule(".focused .b3")};this.rules.notes={note_padding:this.findRule('.note_padding'),b1:this.findRule('.b1'),b2:this.findRule('.b2'),b3:this.findRule('.b3'),editor:this.findRule('.editor')};},findRule:function(selectorText){var results=[];$A(document.styleSheets).each(function(sheet){var rules=sheet.cssRules||sheet.rules;for(var i=0;i<rules.length;i++)
if(rules[i].selectorText.toLowerCase()==selectorText)
results.push(rules[i]);});return results;},styleProperties:function(styleRule){var style;for(k in styleRule){var val=styleRule[k];if(val!=""&&val!=false)style[k]=val;}
delete style.cssText;},parseCssText:function(text){var rules=text.split(";");var style={};rules.each(function(r){var pair=r.split(":");var ruleName=pair[0].trim().toLowerCase().replace(/\-(.)/,function(a,b){return b.toUpperCase();});style[ruleName]=pair[1].trim();});return style;},styleObjectForRule:function(selectorText){var cssText=this.findRule(selectorText).map(function(r){return r.style.cssText;}).join(';');return Stylesheets.parseCssText(cssText);}};Element.extend({unapplyRule:function(selectorText){if(!window.ie){var className=selectorText.match(/\..*/).last().substring(1);this.removeClass(className);return;}
var styleObject=Stylesheets.styleObjectForRule(selectorText);for(var k in styleObject){if(!k.contains("border"))
this.style[k]="";else{var attrs=["borderStyle","borderWidth","borderColor"];attrs.each(function(a){this.style[a]="";}.bind(this));}}
return;},applyRule:function(selectorText){if(!window.ie){var className=selectorText.match(/\..*/).last().substring(1);this.addClass(className);return;}
var styleObject=Stylesheets.styleObjectForRule(selectorText);for(var k in styleObject)
this.style[k]=styleObject[k];},applyClass:function(ruleSet){var rules=ruleSet.map(function(r){return Stylesheets.parseCssText(r.style.cssText);}).join('\n');for(var k in rules)
this.style[k]=rules[k];},unapplyClass:function(ruleSet){var rules=ruleSet.map(function(r){return Stylesheets.parseCssText(r.style.cssText);}).join('\n');for(var k in rules){if(!k.contains("border"))
this.style[k]="";else{var attrs=["borderStyle","borderWidth","borderColor"];attrs.each(function(a){this.style[a]="";}.bind(this));}}}});var Page={fullInit:function(){log('page.init');Notes.overflowContainer=window.ie6?$('note-area'):$('note-scroll');$(window).addEvent('resize',Page.resizeNoteArea);this.resizeNoteArea();if(Debug)
Debug.init();Stylesheets.init();StretchyGrid.init();if(!Page.index){var a=new Ajax("/main/content/"+Page.boardOwner+"/"+Page.boardNumber+window.location.search,{method:"post",postBody:"x",onSuccess:function(m){eval(m);var br=document.createElement("br");br.style.clear="left";$('note-area').appendChild(br);Page.onNotesLoaded();}});a.request();}else
Page.onNotesLoaded();ModalDialog.init();Login.init();},onNotesLoaded:function(){if(!Page.shared)
Archived.init();rte.init();Notes.init();var maximizedNotes=ViewPreferences.maximizedNoteIds();var notes=$$('.note');$$('.note').each(function(e){var n=new Note(e,maximizedNotes[e.id.substring(5)]);});Notes.popoutInit();if(window.ie){var el,editorElement,range=document.selection.createRange();try{el=range.parentElement();}catch(e){}
if(el){var noteEl=util.dom.findParentWithClass(el,"note");log("got this note element:",noteEl);if(noteEl)noteEl.note.focus(true);}}
StretchyGrid.setNoteSize(StretchyGrid.noteSize);this.attachListeners();if(!Page.shared)
DD.init();Page.Hotkeys.init();this.showSaveStatus(this.saveStatus.saved);window.onbeforeunload=function(){if(Messages.syncTimer!=null){return"Some notes have not been saved; do you still want to exit?";}};if(this.focusWhenLoaded!=null){var focusId='cnote'+this.focusWhenLoaded;if($(focusId)){var editor=$('note'+this.focusWhenLoaded).editor;var scrollTo=function(){$(focusId).note.scrollIntoView();};editor.executeWhenReady([scrollTo,editor.focus.bind(editor)]);}}
log("page loading time minus images:",((new Date()).getTime()-beganLoading)/1000);if(!Page.production){first=$$('.note')[0];if(first){first=first.note;ed=first.editor;}}},partialInit:function(){Notes.overflowContainer=window.ie6?$('note-area'):$('note-scroll');ModalDialog.init();Login.init();this.attachListeners();},resizeNoteArea:function(){Notes.overflowContainer.style.height=window.getHeight()-Notes.overflowContainer.getTop()+"px";},attachListeners:function(){if($('new')){$('new').onclick=function(){Notes.newNote();return false;};$('notesize-bigger').onclick=function(){if(window.ie)this.blur();return ViewPreferences.biggerNotes();};$('notesize-smaller').onclick=function(){if(window.ie)this.blur();return ViewPreferences.smallerNotes();};$('search-clear').addEvent('click',function(){Search.deactivate();$('search').value="";$('search').focus();});Search.attachListeners();$('print').onclick=function(ev){window.open(ev.target.href);return false;}.bindWithEvent(this);this.noteboardOptionsMenu=new Controls.FileMenu({toggleButton:$('noteboard-options')},{text:"Rename noteboard",handler:this.renameNoteboardClick.bind(this),disabled:Page.shared},{text:"Delete noteboard",handler:this.deleteNoteboardClick.bind(this),disabled:Page.shared});this.noteboardOptionsMenu.addEvent("hide",function(){$('noteboard-options').removeClass("menu-active");});$("noteboard-options").onclick=function(){var n=$('noteboard-options');if(n.hasClass("menu-active"))
Page.noteboardOptionsMenu.hide("menu-active");else{Page.noteboardOptionsMenu.display(n,{anchorRight:true});n.addClass("menu-active");}
return false;};}
if($('create-noteboard')){this.createNoteboardForm=new Forms.EnhancedForm($('create-noteboard-ui'),{validateKeypress:Forms.Validation.noEmptyTextFields,submitOnSuccess:true,cancel:function(){Page.createNoteboardForm.toggle();return false;},submit:function(){}});$E('a',$('create-noteboard')).onclick=function(){Page.createNoteboardForm.toggle();return false;};}},showKeyboardShortcuts:function(){var contents=div({id:"keyboard-shortcuts-dialog"},h4({style:"margin-top:0"},"Anywhere:"),p("New note: Shift+Ctrl+N"),p("Search: Shift+Ctrl+L"),h4("Inside of notes:"),p("Undo: Ctrl+Z"),p("Bullet points: Ctrl+U"),p("Create link: Ctrl+K"),p("Bold: Ctrl+B"),p("Next note: Tab"));var d=this.hotkeysDialog;if(!this.hotkeysDialog){d=this.hotkeysDialog=new ModalDialog({width:"170px",cancelButton:false,contents:contents,modal:false,showAnimation:function(el){el.setStyle("opacity",0);el.style.left="-6px";el.style.top=$('keyboard-shortcuts').getPosition().y+14+"px";el.style.display="";el.effect('opacity',{duration:400}).start(0.0,1.0);}});}
if(d.wrapper.style.display=="none")
d.show();else
d.close();},renameNoteboardClick:function(){if(!this.renameDialog){var formHTML=form({action:Page.urlToBoard+"/rename",method:"post"},p("New name:")+input({type:"text",name:"name",style:"width:98%"}));this.renameDialog=new ModalDialog({title:"Rename this noteboard",submitButton:"Rename",width:"300px",contents:formHTML,onClose:function(ev){if(!ev.cancelled){if(Page.demo)
$('search-message').innerHTML="<strong>You must sign in to rename your noteboards.</strong>";else
$E('form',ev.dialog).submit();}
ev.cancelClose=!ev.cancelled&&!Page.demo;}});}
this.renameDialog.show();},deleteNoteboardClick:function(){if(!this.deleteDialog){var formHTML=form({action:Page.urlToBoard+"/delete",method:"post"},p("Are you sure you want to delete this noteboard?"),input({type:"hidden",name:"confirm",value:"yes"}));var singleNoteboard=Page.boards.length<=1;if(singleNoteboard)formHTML=p("You cannot delete your only noteboard.");this.deleteDialog=new ModalDialog({title:"Delete this noteboard",submitButton:singleNoteboard?"Ok":"Delete noteboard",cancelButton:!singleNoteboard,width:"300px",contents:formHTML,onClose:function(ev){if(!ev.cancelled&&!singleNoteboard){if(Page.demo)
$('search-message').innerHTML="<strong>You must sign in to delete noteboards.</strong";else
$E('form',ev.dialog).submit();}
ev.cancelClose=!ev.cancelled&&!Page.demo;}});}
this.deleteDialog.show();return false;},showStatus:function(message,undoFunction){$('status-message').innerHTML=message+" ";if(undoFunction){var a=document.createElement("a");a.innerHTML="Undo";a.onclick=this.createUndoFunction(undoFunction);a.href="#";$('status-message').appendChild(a);}},createUndoFunction:function(undoFunction){return function(){undoFunction();return false;};},saveStatus:{unsaved:1,saving:2,saved:3},showSaveStatus:function(status){var el=$('save-status');var useButton=false;var messages={};messages[this.saveStatus.unsaved]="Not saved";messages[this.saveStatus.saving]="Saving...";messages[this.saveStatus.saved]="Saved";var lastSaveText='Unknown';var lastSave=$('last-save');if(lastSave){var d=new Date();var n=parseInt(lastSave.innerHTML,10);if(!isNaN(n)){d.setTime(n);lastSaveText=d.toString();}}
el.innerHTML='<span title="Last Save: '+lastSaveText+'">'+messages[status]+'</span>';},flashEffect:function(element,cssProperty,endColor){cssProperty=cssProperty||"background-color";endColor=endColor||element.getStyle(cssProperty);var middleColor="#ffc391";var animate=new Fx.Style(element,cssProperty,{duration:500});animate.start("#ffe6c3",middleColor).chain(animate.start.pass([middleColor,endColor],animate)).chain(function(){element.setStyle(cssProperty,"");});},isJjotWindow:function(window){try{return window&&!window.closed&&window.Notes;}catch(e){}
return false;}};Page.Hotkeys={init:function(){this.keydown={};this.keypress={};if(!Page.production){this.add("keydown",'ctrl_1',function(){log("crl 1 handler");$$('.note')[0].note.focus(true);});}
this.add("keydown",["ctrl_shift_n","ctrl_shift_1"],function(){Notes.newNote();});this.add("keydown",["ctrl_shift_2","ctrl_shift_l"],function(){$('search').focus();});document.addEvent('keydown',function(ev){this.runHandlerForKey(ev);}.bindWithEvent(this));}};Page.Hotkeys=$extend(Page.Hotkeys,HotkeyManager);Login={useWidth:window.ie6||window.opera,rightOffset:20,slideInDuration:600,init:function(){this.signupPanel=$('signup-panel');if(!this.signupPanel)return;this.signupPanel.form=new Forms.EnhancedForm(this.signupPanel,{submit:jjotutil.alterSubmitUrl.pass(["/signup/","new-username"]),validateSubmit:Forms.Validation.validateFromHtml,cancel:this.toggleSignup});this.signinPanel=$('signin-panel');this.signinPanel.form=new Forms.EnhancedForm(this.signinPanel,{submit:jjotutil.alterSubmitUrl.pass(["/signin/","existing-username"]),cancel:this.toggleSignin});this.anims=[];[this.signinPanel,this.signupPanel].each(function(e){this.anims[e.id]={slideIn:this.slideInAnimation(e),slideOut:this.slideOutAnimation(e)};}.bind(this));$E('.x',this.signupPanel).onclick=this.toggleSignup;$E('.x',this.signinPanel).onclick=this.toggleSignin;var su=$('sign-up');if(su)su.onclick=this.toggleSignup;var si=$('sign-in');if(si)si.onclick=this.toggleSignin;},toggleSignup:function(){return Login.togglePanel(Login.signupPanel);},toggleSignin:function(){return Login.togglePanel(Login.signinPanel);},slideInAnimation:function(e){return new Fx.Style(e,this.useWidth?'width':'right',{duration:this.slideInDuration,transition:Login.backOut,onComplete:this.slideInComplete.bind(this)});},slideOutAnimation:function(e){return new Fx.Style(e,this.useWidth?'width':'right',{duration:250,transition:Login.quadIn,onComplete:this.slideOutComplete.bind(this)});},slideInComplete:function(e){if(window.geckp)
e.style.overflow="auto";e.animating=false;e.focusFirstInput();},slideOutComplete:function(e){e.style.display="none";e.style.overflow="";if(this.useWidth){e.style.width="0";e.style.right="0";}else
e.style.right=-e.cachedWidth;e.animating=false;},slideIn:function(e){if(!e.cachedWidth){e.style.right=0;e.setStyle("visibility","hidden");if(window.gecko)e.style.overflow="";e.style.display="";e.style.width="";e.cachedWidth=e.getStyle('width').toInt();var xButton=$E('.x',e);xButton.style.left=e.cachedWidth-xButton.offsetWidth-(this.useWidth?4:this.rightOffset)-15+"px";}
if(this.useWidth)
e.style.width=0;else
e.style.right=-e.cachedWidth+"px";e.style.visibility="";e.style.display="";e.style.overflow="";e.animating=true;if(this.useWidth)
this.slideInAnimation(e).start(e.cachedWidth);else
this.slideInAnimation(e).start(-e.cachedWidth,-this.rightOffset);if(!this.useWidth)
e.focusFirstInput();},slideOut:function(e){Login.anims[e.id].slideIn.stop();if(window.gecko)e.style.overflow="";Login.anims[e.id].slideOut.start(this.useWidth?0:-e.cachedWidth);e.animating=true;},togglePanel:function(e){if(this.signinPanel.animating||this.signupPanel.animating)
return false;if(e==this.signupPanel&&this.signinPanel.style.display!="none")
this.slideOut(this.signinPanel);else if(e==this.signinPanel&&this.signupPanel.style.display!="none")
this.slideOut(this.signupPanel);this.animating=true;if(e.style.display=="none")
this.slideIn(e);else
this.slideOut(e);return false;},backOut:function(p,x){x=.7;p=1-p;var a=Math.pow(p,2)*((x+1)*p-x);return 1-a;},quadIn:function(p){return Math.pow(p,2||6);}};var ViewPreferences={noteboardSize:4,biggerNotes:function(){StretchyGrid.bigger();return false;},smallerNotes:function(){StretchyGrid.smaller();return false;},parseCookie:function(){var cookie=Cookie.get("jjot-nb");if(!cookie)
return{};var res={};try{res=Json.evaluate(cookie);}catch(e){}
return res;},getPreference:function(name){var noteboards=this.parseCookie();if(noteboards[Page.boardIdentifier])
return noteboards[Page.boardIdentifier][name];return null;},setMaximized:function(noteId,maximized){var maxed=this.getPreference("max");var maxedNotes=maxed||[];if(maximized&&maxedNotes.indexOf(noteId)<0)
maxedNotes.push(noteId);else if(!maximized&&maxedNotes.indexOf(noteId)>=0)
maxedNotes.splice(maxedNotes.indexOf(noteId),1);this.setPreference('max',maxedNotes);},maximizedNoteIds:function(){var map={};var ids=this.getPreference('max');ids=ids||[];ids.each(function(e){map[e]=true;});return map;},setPreference:function(name,value){var noteboards=this.parseCookie();var prefs=noteboards[Page.boardIdentifier]||{};prefs[name]=value;noteboards[Page.boardIdentifier]=prefs;Cookie.set('jjot-nb',Json.toString(noteboards),{duration:90,path:"/"});}};var DD={droppableOptions:{over:function(el){var gh=$(DD.ghostElement);if(gh.style.display=="none")
gh.injectBefore(this);else if(DD.ghostOccursBefore(this))
gh.injectAfter(this);else
gh.injectBefore(this);},leave:function(el){},drop:function(el,drag){}},draggableOptions:{onBeforeStart:function(el){var dragged=this.element;if(dragged.style.position=="absolute"){this.options.canceled=true;return;}
console.log("drag has begun for element "+dragged.id);dragged.addClass("dragging");var textArea=dragged.getElementsByTagName("textarea")[0];textArea.editor.beforeDrag();textArea.editor.focus();var overflown=[$('note-scroll')];var top,left;if(window.ie){top=dragged.getTop()-Notes.overflowContainer.getTop();left=dragged.getLeft()-Notes.overflowContainer.getLeft();}else{top=dragged.getTop(overflown);left=dragged.getLeft(overflown);}
var size=dragged.getSize().size;DD.ghostElement.show();this.element.parentNode.replaceChild(DD.ghostElement,this.element);dragged.style.left=0;dragged.style.position='absolute';dragged.style.top=top+"px";dragged.style.left=left+"px";if(window.gecko)$E('.b3',dragged).style.overflow="auto";dragged.setStyle('width',size.x+"px");dragged.injectAfter(DD.ghostElement);if(window.gecko){if(!DD.overlay)DD.overlay=new Overlay();DD.overlay.show(dragged);DD.overlay.overlay.style.background="none";}
DD.scroller.start();$(document.body).addClass("drag-cursor");},onComplete:function(el){$(document.body).removeClass("drag-cursor");var dragged=this.element;console.log("drag has just completed for element "+dragged.id);DD.scroller.stop();if(window.gecko)DD.overlay.remove();var textArea=dragged.getElementsByTagName('textarea')[0];dragged.removeClass("transparent");dragged.removeClass("dragging");if(dragged.moveTo){var note=Note.forElement(dragged);DD.ghostElement.remove();if(dragged.moveTo.number!=Page.boardNumber){note.moveTo(dragged.moveTo.number,dragged.moveTo.name);return;}else
dragged.injectTop($('note-area'));}
var p=dragged.parentNode;this.element.style.left=0;this.element.style.top=0;this.element.style.position="relative";this.element.style.width='';this.element.style.height='';if(DD.ghostElement.parentNode)
DD.ghostElement.parentNode.replaceChild(this.element,DD.ghostElement);if(window.gecko)$E('.b3',dragged).style.overflow="";Messages.saveOrder();textArea.editor.afterDrag();return true;}},init:function(){this.ghostElement=new Element(document.createElement("div"));this.ghostElement.innerHTML="<div></div>";this.ghostElement.className="notebox";this.ghostElement.id="ghost-element";DD.scroller=new Scroller(Notes.overflowContainer,{area:30,verticalOnly:true});this.setupDragDrop();this.setupNoteboardDropTargets();},ghostOccursBefore:function(element){var na=$('note-area');var e=na.firstChild;while(e.id!=element.id){if(e.id=="ghost-element")
return true;e=e.nextSibling;}
return false;},setupDragDrop:function(){var notes=$$('.note');var noteboards=$$('#noteboards li');var noteboardsContainer=$('noteboards');var d=notes.slice(0,notes.length);var overflow=[Notes.overflowContainer];d.each(function(e){e.overflow=overflow;});d.push(noteboardsContainer);DD.draggableOptions.droppables=d.concat(noteboards);DD.draggableOptions.overflown=[Notes.overflowContainer];notes.each(function(el){if(!el.dragObject){DD.draggableOptions.handle=el.id+'_drag';DD.draggableOptions.editor=el.note.editor;el.dragObject=el.makeDraggable(DD.draggableOptions);el.addEvents(DD.droppableOptions,true);}else
el.dragObject.droppables=DD.draggableOptions.droppables;});},setupNoteboardDropTargets:function(){var noteboards=$$('#noteboards li');var noteboardsContainer=$('noteboards');var noteboardEvents={over:function(el){this.addClass("drag-hover");$clear(DD.noteboardDDTimer);DD.dragOverNoteboard(el);},leave:function(el){this.removeClass("drag-hover");DD.dragLeaveNoteboard(el);DD.noteboardDDTimer=DD.dragLeaveNoteboard.delay(100,DD,[el]);},drop:function(el){if(!this.hasClass("drag-hover")||!el.parentNode)
return;this.removeClass("drag-hover");var link=$E('.bar',this);el.moveTo={name:link.getAttribute("title"),number:link.getAttribute("number")};}};for(var i=0;i<noteboards.length;i++)
noteboards[i].addEvents(noteboardEvents,true);noteboardsContainer.addEvents({over:function(el){$clear(DD.noteboardDDTimer);DD.dragOverNoteboard(el);},leave:function(el){DD.noteboardDDTimer=DD.dragLeaveNoteboard.delay(70,DD,[el]);}});},dragOverNoteboard:function(el){el.addClass("transparent");DD.ghostElement.hide();},dragLeaveNoteboard:function(el){el.removeClass("transparent");DD.ghostElement.show();},noteboardDDTimer:0};rte={styleSheet:"*{margin:0;padding:0}"+"html,body{height:100%} body{padding-left:2px;font-family:helvetica,arial,sans; line-height:130%;}"+".title{font-size:1.2em;color:#005eAD; margin-bottom:3px}"+"a{cursor:pointer ! important}"+"a{color:blue;}"+"body,html{cursor:text ! important;}"+"a{padding:1px}"+"a:visited{color:#111180 ! important}"+"a._mouseover{background-color:#e4eaee;}"+"li{margin-left:20px;}"+".ed-search-miss{color:#888;}"+".ed-search-miss div.title{color:#4d7e8a}"+".ed-search-miss a{color:#081a5c}",init:function(){rte.Events.implement(new Events);rte.Events=new rte.Events();rte.Control.implement(new Events);rte.Control.implement(new Options);rte.Control.implement(new rte.Range.Extension);rte.Control.implement(new rte.Links);rte.Control.implement(new rte.LinkEditor);rte.KeyListeners.init();this.styleSheetNode=this.createStyleSheetNode(rte.styleSheet,"styleSheet");this.cleanupRegex=new RegExp('(class="?'+rte.LinkMenu.mouseoverClassname+'"?)|'+rte.undo.undoNodeID,"i");},createStyleSheetNode:function(style,id){var s=document.createElement("style");s.id=id;if(s.canHaveChildren==false)
s.text=style;else
s.appendChild(document.createTextNode(style));return s;},replaceTextareas:function(){var areas=document.getElementsByTagName('textarea');for(var i=0;i<areas.length;i++)
new rte.newControl(areas[i]);},attach:function(id){var e=$(id);return new rte.newControl(e);},endsWithBR:function(str){return str.match(/<br\s*[\/]?>$/i);}};rte.ClonedRange=new Class({initialize:function(range,editor){this.editor=editor;this.offset=range.startOffset;this.nodePosition=new rte.NodePosition(range.startContainer);},createRange:function(bodyNode){var body=bodyNode||this.editor.bodyNode();var newNode=this.nodePosition.findMatchingNode(body);var range=this.editor.newRange();range.setStart(newNode,this.offset);range.setEnd(newNode,this.offset);return range;}});rte.NodePosition=new Class({initialize:function(node,options){if(!node.tagName||node.tagName.toLowerCase()!="body"){this.parentOffset=util.dom.indexOfChild(node);if(node.parentNode.tagName&&node.parentNode.tagName.toLowerCase()!="body")
this.parentPosition=new rte.NodePosition(node.parentNode,{child:this,tag:node.parentNode.tagName});}
this.options=options||{};},findMatchingNode:function(body){var n=this;while(n.parentPosition)
n=n.parentPosition;n1=n;var matchingNode=body;while(n&&n.parentOffset!=null){matchingNode=matchingNode.childNodes[n.parentOffset];n=n.options.child;}
return matchingNode;},toString:function(){return"tag: "+this.options.tag+" child: "+(this.options.child?"yes":"no");}});rte.RangeContainer=new Class({initialize:function(range){this.startContainer=range.startContainer;this.endContainer=range.endContainer;this.startOffset=range.startOffset;this.endOffset=range.endOffset;},buildRange:function(doc){var range=doc.createRange();range.setStart(this.startContainer,this.startOffset);range.setEnd(this.endContainer,this.endOffset);return range;},log:function(){log(this.startContainer,":",this.startOffset,this.endContainer,":",this.endOffset);}});rte.Events=new Class({initialize:function(){}});rte.Commands=new Class({initialize:function(editor){this.ed=editor;},beforeCommand:function(ev){this.ed.focus();},bold:function(){this.beforeCommand();this.ed.execCommand("bold");this.ed.toolbar.determineButtonStates();this.ed.checkForChanges();return false;},italic:function(){this.beforeCommand();this.ed.execCommand("italic");this.ed.checkForChanges();return false;},unorderedList:function(ev){this.beforeCommand();this.ed.execCommand("insertunorderedlist");this.ed.toolbar.determineButtonStates();this.ed.checkForChanges();return false;}});rte.Control=new Class({initialize:function(textarea){this.onMousemove=Class.empty;this.onChanged=Class.empty;this.textarea=$(textarea);this.textarea.setStyle('display','none');this.titlebar=$('c'+textarea.id+"_buttons");this.commands=new rte.Commands(this);this.toolbar=new rte.Toolbar(this.titlebar,this);this.toolbar.addButtons();if(typeof newNoteTimer!="undefined")log("content editable:",((new Date()).getTime()-newNoteTimer)/1000);this.createEditorElement();this.textarea.editor=this;this.editActions=0;},setupControl:function(){this.attachEvents();this.attachLinkHandlers();this.textarea.value=this.oldContent=this.bodyNode().innerHTML;this.undoManager=new rte.undo.Manager(this);if(this.queuedFunctions){this.queuedFunctions.each(function(f){f();});this.queuedFunctions=[];}},reinitializeContents:function(contents){this.textarea.value=this.oldContent=this.bodyNode().innerHTML=contents;this.undoManager=new rte.undo.Manager(this);this.textarea.title=this.getTitle();this.attachLinkHandlers();},attachEvents:function(){var d=this.containerDocument();var keyEvent=this.keyEvent.bindWithEvent(this);util.attach(d,'keydown',keyEvent);util.attach(d,'keypress',keyEvent);util.attach(d,'keyup',this.keyup.bindWithEvent(this));util.attach(d,'mouseup',this.toolbar.determineButtonStates.bindAsEventListener(this.toolbar));util.attach(d,'focus',this.editorFocused.bindAsEventListener(this));util.attach(d,'blur',this.editorBlurred.bindAsEventListener(this));},keyEvent:function(ev){if(rte.KeyListeners.runHandlerForKey(ev,this))
return;if(!this.ce&&(ev.control||ev.meta))
Page.Hotkeys.runHandlerForKey.pass([ev],Page.Hotkeys).delay(2);},keyup:function(ev){if(ev.code==16||ev.code==17||ev.code==18||ev.code==224)
return;if((ev.key=="z"||ev.key=="y")&&(ev.control||ev.meta)){}else if(ev.key!=""){if(this.bodyNode().innerHTML!=this.textarea.value){this.insertTitleIfMissing();}}
this.checkForChanges();this.toolbar.determineButtonStates();this.fireEvent('keypress',this);Debug.out(this.bodyNode(),true);},reflowTitleNode:function(){this.undoManager.saveState();var currentRange=this.selectedRange();log("reflowing title node");var titleNode=this.getTitleNode();if(!util.dom.descendsFrom(currentRange.startContainer,titleNode))
return false;var offsetFromBody=util.dom.indexOfChild(titleNode);var leftHalfRange=this.newRange();leftHalfRange.selectNodeContents(titleNode);leftHalfRange.setEnd(currentRange.startContainer,currentRange.startOffset);var leftHalf=leftHalfRange.cloneContents();var rightRange=this.newRange();rightRange.selectNodeContents(titleNode);rightRange.setStart(currentRange.startContainer,currentRange.startOffset);var rightHalf=rightRange.cloneContents();var rightHTML=util.dom.fragmentInnerHTML(rightHalf);if(rightHTML.length==0)rightHTML="<br/>";rightHTML="<p>"+rightHTML+"</p>";var newTitle="<p class='title'>"+util.dom.fragmentInnerHTML(leftHalf)+"</p>"+rightHTML;this.getTitleNode().remove();this.bodyNode().innerHTML=newTitle+this.bodyNode().innerHTML;if(window.ie)
this.placeCursorInside(this.getTitleNode());else
this.placeCursorInside(this.getTitleNode().nextSibling);this.undoManager.saveState();this.recentUndo=true;this.attachLinkHandlers();this.checkForChanges();return true;},insertTitleIfMissing:function(){var bodyNode=this.bodyNode();var firstChild=bodyNode.firstChild;var titleNodes=this.getTitleNodes();if(firstChild&&firstChild.className&&firstChild.className.contains("title")&&firstChild.tagName=="P"&&titleNodes.length==1)
return;for(var i=0;i<titleNodes.length;i++)
titleNodes[i].removeClass("title");if(!firstChild){bodyNode.innerHTML="<p class='title'></p>";this.placeCursorInside(this.getTitleNode());}else if(firstChild.tagName=="P"){firstChild.className="title";}else if(firstChild.nodeType==3){var replacing=firstChild.nodeValue?firstChild.nodeValue:firstChild.innerHTML;if(!replacing)replacing="<br/>";var newHTML="<p class='title'>"+replacing+"</p>";bodyNode.removeChild(firstChild);bodyNode.innerHTML=newHTML+bodyNode.innerHTML;if(!window.ie){var sel;if(replacing.match(/^<br\s*\/?>$/)){sel=this.newRangeContaining(this.getTitleNode(),0);}else{sel=this.selectionAtEndOfNode(this.getTitleNode());}
this.setSelection(sel);}else{this.placeCursorInside(this.getTitleNode());}}},getTitleNodes:function(){if(window.newFirefox)
return $A(this.cw.document.getElementsByClassName('title')).map(function(e){return $(e);});else
return $ES('.title',this.bodyNode());},getTitleNode:function(){if(window.newFirefox)
return $(this.cw.document.getElementsByClassName('title')[0]);else
return $E('.title',this.bodyNode());},cleanupText:function(text){return text.replace(rte.cleanupRegex,"");},getContents:function(){return this.textarea.value;},checkForChanges:function(){if(!this.editorIsReady())
return;this.textarea.value=this.cleanupText(this.bodyNode().innerHTML);this.textarea.title=this.getTitle();if(this.textarea.value!=this.oldContent)
{this.attachLinkHandlers();this.editActions++;if(this.recentUndo){this.recentUndo=false;this.editActions=0;}
else{var diff=Math.abs(this.oldContent.length-this.textarea.value.length);if(diff>50||this.editActions>7){this.undoManager.saveState();this.editActions=0;}else
this.undoManager.dirty();}
this.oldContent=this.textarea.value;this.fireEvent("changed",this);}},beforeDrag:function(){rte.dragging=true;if(!this.ce){this.saveScrollPosition();this.checkForChanges();}},afterDrag:function(){rte.dragging=false;if(window.ie)return;this.executeWhenReady(function(){this.restoreScrollPosition();}.bind(this));},saveScrollPosition:function(){this.savedScrollOffset=[this.cw.pageXOffset,this.cw.pageYOffset];},restoreScrollPosition:function(){this.cw.scrollBy(this.savedScrollOffset[0],this.savedScrollOffset[1]);this.savedScrollOffset=null;},editorIsReady:function(){if(this.ce)
return true;else
return this.cw&&this.cw.document?true:false;},editorFocused:function(ev){if(!Page.shared)
this.undoManager.focused();this.oldContent=this.textarea.value;rte.focusedEditor=this;this.fireEvent('focus',this);Debug.out(this.bodyNode(),true);},editorBlurred:function(ev){if(!this.editorIsReady())
return;this.checkForChanges();rte.focusedEditor=null;this.fireEvent('blur',this);},iframeMouseMove:function(ev){ev.relativeTo=this.iframe;rte.Events.fireEvent('mousemove',ev);this.fireEvent('mousemove',ev);},iframeMouseUp:function(ev){ev.relativeTo=this.iframe;rte.Events.fireEvent('mouseup',ev);},iframeClick:function(ev){rte.Events.fireEvent('click',ev);},executeWhenReady:function(funcs){if($type(funcs)=="function")
funcs=[funcs];this.queuedFunctions=this.queuedFunctions||[];this.queuedFunctions=this.queuedFunctions.concat(funcs);if(this.editorIsReady()){this.queuedFunctions.each(function(f){f();});this.queuedFunctions=[];}},selectAll:function(){var range=this.cw.document.createRange();range.selectNodeContents(this.bodyNode());this.setSelection(range);},selectTitleNode:function(){if(window.ie){var r=document.body.createTextRange();r.moveToElementText(this.getTitleNode());r.select();}else{var r=this.newRange();r.selectNode(this.getTitleNode().firstChild);r.selectNodeContents(this.getTitleNode());this.setSelection(r);}},focus:function(){if(this.ce)
this.containerDocument().focus();else
this.cw.focus();},setSelection:function(newRange){if(window.ie)
newRange._range.select();else{var selection=this.selection();selection.removeAllRanges();selection.addRange(newRange);}},selection:function(){if(!this.ce)
return this.cw.getSelection();else{return window.ie?document.selection:window.getSelection();}},editorElement:function(){return this.ce?this.div:this.iframe;},documentNode:function(){return this.ce?document:this.cw.document;},bodyNode:function(){return this.ce?this.div:this.cw.document.body;},execCommand:function(commandName,argument){var doc=this.ce?document:this.cw.document;if(window.ie&&commandName.toLowerCase()=="inserthtml")
this.selectedRange()._range.pasteHTML(argument);else
doc.execCommand(commandName,false,argument);},containerDocument:function(){if(this.ce)
return this.div;else
return this.cw.document;},selectedRange:function(){if(window.ie){var sel=document.selection;return new rte.Range.IERange(document.selection.createRange());try{return new rte.Range.IERange(document.selection.createRange());}catch(e){log("exception returning IERange");return null;}}else{var sel=this.selection();try{return sel.getRangeAt(0);}
catch(e){log("Mozilla exception while calling this.selection().getRangeAt(0)");}
return null;}},formatTitle:function(title){var t=title?rte.util.HTML.scrapeText(title):"";return t.replace(/&nbsp;/g," ").trim();},getTitle:function(){if(!this.editorIsReady())
return this.textarea.title;var titleNode=this.getTitleNode();return this.formatTitle(titleNode?titleNode.innerHTML:this.bodyNode().innerHTML.substring(0,60));},gc:function(){this.div=this.cw=null;this.textarea=this.textarea.editor=null;this.titlebar=this.commands=null;}});rte.ContentEditableControl=rte.Control.extend({createEditorElement:function(){this.ce=true;var d=$(document.createElement("div"));d.className="editor ce";d.innerHTML=this.textarea.value;d.injectBefore(this.textarea);if(!Page.shared)
d.contentEditable="true";this.div=d;this.setupControl();}});rte.IFrameControl=rte.Control.extend({createEditorElement:function(){this.iframe=new Element(document.createElement("iframe"));this.iframe.className="editor";this.iframe.id=this.textarea.id+"_if";this.cw=null;this.iframe.addEvent('load',this.iframeLoad.bindAsEventListener(this));this.iframe.injectBefore(this.textarea);},iframeLoad:function(){if(!this.buildIframe()){log("was not able to build iframe");return;}},buildIframe:function(){doc=this.iframe.contentWindow.document;var body=$(this.iframe.contentWindow.document.body);body.spellcheck=false;this.cw=this.iframe.contentWindow;var head=doc.getElementsByTagName("head")[0];if(window.newFirefox)
head.appendChild(doc.adoptNode(rte.styleSheetNode.cloneNode(true)));else
head.appendChild(rte.styleSheetNode.cloneNode(true));this.cw.log=console.log;var d=doc.createElement("script");d.innerHTML="window.mozFind=function(){try{window.find('hey')}catch(e){log(e);}};"
head.appendChild(d);body.innerHTML=this.textarea.value;doc.designMode="on";body.addEvent('mousemove',this.iframeMouseMove.bindAsEventListener(this));body.addEvent('click',this.iframeClick);body.addEvent('mouseup',this.iframeMouseUp.bindAsEventListener(this));this.setupControl();if(Page.shared)this.execCommand("contentReadOnly");this.execCommand("insertBrOnReturn",false);return true;}});rte.newControl=function(textarea){if(window.gecko)
return new rte.IFrameControl(textarea);else
return new rte.ContentEditableControl(textarea);};rte.KeyListeners={init:function(){this.keydown={};this.keypress={};var add=this.add.bind(this);var kd="keydown";var kp="keypress";add(kd,"tab",this.switchNote);add(kd,"shift_tab",this.switchNote);if(Page.shared){add(kd,"ctrl_k",function(){});return;}
add(kd,"ctrl_k",this.link);add(kd,"ctrl_l",this.link);add(kd,"ctrl_y",this.redo);add(kd,"ctrl_z",this.ctrlZ);add(kd,"ctrl_shift_z",this.ctrlZ);add(kd,"meta_z",this.ctrlZ);add(kd,"meta_shift_z",this.ctrlZ);add(kp,"enter",this.enter,{cancel:false});add(kp,"up",this.up,{cancel:false});if(!window.webkit)
{add(kd,"ctrl_b",function(){rte.focusedEditor.commands.bold();});add(kd,"ctrl_i",function(){rte.focusedEditor.commands.italic();});add(kd,"ctrl_u",function(){rte.focusedEditor.commands.unorderedList();});}},ctrlZ:function(ev,ed){if(ev.shift)
rte.KeyListeners.redo(ev,ed);else
rte.KeyListeners.undo(ev,ed);},undo:function(ev,ed){if(ed.undoManager.undo())
ed.recentUndo=true;},redo:function(ev,ed){if(ed.undoManager.redo())
ed.recentUndo=true;},link:function(ev,ed){ed.toolbarLink();},switchNote:function(ev,ed){var el=ed.textarea.note.element;var n=ev.shift?el.getPrevious():el.getNext();if(!n||!n.note){var na=$('note-area');n=ev.shift?na.getLast().getPrevious():na.getFirst();}
n.note.scrollIntoView(window.ie?0:100);n.note.focus(true);},bold:function(ev,ed){ed.commands.bold();},up:function(ev,ed){var previous=ed.getTitleNode().previousSibling;var noSibling=!previous||($type(previous)=="whitespace"&&!previous.previousSibling);if(noSibling&&util.dom.descendsFrom(ed.selectedRange().startContainer,ed.getTitleNode())){ed.setSelection(ed.newRangeContaining(ed.getTitleNode(),0));ev.stop();}},enter:function(ev,ed){ed.insertTitleIfMissing();if(ed.reflowTitleNode())
ev.stop();}};rte.KeyListeners=$extend(rte.KeyListeners,HotkeyManager);rte.Toolbar=new Class({initialize:function(titlebar,editor){this.editor=editor;this.titlebar=$(titlebar);},addButtons:function(){this.bold=this.titlebar.getElementsBySelector(".bold")[0];this.bold.title="Bold "+this.hotkeyString("B");this.link=this.titlebar.getElementsBySelector(".link")[0];this.link.title="Create link "+this.hotkeyString("K");this.bullets=this.titlebar.getElementsBySelector(".bullets")[0];this.bullets.title="Create bulleted list "+this.hotkeyString("U");if(window.webkit){this.bold.setStyle('display','none');this.link.setStyle('display','none');this.bullets.setStyle('display','none');return;}
if(!Page.shared){this.link.onclick=this.editor.toolbarLink.bind(this.editor);this.bold.onclick=this.editor.commands.bold.bind(this.editor.commands);this.bullets.onclick=this.editor.commands.unorderedList.bind(this.editor.commands);}else
this.link.onclick=this.bold.onclick=this.bullets.onclick=function(){return false;};GC.run(this.gc.bind(this));},hotkeyString:function(c){var str="Ctrl"+"+"+c;return"("+str+")";},toggled:function(button){var button=$('c'+this.editor.textarea.id+'_'+button);return button.hasClass('on');},setChecked:function(button,state){var button=$('c'+this.editor.textarea.id+'_'+button);if(!button.hasClass('on'))
button.addClass('on');},determineButtonStates:function(){var parent;if(window.ie){var sel=this.editor.selection();var range=sel.createRange();try{parent=range.parentElement();}catch(e){return false;}}else{var range=this.editor.selectedRange();if(!range)return;parent=range.commonAncestorContainer;parent=parent.parentNode;}
var children=this.titlebar.childNodes;$(this.titlebar).getChildren().each(function(child){if(child.hasClass('on'))
child.removeClass('on');});var d=this.editor.documentNode();if(d.queryCommandState('bold'))
$(this.bold).addClass('on');if(d.queryCommandState('unlink'))
$(this.link).addClass('on');if(parent&&rte.util.Node.findParentWithTag(parent,"A",this.editor.editorElement()))
$(this.link).addClass('on');return;if(this.editor.iframe.contentWindow.document.selection)
{selection=this.editor.selection();range=selection.createRange();try{parent=range.parentElement();}catch(e){return false;}}
else
{try{selection=this.editor.selection();}catch(e){console.log("exception: ",e);return false;}
range=selection.getRangeAt(0);if(!range.commonAncestorContainer)
log("!!no ancestor container");log(range);parent=range.commonAncestorContainer;}
while(parent.nodeType==3){parent=parent.parentNode;}
while(parent.nodeName.toLowerCase()!="body"){switch(parent.nodeName.toLowerCase()){case"span":if(parent.getAttribute("style").test("font-weight: bold;")){this.setChecked('bold',true);}
break;}
parent=parent.parentNode;}},gc:function(){this.titlebar=this.bold=this.link=this.bullets=null;}});Notes={board:"",init:function(){Messages.addEvent("untrash",this.untrash.bind(this));},newNote:function(id,contents,options){options=options||{};newNoteTimer=(new Date()).getTime();var id=id||this.newID();var node=$(this.newHtmlNode(id,contents));if($('note-area').getFirst()==false)
$('note-area').appendChild(node);else
$('note-area').insertBefore(node,$('note-area').getFirst());var n=new Note(node);DD.setupDragDrop();var saveFunction=function(){if(options.saveContents!=false)
Messages.doSync("save",n.getNoteData());Messages.saveOrder();}.bind(this);var toExecute=[n.editor.focus.bind(n.editor),saveFunction];if(!contents)
toExecute.unshift(n.editor.selectTitleNode.bind(n.editor));n.editor.executeWhenReady(toExecute);console.log('creating new note '+id);n.scrollIntoView();if(options.flashEffect){var titleBar=$E('.titlebar',n.element);Page.flashEffect(titleBar);}
return false;},formatTitleForDisplay:function(title){return title.truncate(18)||"untitled";},getAll:function(){return $ES('.note','note-area').map(function(e){return e.note;});},deleteNote:function(noteData){var noteid='cnote'+noteData.id;log("Deleting note with id",noteData.id);if($(noteid))
$(noteid).remove();Archived.removeFromArchive(noteData.id,true);Page.showStatus("\""+Notes.formatTitleForDisplay(noteData.title)+"\" was deleted.",function(){Messages.doSync("untrash",{id:noteData.id});});Messages.doSync("trash",noteData);},untrash:function(note){Notes.newNote(note.id,note.text,{flashEffect:true,saveContents:false});Page.showStatus("");},newHtmlNode:function(id,content){var noteIdString='note'+id;var note=document.createElement("div");note.id="c"+noteIdString;note.className="note notebox";var html='<div class="note_padding">'+'<div class="b1"><div class="b2"><div class="b3">'+'<div class="titlebar" id="c<%=id%>_tb">'+'<div id="c<%=id%>_buttons" class="buttons">'+'<a href="#" class="bold button"></a><a href="#" class="link button"></a>'+'<a href="#" class="bullets button"></a><a href="#" class="more button"></a>'+'</div>'+'<div class="metabuttons">'+'<a href="#" class="maximize button"></a><a href="#" class="delete button"></a>'+'</div>'+'<div id="c<%=id%>_drag" class="drag"></div>'+'</div>'+'<div class="titlebar-divider"></div>'+'<div class="editor-parent">'+'<textarea id="<%=id%>" name="elm<%=id%>" rows="10" cols="40"><%=note.text%></textarea>'+'</div>'+'</div></div></div>'+'</div>';html=html.replace(/<%=id%>/g,noteIdString);content=content||"<p class='title'>"+this.dateString()+"</p>";html=html.replace(/<%=note.text%>/,content);note.innerHTML=html;return note;},dateString:function(){var months=new Array("Jan","Feb","March","April","May","June","July","Aug","Sept","Oct","Nov","Dec");var d=new Date();return months[d.getMonth()]+' '+d.getDate()+', '+d.getFullYear();},noteIds:function(){return $$('.note').map(function(e){return e.id.substring(5);});},newID:function(){return $random(0,1000000000);}};var Note=new Class({initialize:function(element,maximized){this.element=$(element);this.textarea=element.getElementsByTagName("textarea")[0];this.textarea.note=this;this.element.note=this;this.editor=rte.attach(this.textarea);this.editor.addEvent('focus',this.onFocus.bind(this));this.editor.addEvent('blur',this.onBlur.bind(this));this.editor.addEvent('dialogShow',this.onDialogShow.bind(this));this.editor.addEvent('dialogHide',this.onDialogHide.bind(this));this.noteId=this.textarea.id.substring(4);this.editor.addEvent('changed',this.onChanged.bindAsEventListener(this));this.maximizeButton=this.element.getElementsBySelector('.maximize')[0];this.maximizeButton.onclick=this.toggleMaximize.bind(this);if(!Page.popout)
this.element.getElementsBySelector('.delete')[0].onclick=this.archive.bind(this);this.moreButton=this.element.getElementsBySelector('.more')[0];this.moreButton.onclick=this.showMoreMenuClick.bind(this);if(maximized)
this.setMaximizedState(true,true);GC.run(this.gc.bind(this));},getNoteData:function(){return{id:this.noteId,text:this.getText(),title:this.getTitle()};},focus:function(focusCursor){if(focusCursor)
this.editor.focus();else
this.onFocus();},onFocus:function(){if(Notes.lastFocused)
Notes.lastFocused.element.removeClass("focused");this.element.addClass("focused");Notes.lastFocused=this;if(this.element.hasClass("search-miss"))
Search.deactivate();},onBlur:function(){this.element.removeClass("focused");},onDialogShow:function(){this.element.addClass("dialog-showing");},onDialogHide:function(){this.element.removeClass("dialog-showing");},onChanged:function(editor){var f=function(){Messages.doSync("save",this.getNoteData());};f.delay(10,this);},archive:function(){if(this.archiving||Page.shared)
return false;console.log('archiving note '+this.noteId);this.archiving=true;var whenDone=function(){Archived.add(this.getNoteData());this.element.remove();}.bind(this);whenDone();ViewPreferences.setMaximized(this.noteId,false);return false;},moveTo:function(boardNumber,boardName){var noteData=this.getNoteData();this.element.remove();Page.showStatus("Moved \""+
Notes.formatTitleForDisplay(noteData.title)+"\" to <strong>"+boardName+"</strong>.");var nb=$('nb-'+boardNumber);Page.flashEffect(nb,"background-color","#FFFFFF");noteData.board=boardNumber;Messages.doSync("move",noteData);},setMaximizedState:function(state,pageLoading){if(state){this.element.addClass('maximized');this.maximizeButton.addClass("on");this.maximized=true;}else{this.element.removeClass('maximized');this.maximizeButton.removeClass("on");this.maximized=false;}
if(!pageLoading){if(!Page.popout)this.scrollIntoView();this.editor.focus();}
this.fireEvent("maximize");},scrollIntoView:function(duration){Notes.overflowContainer.scrollUntilVisible(this.element,duration);},toggleMaximize:function(){this.setMaximizedState(!this.maximized);if(!Page.popout)
ViewPreferences.setMaximized(this.noteId,this.maximized);return false;},showMoreMenuClick:function(){if(!this.moreMenu){this.moreMenu=new Controls.FileMenu({toggleButton:this.moreButton},{text:"Pop-out",handler:Notes.popout.pass([this.noteId],Notes),disabled:Page.popout},{text:"Email to...",handler:this.menuEmailClick.bind(this),disabled:Page.popout},{text:"Print",handler:this.menuPrintClick.bind(this)},{text:"Move",handler:this.menuMoveClick.bind(this),disabled:(Page.popout||Page.shared||Page.boards.length<=1)},{text:"Delete",handler:this.menuDeleteClick.bind(this),disabled:(Page.popout||Page.shared)});this.moreMenu.addEvent('hide',function(){this.moreButton.removeClass("menu-active");}.bind(this));}
if(this.moreButton.hasClass("menu-active"))
Controls.FileMenu.hideActive();else
this.showMoreMenu();return false;},showMoreMenu:function(){var adjust=window.ie6?8:6;this.moreMenu.display(this.moreButton,{left:this.moreButton.getLeft()-this.moreButton.getParent().getLeft()-adjust,top:this.moreButton.getSize().size.y-adjust+1});this.moreButton.addClass("menu-active");},moveDialogResult:function(ev){if(ev.cancelled)return;this.onDialogHide();var selected=Forms.util.selectedRadio($E('input[type=radio]',this.moveDialog));this.moveTo(selected.getAttribute("number"),selected.value);},emailDialogResult:function(ev){if(ev.cancelled)return;this.onDialogHide();var text=$E('.emails',ev.dialog).value.split(/[\s\n,]/);var emails=[];text.each(function(e){e=e.trim();if(e.contains("@"))
emails.push(e);});var data=this.getNoteData();var postData={emails:emails,metoo:false,noteText:data.text,noteTitle:data.title};Page.showStatus("Emailing your note...");var a=new Ajax(Page.urlToBoard+"/email",{postBody:Json.toString(postData),method:"post",onSuccess:function(){Page.showStatus("Your note has been emailed to "+emails.length+(emails.length==1?" person":" people")+".");}});a.request();},emailPreview:function(){var html=p("This is what the email will look like:")+
hr();},menuEmailClick:function(ev){if(!this.emailDialog){var formHTML=form({action:"#",cls:"email-form"},p({cls:"comment"},"Type in some email addresses separated by commas or spaces"),textarea({cls:"emails"}));if(Page.demo)formHTML=p("You must sign in before you can email notes to people.");this.emailDialog=new ModalDialog({title:"Email this note to...",submitButton:Page.demo?"Ok":"Email note",cancelButton:!Page.demo,contents:formHTML,width:"340px",container:Notes.overflowContainer,parent:this.element,onClose:Page.demo?null:this.emailDialogResult.bind(this)});}
this.onDialogShow();this.emailDialog.show();return false;},menuMoveClick:function(ev){if(!this.moveDialog){var listItems="";Page.boards.each(function(e){var disabled=(e.number==Page.boardNumber)?"disabled":"";listItems+="<li class='"+disabled+"'><label>"+"<input type='radio' name='board' value='"+e.name+"' number='"+e.number+"' "+disabled+">"+e.name+"</label></li>";});var formHTML=form({action:"#"},ul({cls:"options radio-group"},listItems));this.moveDialog=new ModalDialog({title:"Move this note to...",submitButton:"Ok",contents:formHTML,container:Notes.overflowContainer,parent:this.element,onClose:this.moveDialogResult.bind(this)});}
this.onDialogShow();this.moveDialog.show();Forms.util.selectFirstActiveRadio($E('input[type=radio]',this.moveDialog.dialogBody));return false;},menuPrintClick:function(){var w=window.open(Page.urlToBoard+"/print/"+this.noteId);if(Page.boardOwner=="demo")w.demoNoteData=this.getNoteData();return false;},menuDeleteClick:function(ev){Notes.deleteNote(this.getNoteData());return false;},gc:function(){this.editor.gc();this.moreButton=this.maximizeButton=null;this.moveDialog=null;this.textarea.note=null;this.textarea=null;this.element.note=null;if(this.element.dragObject)
this.element.dragObject=this.element.dragObject.handle=null;this.element=null;},getText:function(){return this.textarea.value.trim();},getTitle:function(){return this.editor.getTitle();}});Note.implement(new Events());Note.forElement=function(elem){if(elem.tagName.toLowerCase()=="textarea")
return elem.note;return elem.getElementsByTagName("textarea")[0].note;};$extend(Notes,{poppedOut:{},popoutMap:{},popoutInit:function(){this.checkPopouts();this.checkPopouts.periodical(1000*5,this);},savePopoutState:function(id,poppedOut){var a=ViewPreferences.getPreference("poppedOut")||{};if(poppedOut)
a[id]=util.timeInSeconds();else
delete a[id];ViewPreferences.setPreference("poppedOut",a);},checkPopouts:function(){if(Notes.popoutLock)return;var a=ViewPreferences.getPreference("poppedOut")||{};var keys=util.keys(a);for(var id in a){if(!this.poppedOut[id]){if((util.timeInSeconds()-a[id])<30)
Notes.popout(id);else
delete a[id];}}
for(var id in this.poppedOut)
if(!a[id])Notes.unpopout(id,{closeWindow:false});if(keys.length!=util.keys(a).length)
ViewPreferences.setPreference("poppedOut");this.poppedOut=a;},popout:function(id,username,boardNumber){if(username&&boardNumber&&(username!=Page.user||boardNumber!=Page.boardNumber))
return;log("popping out from Notes",id);if(this.poppedOut[id])return;Notes.popoutLock=true;var n=$('note'+id);if(n){this.poppedOut[id]=util.timeInSeconds();this.popoutMap[id]=n.note.popout();this.savePopoutState(id,true);}
Notes.popoutLock=false;},unpopout:function(id,options){options=options||{};log("unpopping out from Notes",id,options);if(options.username&&options.boardNumber&&(options.username!=Page.user||options.boardNumber!=Page.boardNumber))
return;if(this.poppedOut[id]){delete this.poppedOut[id];var w=this.popoutMap[id];if(Page.isJjotWindow(w)&&options.closeWindow!=false)
w.close();delete this.popoutMap[id];var n=$('note'+id);if(n)
n.note.unpopout(options);}
Notes.savePopoutState(id,false);}});$extend(Note.prototype,{popoutWindowName:function(){return Page.user+"_"+Page.boardNumber+"_"+this.noteId;},popout:function(){var size=this.element.getSize().size;log("note popup");var popupWindowArgs="resizable=yes,status=no,width="+size.x+",height="+(size.y);var w=window.open(Page.urlToBoard+"/popout/"+this.noteId+"#",this.popoutWindowName(),popupWindowArgs);if(w.listeners)
w.listeners[w.listeners.length]=window;else
w.listeners=[window];if(Page.boardOwner=="demo")w.demoNoteData=this.getNoteData();this.displayPopupControls();return w;},displayPopupControls:function(){this.editor.editorElement().style.visibility="hidden";if(!this.popoutOverlay)this.popoutOverlay=new Overlay();this.popoutOverlay.show(this.element);var d=this.popoutControls=$(document.createElement("div"));d.className="overlay popout-controls";d.style.position="absolute";d.style.left=0;d.style.top=0;d.innerHTML="<div>This note is popped out into another window.<br/><br/>";var b=document.createElement("button");b.innerHTML="Close popped-out window";b.onclick=function(){Notes.unpopout(this.noteId,{focus:true});}.bind(this);d.firstChild.appendChild(b);this.element.appendChild(d);},unpopout:function(options){log("unpopout out from note");if(options.noteData)
this.editor.reinitializeContents(options.noteData.text);if(options.saved==false)
Messages.doSync("save",this.getNoteData());this.popoutControls.remove();this.popoutOverlay.remove();this.editor.editorElement().style.visibility="";if(options.focus){var f=function(){this.focus(true);}.delay(1,this);}}});Debug=new function(){this.useFirebug=true;this.init=function(){log("debgug init");this.debugPrefs={};$(document).addEvent('keydown',this.keydown.bindWithEvent(this));this.parseCookie();this.addButton('Clear cookies',this.clearCookies.bind(this));this.addButton('Print cookies',this.printCookies.bind(this));this.addBoolOption("debugOutput","Enable debug output");this.addBoolOption("instantSave","Instant save");var debugPanel=$('debug-panel');if(!debugPanel)return;Debug.Console.init();if(debugPanel&&(typeof console=="undefined"||!this.useFirebug))
console={log:Debug.Console.log};var tabs=new Controls.TabPanel('debug-tabs');tabs.addTab('console',Debug.Console.element);var o=document.createElement("div");o.id="debug-output";o.innerHTML="output element";tabs.addTab('output panel',o);this.outputElement=$(o);if(this.debugPrefs.panelDisplayed)
$('debug-panel').show();else
$('debug-panel').hide();};this.clearCookies=function(){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){if(cookies[i].indexOf("=")<0)
continue;var cookieName=cookies[i].match(/([^=]*)=/)[1];if(cookieName)
Cookie.remove(cookieName);}};this.printCookies=function(){this.out(document.cookie);};this.out=function(contents,childrenOnly,escapeHtml){if(Page.production||!this.debugPrefs.debugOutput)
return;var html=DomPrinter.print(contents,childrenOnly);if(escapeHtml){var tn=document.createTextNode(html);this.outputElement.appendChild(tn);}else{this.outputElement.innerHTML=html;}};this.outputObject=function(object,childrenOnly){var html=ObjectPrinter.print(object,childrenOnly);this.outputElement.innerHTML=html;};this.close=function(){this.toggle();return false;};this.toggle=function(){$('debug-panel').toggle();var displayed=!($('debug-panel').style.display=="none");this.debugPrefs.panelDisplayed=displayed;this.savePrefs();};this.keydown=function(ev){if(ev.shift&&(ev.control||ev.meta)&&ev.key=="d"){this.toggle();ev.stop();}};this.addButton=function(caption,callback){var b=document.createElement("input");b.type="button";b.value=caption;b.onclick=callback;$('debug-options').appendChild(b);};this.addBoolOption=function(name,caption){var checked=this.debugPrefs[name]?true:false;var div=document.createElement("div");div.innerHTML=input({name:name,type:"checkbox"})+caption;var checkbox=div.getElementsByTagName("input")[0];checkbox.onchange=this.togglePref.bindAsEventListener(this);if(checked)
checkbox.checked="true";$('debug-options').appendChild(div);this.debugPrefs[name]=checked;};this.togglePref=function(ev){ev=new Event(ev);var input=ev.target;var name=ev.target.name;if(input.type=="checkbox")
this.setPref(name,input.checked);};this.getPref=function(name){return this.debugPrefs[name];};this.setPref=function(name,value){this.debugPrefs[name]=value;this.savePrefs();};this.parseCookie=function(){var cookie=Cookie.get('jjot-debug');if(!cookie)
return;cookie=cookie.split(",");cookie=cookie[0]?cookie:[];for(var i=0;i<cookie.length;i++){var keyval=cookie[i].split('=');if(keyval[1]=="false")
keyval[1]=false;this.debugPrefs[keyval[0]]=keyval[1];}};this.savePrefs=function(){var prefs=[];for(key in this.debugPrefs)
prefs.push(key+"="+this.debugPrefs[key]);Cookie.set("jjot-debug",prefs.join(','),{duration:90,path:"/"});};};var TreePrinter=new Class({enableIndent:true,print:function(node,childrenOnly){this.tabIndex=0;this.output="";if(childrenOnly){this.printChildren(node);}else{this.printNode(node);}
return this.output;},writeLine:function(text){var space="";if(this.enableIndent){for(var i=0;i<this.tabIndex*5;i++)
space+="&nbsp;";}
this.output+=space+text;if(this.enableIndent)
this.output+="<br/>";}});var DomPrinter=TreePrinter.extend({printNode:function(node){if(node.nodeType==1){this.printElement(node);}
else if(node.nodeType==3){var out=node.nodeValue;this.writeLine(out);}},printChildren:function(node){var children=node.childNodes;this.tabIndex++;for(var i=0;i<children.length;i++)
this.printNode(children[i]);this.tabIndex--;},printElement:function(node){var tag=node.tagName.toLowerCase();var attr=["id","className","class","style","href"];if(tag=="br"){this.writeLine(this.brackets(tag+DomPrinter.attributeString(node,attr)+"/"));return;}else{this.writeLine(this.brackets(tag+DomPrinter.attributeString(node,attr)));}
this.printChildren(node);this.writeLine(this.brackets(tag,true));},brackets:function(text,end){return"<span class='tag'>&lt;"+(end?"/":"")+text+"&gt;</span>";},elementToString:function(el){return this.brackets;},attributeString:function(node,attributeFilter){var result=[];var attr=node.attributes;for(var i=0;i<attr.length;i++){if(attributeFilter&&!attributeFilter.indexOf(attr[i].nodeNode))continue;var nv=attr[i].nodeValue;if(nv==null||nv==""||$type(nv)=="function")continue;result.push(attr[i].nodeName+"="+attr[i].nodeValue);}
result=result.join(" ");if(result.length>0)
return" "+result;return result;}});var ObjectPrinter=TreePrinter.extend({printNode:function(node){this.printChildren(node);},printChildren:function(node){for(var key in node){try{this.writeLine("<span class='object-key'>"+key+"</span> : "+this.attributeString(node[key]));}catch(e){}}},attributeString:function(attr){if(typeof attr=="function")
return"function()";else
return attr.toString();}});DomPrinter=new DomPrinter();ObjectPrinter=new ObjectPrinter();var Search={matches:[],currentQuery:"",active:false,ni:0,menu:null,menuIndex:null,hidingMenu:false,attachListeners:function(){var s=$('search');s.addEvent('keypress',this.onkeypress.bindWithEvent(this));s.addEvent('keyup',this.onkeyup.bindWithEvent(this));s.addEvent('keydown',this.onkeydown.bindWithEvent(this));s.removeEvent('focus',searchFocusCheck);s.addEvent('focus',function(){searchFocusCheck.bind(this)();Search.hidingMenu=false;if(this.value!=""&&!$(this).hasClass("blank"))
Search.search(this.value,true);});s.addEvent('onblur',function(){Search.menu.destroy();});s.addEvent('click',function(){if(this.value!="")
Search.search(this.value);});},onkeydown:function(ev){if(ev.key=="esc"){this.hidingMenu=!this.hidingMenu;if(this.hidingMenu)
this.menu.hide();else
this.showMenu();ev.stop();}
else if(ev.key=="down"||ev.key=="up"){ev.stop();if($('search').value.length==0||this.matches.length==0)return;if(this.menuIndex==null)
this.menuIndex=ev.key=="down"?0:this.matches.length-1;else if(!this.hidingMenu){this.menuIndex=util.mod(this.menuIndex,this.matches.length,ev.key=="down"?1:-1);}
this.hidingMenu=false;this.highlightNote(this.matches[this.menuIndex]);this.showMenu();}},onkeyup:function(ev){this.search($('search').value);},onkeypress:function(ev){if(ev.key=="enter"){if(this.menuIndex!=null&&!this.hidingMenu){this.highlightNote(this.matches[this.menuIndex],true);ev.stop();}
this.menu.hide();}},search:function(query,force){if(query==this.currentQuery&&this.active&&!force){if(!this.hidingMenu&&(this.menu&&!this.menu.visible()))this.showMenu();return;}
this.currentQuery=query;this.active=true;this.menuIndex=null;if(query.length==0){this.matches=[];Notes.getAll().each(function(n){n.element.removeClass("search-miss");n.element.removeClass("search-hit");$(n.editor.bodyNode()).removeClass("ed-search-miss");});}else
this.highlightResults(query,force);this.showMenu(force);this.updateSearchMessage(query);},highlightResults:function(query,preventFocus){this.matches=[];var regex=new RegExp(RegExp.escape(query),"i");var notes=Notes.getAll();for(var i=0;i<notes.length;i++){var n=notes[i];var el=n.element;var strippedHTML=n.editor.bodyNode().innerHTML.replace(/<.*?>/g,"");if(strippedHTML.test(regex))
{this.matches.push(n);el.removeClass('search-miss');el.addClass('search-hit');$(n.editor.bodyNode()).removeClass("ed-search-miss");if(this.matches.length==1&&!preventFocus)this.highlightNote(n);}else{el.removeClass('search-hit');el.addClass('search-miss');$(n.editor.bodyNode()).addClass("ed-search-miss");}}},buildMenu:function(){var entries=[];for(var i=0;i<this.matches.length;i++)
entries.push({text:this.matches[i].editor.getTitle(),handler:this.menuClick});entries.push({limit:4,outsideClick:this.outsideMenuClick});return entries;},menuClick:function(e){Search.ni=util.dom.indexOfChild(e.target);Search.highlightNote(Search.matches[Search.ni],true);},showMenu:function(force){if(this.matches.length==0||this.currentQuery==""){if(this.menu)this.menu.destroy();return;}
var oldMenu;log("menu",this.menu);if(!this.menu||this.menu.query!=this.currentQuery||force){oldMenu=this.menu;this.menu=new Controls.FileMenu(this.buildMenu());this.menu.query=this.currentQuery;}
if(!this.hidingMenu&&!this.menu.visible()){this.menu.display($('search-box-wrapper'),{width:window.ie6?$('search').getStyle('width').toInt()+5:null});}
if(this.menuIndex!=null)
this.menu.highlight(this.menuIndex);if(oldMenu)oldMenu.destroy.delay(30,oldMenu);},outsideMenuClick:function(ev){return ev.target!=$('search');},deactivate:function(){if(!this.active)return;var m=$$('.search-miss');for(var i=0;i<m.length;i++){var n=$(m[i]).note;n.element.removeClass("search-miss");$(n.editor.bodyNode()).removeClass("ed-search-miss");}
this.active=false;$('search-message').innerHTML="";},updateSearchMessage:function(query){var msg="";if(query.length>0){var c=this.matches.length;msg="<div id='search-caption'>Notes containing the word"+
(query.test(" ")?"s":"")+" <strong>"+" "+query+"</strong></div>"+"<div id='search-count'>"+c+(c==1?" match ":" matches ");if(c>1)
msg+="&nbsp;<a href='#' onclick='return Search.next(-1);'>prev</a> &nbsp;<a href='#' onclick='return Search.next(1);'>next</a></div>";}
$('search-message').innerHTML=msg;},highlightNote:function(note,focusKeyboard){note.focus(focusKeyboard);note.scrollIntoView();},indexOfFocused:function(){var n=Notes.lastFocused;if(n&&n.element.parentNode&&!n.element.hasClass("search-miss"))
return this.matches.indexOf(n);return this.ni;},next:function(direction){this.ni=util.mod(Search.indexOfFocused(),this.matches.length,direction);this.highlightNote(this.matches[this.ni]);return false;}};Archived={notes:[],currentPage:0,pageSize:6,init:function(){this.archivedElement=$('archived');this.navLinks=$('archived-nav');Messages.addEvent("unarchive",this.unarchive.bind(this));this.buildList();},unarchive:function(noteData){Notes.newNote(noteData.id,noteData.text,{flashEffect:true,saveContents:false});this.removeFromArchive(noteData.id);Page.showStatus("");},removeFromArchive:function(id,animate){if(this.deleteAnimation)
this.buildList(this.currentPage);var n=this.noteForID(id);var whenFinished=function(){this.buildList(this.currentPage);this.deleteAnimation=null;};this.notes.remove(n);var element=$E('#archived a[noteid='+id+']');if(element&&animate){this.deleteAnimation=$(element).effect('opacity',{duration:400,onComplete:whenFinished.bind(this)});this.deleteAnimation.start(1.0,0);}else
whenFinished.bind(this)();},noteForID:function(id){return this.notes.filter(function(e){return e.id==id;})[0];},onclick:function(ev){ev=new Event(ev);Messages.doSync("unarchive",{id:ev.target.getAttribute("noteid")});return false;},listItemHtml:function(id,title){return"<li style=''><a class='bar' href='#' noteid='"+id+"' title='"+title.replace(/'/g,"\\'")+"'>"+title+"</a>"+"<a href='#' class='delete' title='Delete from archive' "+"></a></li>";},trashcanClick:function(ev){ev=new Event(ev);var noteLink=$(ev.target).getPrevious();var data=Archived.noteForID(noteLink.getAttribute("noteid"));Notes.deleteNote(data);return false;},buildList:function(page,animateFirst){if(this.deleteAnimation)
this.deleteAnimation.stop();page=page||0;var maxPage=Math.floor((this.notes.length-1)/this.pageSize);if(maxPage>=0&&page>maxPage)page=maxPage;var html="";var start=this.pageSize*page;var end=this.pageSize*(page+1);if(end>this.notes.length)
end=this.notes.length;for(var i=start;i<end;i++){var n=this.notes[i];html+=this.listItemHtml(n.id,Notes.formatTitleForDisplay(n.title));}
this.archivedElement.innerHTML=html;var links=this.archivedElement.getElementsByTagName("A");for(var i=0;i<links.length;i++)
links[i].onclick=links[i].className=="delete"?this.trashcanClick:this.onclick;if(animateFirst){var f=$(this.archivedElement.getElementsByTagName('LI')[0]);Page.flashEffect(f,"background-color","#ffffff");Page.flashEffect($E('.delete',f),"background-color","#ffffff");}
if(this.notes.length>this.pageSize){var li=$(this.archivedElement.firstChild);var height=li.getSize().size.y+(window.ie7?3:0);this.archivedElement.style.height=this.pageSize*height+"px";this.buildNavLinks(page);}
else{this.archivedElement.style.height="";this.navLinks.innerHTML="";}
return false;},buildNavLinks:function(page){var prev="&#171;prev";if(page==0)
prev="<span class='nav unselectable'>"+prev+"</span>";else
prev="<a href='#' class='nav unselectable' onclick='return Archived.prev();'>"+prev+"</a>";var next="next&#187;";if(this.pageSize*(page+1)<this.notes.length)
next="<a href='#' class='nav' onclick='return Archived.next();'>"+next+"</a>";else
next="<span class='nav unselectable'>"+next+"</span>";this.navLinks.innerHTML=prev+next;},add:function(noteData){this.notes.unshift(noteData);Messages.doSync("archive",noteData);this.buildList(this.currentPage,true);Page.showStatus("Archived \""+Notes.formatTitleForDisplay(noteData.title)+"\".",function(){Messages.doSync("unarchive",{id:noteData.id});return false;});},next:function(){return Archived.buildList(++Archived.currentPage);},prev:function(){return Archived.buildList(--Archived.currentPage);}};rte.LinkEditor=new Class({domainRegex:/^((\w:\/\/)?[\w:\/]{2,}\.)+(com|org|net|us|info|gov|biz|jp|ca)(\/[\w\.#,?=]*)*$/,wordBoundariesRegex:/([\n\s\>\<!\t]+)/,wordBoundariesRegex:/([\s\>\<!\t]+)/,breakApart:function(string){var tokens=string.split(this.wordBoundariesRegex);var html="";for(var i=0;i<tokens.length;i++){var str=tokens[i];if(!this.isUrl(str)){html+=str.replace(/ /g,'&nbsp;');}
else
html+=this.linkHtml("http://www.google.com",str);}
return html;},searchLeft:function(startNode,n,start){console.log("startNode,n,start:",startNode,n,start);while(n>=0&&startNode)
{var textNode=this.findChildTextNode(startNode);startNode=startNode.previousSibling;if(!textNode)
continue;var textLength=$pick(start,textNode.nodeValue.length);if(n-textLength<=0)
{var newRange=this.cw.document.createRange();newRange.setStart(textNode,textLength-n);newRange.setEnd(textNode,textLength-n);return newRange;}
n-=textLength;}
return null;},findChildTextNode:function(node){do{if(node.nodeType==3)
return node;node=node.firstChild;}while(node);return null;},restoreSelectionAfterInsert:function(originalSelection,replacedSelection){log("restore selection after insert");var selection=this.cw.getSelection().getRangeAt(0);var node=selection.startContainer;log("repl sel:",replacedSelection);var target=node.nodeType==3?node:node.childNodes[selection.startOffset-1];log("target chosen:",target);var n=0;log("node:",node);log("orig start offset:",originalSelection.startOffset);log("sel offset",selection.startOffset);var start=null;n=replacedSelection.endOffset-originalSelection.startOffset;log("n2",n);if(node.nodeType==3)
start=selection.startOffset;var toSelect=this.searchLeft(target,n,start);log("final startOffset:",toSelect.startOffset);log(toSelect.startContainer);log("final endOffset:",toSelect.endOffset);log(toSelect);this.setSelection(toSelect);},checkLinks:function(){return;log("CHECK LINKS");var selection=this.cw.getSelection();var textNode=selection.anchorNode;if(textNode.nodeType!=3)
return;var nodeValue=textNode.nodeValue;var range=selection.getRangeAt(0);var span=textNode.parentNode;if(span.parentNode&&span.parentNode.tagName=="A"){if(!this.isUrl(nodeValue)){log("string that's in this link (",nodeValue,") is not a url");var newHtml=this.breakApart(nodeValue);log("new html:",newHtml);var originalSelection=new rte.RangeContainer(this.cw.getSelection().getRangeAt(0));var replacedSelection=this.cw.document.createRange();replacedSelection.selectNode(span.parentNode);var toRestore=new rte.RangeContainer(replacedSelection);toRestore.startOffset=0;toRestore.endOffset=nodeValue.length;log("nodevalue:",nodeValue,nodeValue.length);log("building around",toRestore);var replacedSelectionContainer=new rte.RangeContainer(replacedSelection);this.makeSelectionIntoLink(replacedSelectionContainer,newHtml,false);this.restoreSelectionAfterInsert(originalSelection,toRestore);this.attachLinkHandlers();return;}else{return;}}
var wordRange=this.nearestWord(range);if(this.isUrl(wordRange.contents)){this.makeSelectionIntoLink(wordRange,this.linkHtml("http://www.google.com",wordRange.contents),true);}},safeInsertHtml:function(wordRange,replaceWith){},makeSelectionIntoLink:function(wordRange,linkHtml,autoRestoreSelection){log("making current text selection into a new URL.");this.savedSel=new rte.SavedSelection(this);this.createLinkAroundRange(wordRange,linkHtml,autoRestoreSelection);if(this.hasBuggedLinkNodes()){log("there was a bugged link. Undoing");this.cw.document.execCommand("undo",false,false);this.savedSel.restore();var scrolled=this.cw.pageYOffset>0;if(scrolled){this.saveScrollPosition();this.iframe.style.visibility="hidden";}
this.cw.document.body.style.overflow="hidden";var modifiedHtml=linkHtml+"<br/>";log("inserting modified:",modifiedHtml);this.createLinkAroundRange(wordRange,modifiedHtml,autoRestoreSelection);this.cw.document.body.style.overflow="";if(scrolled){this.restoreScrollPosition();this.iframe.style.visibility="visible";}}},hasBuggedLinkNodes:function(){var links=this.cw.document.getElementsByTagName("A");for(var i=0;i<links.length;i++){if(links[i].hasAttribute("_moz_dirty")&&links[i].offsetWidth==0){log("found dirty link:",links[i]);return true;}}
log("did not find a dirty link");return false;},recycle:function(){log("recycling");var s=new rte.SavedSelection(this);this.syncContents();this.buildIframe();s.restore();}});Overlay=new Class({show:function(element){if(!this.overlay)
this.overlay=new Element(Overlay.createElement());var o=this.overlay;element.appendChild(o);if(element==document.body){var w=$(window).getSize();o.style.height=w.scrollSize.y+"px";}
o.style.display="block";},remove:function(){if(!this.overlay)return;this.overlay.getParent().removeChild(this.overlay);this.overlay=null;}});Overlay.extendStatic({createElement:function(){var o=document.createElement("div");var s=o.style;s.display="none";o.className="overlay white-overlay";s.position="absolute";s.left=0;s.top=0;return o;}});Nta=new Class({initialize:function(){this.ids=[];this.data=[];},set:function(id,data){var i=this.ids.indexOf(id);if(i==-1){this.ids.push(id);this.data.push(data);}else{this.data[i]=data}},get:function(id){var i=this.ids.indexOf(id);if(i==-1)
return null;else
return this.data[i];},remove:function(id){var i=this.ids.indexOf(id);if(i!=-1){this.ids.splice(i,1);this.data.splice(i,1);}},empty:function(){return this.ids.length==0;}});NoteOperations=new Class({initialize:function(){this.ntas=["save","move","unmove","archive","unarchive","trash","untrash"];for(var i=0;i<this.ntas.length;i++){var x=this.ntas[i];this[x]=new Nta();}
this._saveOrder=false;},empty:function(){for(var i=0;i<this.ntas.length;i++){var x=this.ntas[i];if(!this[x].empty()){return false;}}
return!this._saveOrder;},saveNote:function(hash){this.save.set(hash.id,hash);},moveNote:function(hash){if(this.unmove.get(hash.id)==null){this.move.set(hash.id,hash);}else{this.unmove.remove(hash.id);}},unmoveNote:function(hash){var id=hash.id;if(this.move.get(id)==null){this.unmove.set(id,hash.board);}else{var noteData=this.move.get(id).note;this.move.remove(id);Messages.fireEvent("unmove",noteData);}},archiveNote:function(hash){var id=hash.id;if(this.unarchive.get(id)==null){this.archive.set(id,hash);}else{this.unarchive.remove(id);}},unarchiveNote:function(hash){var id=hash.id;if(this.archive.get(id)==null){this.unarchive.set(id,id);}else{var noteData=this.archive.get(id);this.archive.remove(id);Messages.fireEvent("unarchive",noteData);}},trashNote:function(hash){var id=hash.id;if(this.untrash.get(id)==null){this.trash.set(id,hash);}else{this.untrash.remove(id);}},untrashNote:function(hash){var id=hash.id;if(this.trash.get(id)==null){this.untrash.set(id,id);}else{var noteData=this.trash.get(id);this.trash.remove(id);if(note.text){Messages.fireEvent("untrash",noteData);}else{this.untrash.set(id,id);}}},saveOrder:function(){this._saveOrder=true;}});Messages=new Class({syncTimer:null,queuedNotes:new NoteOperations(),inTransit:null,currSleepOnFailure:2500,syncDelay:2000,continuousEditDelay:10000,maxRetryDelay:30000,firstQueued:null,doSync:function(method,hash){if(Page.shared)return;method=method+"Note";this.queuedNotes[method](hash);Messages.queueSend();},saveOrder:function(){this.queuedNotes.saveOrder();Messages.queueSend();},queueSend:function(){if(Page.demo||Debug.getPref("saveChanges")==false)
return;if(!this.queuedNotes.move.empty()||!this.queuedNotes.unarchive.empty()||!this.queuedNotes.untrash.empty()){theDelay=10;}else{theDelay=this.syncDelay;}
Messages.showSaveStatus();if(this.syncTimer==null){this.syncTimer=Messages.syncWithServer.delay(theDelay,this);var d=new Date();this.firstQueued=d.getTime();}else if(this.inTransit==null){var d=new Date();if(d.getTime()-this.firstQueued<this.continuousEditDelay){$clear(this.syncTimer);this.syncTimer=Messages.syncWithServer.delay(theDelay,this);}}},syncWithServer:function(){if(this.inTransit==null){this.currSleepOnFailure=2500;this.inTransit=this.queuedNotes;}else if(!this.queuedNotes.empty()){var queue=this.queuedNotes;for(var i=0;i<queue.ntas.length;i++){var x=queue.ntas[i];var method=x+"Note";for(var j=0;j<queue[x].data.length;j++){var y=queue[x].data[j];this.inTransit[method](y);}}
if(this.queuedNotes._saveOrder==true)
this.inTransit._saveOrder=true;}
this.queuedNotes=new NoteOperations();this.showSaveStatus();this.sendSyncRequest();},packsave:function(id,note){return{id:id,text:note.text,title:note.title};},packmove:function(id,hash){return{id:id,board:hash.board};},packunmove:function(id,board){return{id:id,board:board};},packarchive:function(id,note){return id;},packunarchive:function(id,dummy_id){return id;},packtrash:function(id,note){return id;},packuntrash:function(id,dummy_id){return id;},sendSyncRequest:function(){var postBody={};postBody.boardNumber=Page.boardNumber;var trans=this.inTransit;if(trans._saveOrder)
postBody.order=Notes.noteIds();for(var i=0;i<trans.ntas.length;i++){var x=trans.ntas[i];if(!trans[x].empty()){postBody[x]=[];for(var j=0;j<trans[x].ids.length;j++){var id=trans[x].ids[j];var data=trans[x].data[j];postBody[x].push(Messages["pack"+x](id,data));}}}
var a=new Ajax("/"+Page.boardOwner+"/"+Page.boardNumber+"/"+"sync",{method:'post',postBody:Json.toString(postBody),onSuccess:function(response){var lastSave=$('last-save');if(lastSave){lastSave.innerHTML=(new Date()).getTime();}
Messages.syncTimer=Messages.inTransit=null;if(!Messages.queuedNotes.empty())
Messages.queueSend();Messages.showSaveStatus();if(response==""||response==" ")
return;var data=eval('('+response+')');var undoActions=["unmove","unarchive","untrash"];for(var i=0;i<undoActions.length;i++){var x=undoActions[i];if(data[x]){for(var j=0;j<data[x].length;j++){var y=data[x][j];Messages.fireEvent(x,y);}}}},onFailure:function(){Messages.currSleepOnFailure=Math.round(Messages.currSleepOnFailure*1.5);if(Messages.currSleepOnFailure>this.maxRetryDelay)
Messages.currSleepOnFailure=this.maxRetryDelay;Messages.syncTimer=Messages.syncWithServer.delay(Messages.currSleepOnFailure,Messages);}});a.request();},showSaveStatus:function(currentlySaving){if(this.inTransit)
Page.showSaveStatus(Page.saveStatus.saving);else if(!this.queuedNotes.empty())
Page.showSaveStatus(Page.saveStatus.unsaved);else
Page.showSaveStatus(Page.saveStatus.saved);}});Messages.implement(new Events);Messages=new Messages();rte.util={};rte.util.Node={findParentWithTag:function(node,tagName,limit){if(!node.tagName)
node=node.parentNode;while(node&&node.tagName!=tagName&&node!=limit)
node=node.parentNode;return node==limit?null:node;},nextTextNode:function(node){do{node=node.nextSibling;}while(node!=null&&node.nodeType!=3);return node;}};rte.util.Display={lineHeight:function(){if(!this.heightNode||!this.heightNode.parentNode){var h=document.createElement("span");h.style.position="absolute";h.style.visibility="hidden";h.style.left=h.style.top=0;h.id="lineheight-calc";h.innerHTML="&nbsp;";document.body.appendChild(h);this.heightNode=$(h);}
return this.heightNode.getStyle('height').toInt();}};rte.util.HTML={scrapeText:function(str){return str.replace(this.blockRegex,' ').replace(this.removeHTMLRegex,'');},removeHTMLRegex:new RegExp("<[^<]*>","g"),blockRegex:new RegExp("</(li|div|p|h\d)>","i")};rte.Mozilla=new Class({correctSelection:function(){var selectedRange=this.cw.getSelection().getRangeAt(0);var s=selectedRange.startContainer;if(s!=selectedRange.endContainer)
return;if(!this.insideParagraph(s)){log("selection is not inside a paragraph node. Setting it to be inside the first p in the editor.");var p=this.cw.document.getElementsByTagName("P")[0];var newSel=this.cw.document.createRange();newSel.setStart(p,0);newSel.setEnd(p,0);this.setSelection(newSel);}},insideParagraph:function(node){while(node&&node.tagName!="P")
node=node.parentNode;return node?true:false;}});var StretchyGrid={container:null,noteSize:4,notesPerLine:null,init:function(){$(window).addEvent('resize',this.recalcNoteWidths.bindAsEventListener(this));this.container=$('note-area');var pref=ViewPreferences.getPreference("size");this.setNoteSize(pref?pref.toInt():this.noteSize);},recalcNoteWidths:function(){var containerWidth=this.container.getStyle('width').toInt();var d=StretchyGrid.noteDimensions(this.noteSize);var currentNotesPerLine=Math.floor(containerWidth/d.width);if(currentNotesPerLine!=this.notesPerLine||this.notesPerLine==null){this.notesPerLine=currentNotesPerLine;this.setNotesPerLine(currentNotesPerLine);}},setNotesPerLine:function(perLine){var adjust=0;if(window.ie)
adjust=(25/this.container.getStyle('width').toInt()*100)/perLine+0.1;Stylesheets.rules.note[0].style.width=(100/perLine)-adjust+"%";var maximizedWidth=100/this.notesPerLine*3;Stylesheets.rules.maximized[0].style.width=maximizedWidth>100?100-(perLine*adjust)+"%":maximizedWidth-adjust*3+"%";},setNoteSize:function(size){if(size<2||size>10)
return;this.noteSize=size;var d=StretchyGrid.noteDimensions(this.noteSize);this.recalcNoteWidths();var rules=Stylesheets.rules;rules.note[0].style.height=(d.height)+"px";if(window.ie)
rules.ghostElementDiv[0].style.height=(d.height-12)+"px";else
rules.ghostElementDiv[0].style.height=(d.height-8)+"px";var heightBetweenNotes=Stylesheets.rules.note[0].style.marginBottom.toInt();var noteEl=$E('.note');var paddingSize=36;if(noteEl)
paddingSize=this.notePaddingHeight(noteEl);rules.editor[0].style.height=(d.height-paddingSize)+"px";rules.editorParent[0].style.height=(d.height-paddingSize)+"px";var maximizedHeight=2*d.height+heightBetweenNotes;rules.maximized[0].style.height=maximizedHeight+"px";rules.maximizedEditor[0].style.height=maximizedHeight-paddingSize+"px";rules.maximizedEditorParent[0].style.height=maximizedHeight-paddingSize+"px";},bigger:function(){this.setNoteSize(this.noteSize+1);ViewPreferences.setPreference("size",this.noteSize);},smaller:function(){this.setNoteSize(this.noteSize-1);ViewPreferences.setPreference("size",this.noteSize);},notePaddingHeight:function(parent){var child;var height=0;do{child=parent.getFirst();height+=this.sumProperties(child,"padding-top","padding-bottom","margin-top","margin-bottom");parent=child;}while(!child.className.contains("titlebar"));var titlebar=child;var divider=titlebar.getNext();height+=titlebar.getStyle("height").toInt()+
this.sumProperties(divider,"height","margin-top","margin-bottom");return height;},sumProperties:function(){var sum=0,a=arguments,el=a[0];for(var i=1;i<arguments.length;i++){var v=el.getStyle(arguments[i]);sum+=((v=="auto")?0:v.toInt());}
return sum;}};StretchyGrid.noteDimensions=function(noteSize){var d={};var widthMulti=1.04;var heightMulti=1.03;d.width=Math.floor(Math.pow(widthMulti,noteSize)*noteSize*45+50);d.height=Math.floor(Math.pow(heightMulti,noteSize)*noteSize*45+40);return d;};rte.Links=new Class({domainRegex:/^((\w:\/\/)?[\w:\/]{2,}\.)+(com|uk|de|org|net|us|info|gov|biz|jp|ca)(\/[\w\.#,?=]*)*$/,toolbarLink:function(){var selectedText=this.selectedRange();var node=selectedText.startContainer;var caption=selectedText.toString();var href;var linkElement=rte.util.Node.findParentWithTag(node,"A");if(!linkElement&&caption.trim().match(this.domainRegex))
href=caption.trim();return this.showLinkEditorDialog(linkElement,caption,href);},showLinkEditorDialog:function(linkElement,caption,href){rte.LinkMenu.hide();if(!this.linkDialog){var formHTML=form({action:"#",cls:"create-link-form"},TableLayout.build([label("URL:"),input({type:"text",name:"url",cls:"field",value:"http://",autocomplete:"off"})],[label("Caption:"),input({type:"text",name:"caption",cls:"field",autocomplete:"off"})]));this.linkDialog=new ModalDialog({title:linkElement?"Edit this link":"Create a link",submitButton:"Ok",contents:formHTML,container:Notes.overflowContainer,parent:this.textarea.note.element,onClose:this.dialogResult.bind(this),buttons:[{value:"Remove link",name:"remove-link",cls:"remove-link submit"}],onShow:function(){var url=$E('input[name=url]',this.linkDialog);if(url.value=="www.")url.select();}.bind(this)});}
if(this.undoManager.isDirty)
this.undoManager.saveState();this.savedSelection=this.selectedRange();this.existingLink=linkElement;if(href==null)
href="www.";var dialogForm=$E('form',this.linkDialog.dialogBody);if(linkElement){log("editing existing");href=linkElement.href;log("link's href",linkElement.href);caption=util.unescapeHTML(rte.util.HTML.scrapeText(linkElement.innerHTML));if(href.toLowerCase().startsWith("http://"))
href=href.substring(7);log(href);dialogForm["remove-link"].disabled=false;}else
dialogForm["remove-link"].disabled=true;dialogForm["url"].value=href;dialogForm["caption"].value=caption;this.fireEvent('dialogShow',this);this.linkDialog.show();return false;},protocols:["http://","https://","ffp://","mailto:"],dialogResult:function(ev){if(!ev.cancelled){var targetElement=ev.eventArgs.target;var removeLink=targetElement&&$(targetElement).hasClass("remove-link");var caption=util.escapeHTML($E('input[name=caption]',ev.dialog).value);var url=$E('input[name=url]',ev.dialog).value.trim();url=url.replace(/www\.http:\/\//,"http://");var startsWith=this.protocols.filter(function(p){return url.startsWith(p);});if(startsWith.length==0)
url="http://"+url;if(this.existingLink){var node;if(removeLink)
node=this.documentNode().createTextNode(caption);else{node=this.documentNode().createElement("A");node.href=url;node.innerHTML=caption;}
this.existingLink.parentNode.replaceChild(node,this.existingLink);this.setSelectionAfter(node);this.existingLink=null;}else{var html="<a href='"+url+"'>"+caption+"</a>";this.setSelection(this.savedSelection);this.execCommand("inserthtml",html);}
this.undoManager.saveState();this.attachLinkHandlers();this.checkForChanges();}else{this.setSelection(this.savedSelection);}
this.fireEvent('dialogHide',this);if(!this.ce)this.focus();},linkClick:function(ev){var ev=new Event(ev);ev.stop();var target=rte.util.Node.findParentWithTag(ev.target,"A");if(!target.href.startsWith("http://"))
return;if(true)
window.open(target.href);else
window.location=target.href;},linkMouseOver:function(ev){if(rte.dragging||Page.shared)return;$clear(rte.LinkMenu.timer);if(window.ie)this.bodyNode().style.cursor="pointer";ev=new Event(ev);var target=ev.target;if(target.tagName!="A")
target=rte.util.Node.findParentWithTag(target,"A");target=$(target);window.status=target.href;var coords=target.getCoordinates();var relativeCoords=this.editorElement().getPosition();var bodyScroll=$(this.bodyNode()).getSize().scroll;var editorOverflow=this.ce?this.bodyNode().parentNode:this.bodyNode();var coords=target.getCoordinates([Notes.overflowContainer,editorOverflow]);if(!this.ce){coords.left+=this.editorElement().getPosition().x;coords.top+=this.editorElement().getPosition().y;}
rte.LinkMenu.show(coords,target,this);},linkMouseOut:function(){if(Page.shared)return;if(window.ie)this.bodyNode().style.cursor="";if(rte.LinkMenu.menu)
rte.LinkMenu.hideWithDelay(150);window.status="";},attachLinkHandlers:function(){var links=this.bodyNode().getElementsByTagName('A');for(var i=0;i<links.length;i++){if(!links[i].rteLinked){links[i].rteLinked={};util.attach(links[i],'click',this.linkClick);util.attach(links[i],'mouseover',this.linkMouseOver.bindAsEventListener(this));util.attach(links[i],'mouseout',this.linkMouseOut.bindAsEventListener(this));}}}});rte.LinkMenu={mouseoverClassname:"jj-mouseover",show:function(coords,linkElement,editor){var m=rte.LinkMenu.menu;if(!m){log("creating link menu");m=document.createElement("div");m.id="edit-link";m.style.position="absolute";m.style.display="none";m.innerHTML="<a href='#'><div>edit</div></a>";m.onmouseover=this.mouseOver;m.onmouseout=this.mouseOut;document.body.appendChild(m);rte.LinkMenu.menu=$(m);}
if(this.currentLink)
this.currentLink.removeClass(rte.LinkMenu.mouseoverClassname);this.currentLink=$(linkElement);this.currentLink.addClass(rte.LinkMenu.mouseoverClassname);m.getElementsByTagName('a')[0].onclick=editor.showLinkEditorDialog.pass([linkElement],editor);m.style.left=coords.left-1+"px";m.style.top=coords.top+rte.util.Display.lineHeight()-4+"px";m.show();},mouseOver:function(ev){$clear(rte.LinkMenu.timer);},mouseOut:function(ev){rte.LinkMenu.hideWithDelay(300);},hide:function(){if(m=rte.LinkMenu.menu)m.hide();},hideWithDelay:function(ms){rte.LinkMenu.timer=function(){rte.LinkMenu.menu.hide();rte.LinkMenu.currentLink.removeClass(rte.LinkMenu.mouseoverClassname);}.delay(ms);}};ModalDialog=new Class({defaultOptions:{cancelButton:true,modal:true},initialize:function(options){this.options=$merge(this.defaultOptions,options);log(this.options);this.wrapper=new Element(ModalDialog.dialogWrapperTemplate.cloneNode(true));this.dialogBody=$E('.dialog-body',this.wrapper);if(options.width)
this.dialogBody.style.width=this.options.width;this.dialogBody.innerHTML=this.buildDialogHtml(this.options);this.addButtons(this.options,this.options.buttons);this.form=new Forms.EnhancedForm(this.dialogBody,{validateKeypress:options.validateKeypress,validateSubmit:options.validateSubmit,cancel:this.cancel.bindAsEventListener(this),submit:this.closeHandler.bindWithEvent(this)});$E('.x',this.wrapper).onclick=this.cancel.bindAsEventListener(this);this.parent=$(this.options.parent||document.body);this.options.container=this.options.container||this.parent;},addButtons:function(options,buttons){if(options.cancelButton||options.submitButton){var submit=options.submitButton?input({type:"submit",cls:"submit",value:options.submitButton}):"";var cancel=options.cancelButton?input({type:"button",cls:"cancel",value:"Cancel"}):"";var others="";if(buttons)
buttons.each(function(b){others+=input({type:"button",cls:b.cls,value:b.value,name:b.name});});var buttonArea=document.createElement("div");buttonArea.className="buttonset";buttonArea.innerHTML=others+submit+cancel;var container=$E('form',this.dialogBody)?$E('form',this.dialogBody):this.dialogBody;container.appendChild(buttonArea);}},buildDialogHtml:function(options){var html="";html+=a({href:"#",cls:"x close"},"");if(options.title)html+=h4(options.title);html+=div({cls:"contents"},options.contents);return html;},closeHandler:function(ev){this.close(false,ev);},close:function(cancelled,ev){var eventArgs={cancelled:cancelled==true?true:false,dialog:this.wrapper,eventArgs:ev};var cancelRemove=false;if(this.options.onClose)
this.options.onClose(eventArgs);if(!eventArgs.cancelClose){this.wrapper.hide();this.wrapper.parentNode.removeChild(this.wrapper);if(this.overlay)
this.overlay.remove();}
return false;},cancel:function(ev){return this.close(true,ev);},centerInsideParent:function(){var p=(this.parent==document.body)?window:this.parent;var parentPos=p.getSize();var parentCenter={x:p.getWidth()/2,y:p.getHeight()/2};this.wrapper.style.left="-9000px";this.wrapper.style.top=0;this.wrapper.style.left=0;this.wrapper.show();var dialogLeft=parentCenter.x-this.wrapper.offsetWidth/2;var dialogTop=this.options.top||(parentCenter.y-this.wrapper.offsetHeight/2);this.wrapper.style.left=dialogLeft+"px";this.wrapper.style.top=dialogTop+"px";this.adjustEdges(this.wrapper);},show:function(){if(!this.wrapper.getParent())
this.parent.appendChild(this.wrapper);this.wrapper.style.overflow="";this.wrapper.style.width="";if(this.options.showAnimation)
this.options.showAnimation(this.wrapper);else
this.centerInsideParent();this.wrapper.style.width=this.wrapper.getStyle('width');this.wrapper.style.overflow="auto";if(this.options.modal){if(!this.overlay)this.overlay=new Overlay();this.overlay.show(this.parent);}
if(this.form)
this.form.show();if(this.options.onShow)
this.options.onShow();},adjustEdges:function(element){element=$(element);var w=$(this.options.container);if(w==document.body)w=window;var s=w.getSize();var containerCoords=w.getCoordinates();var coords=element.getCoordinates();log("size:",s);log("container coords:",containerCoords);cc=containerCoords;var scrolled=s.scrollSize.y>s.size.y;var pad=3;var rightPad=19;if(coords.bottom>containerCoords.top+s.scrollSize.y+pad){log("clips bottom");element.style.top=element.getStyle('top').toInt()-(coords.bottom-(containerCoords.top+s.scrollSize.y+pad));}
coords=element.getCoordinates();if(coords.top<(containerCoords.top+pad))
element.style.top=element.style.top.toInt()+(containerCoords.top+pad-coords.top)+"px";if(coords.right+rightPad>containerCoords.right){log("clips right");var q=(element.getStyle('left').toInt()-(coords.right+rightPad-containerCoords.right));element.style.left=q+"px";}}});ModalDialog.implement(new Events);ModalDialog.init=function(){var wrapperHTML=div({cls:"padding"},div({cls:"dialog-body padding2"}));var t=document.createElement("div");t.className="dialog dialog-wrapper";t.style.display="none";t.innerHTML=wrapperHTML;this.dialogWrapperTemplate=t;};Debug.Console={init:function(){var d=document.createElement("div");d.innerHTML='<div id="debug-eval"><span class="caret">&gt;&gt; </span><input type="text" id="debug-eval-box"></input>'+'<span id="debug-eval-buttons"><input class="clear" type="button" value="clear"><input class="clear" type="button" value="exec"></input>'+' <input class="help" type="button" value="?"></input></span></div>';var inputs=$ES('input',d);Debug.Eval.init(inputs[0]);inputs[1].onclick=this.clear;inputs[2].onclick=Debug.Eval.evaluate.bind(Debug.Eval);var log=document.createElement("div");log.id="debug-log";d.appendChild(log);this.element=d;},clear:function(){$('debug-log').innerHTML="";},log:function(){var d=document.createElement('div');d.className="log-line";for(var i=0;i<arguments.length;i++){var a=arguments[i];Debug.Console.addLogLine(a);d.appendChild(Debug.Console.addLogLine(a));}
var s=$(Debug.Console.element).getSize();$('debug-log').appendChild(d);var s=$('debug-log').getSize();var f=function(){$('debug-log').scrollTo(false,s.scrollSize.y+500);};f.delay(20);},addLogLine:function(o){var e;if(o==null)
return this.textElement("null ");var t=$type(o);switch(t){case"string":var str=(o=="")?"\"\"":o;e=this.textElement(str+" ");break;case"function":e=this.textElement("function() ");break;case"undefined":e=this.textElement("undefined ");break;case"element":var s=this.elementToString(o);return this.textElement(s);break;case"object":e=document.createElement("a");e.href="#";e.innerHTML=Debug.Console.objectToString(o)+" ";e.onclick=function(){Debug.outputObject(o);return false;};break;default:e=this.textElement(o.toString()+" ");}
return e;},elementToString:function(el){return"<"+el.tagName.toLowerCase()+" "+DomPrinter.attributeString(el,["id","className","style","href"])+">";},objectToString:function(o){if(o instanceof Error){return"<span class='error'>Error: "+o.message+"</span>";}else if(o instanceof Array){return"["+o.join(", ")+"]";}else{var count=0;var props=[];for(var k in o){if(typeof o[k]!="function"){props.push(k);count++;}
if(count>=3)
break;}
var str="Object ";for(var i=0;i<count;i++)
str+=props[i]+"="+o[props[i]]+" ";return str;return o.toString();}},textElement:function(text){return document.createTextNode(text);}};Debug.Eval={init:function(evalBox){$(evalBox).addEvent('keypress',this.keypress.bindWithEvent(this.keypress,this));},keypress:function(ev){if(ev.key=="enter"){ev.stop();Debug.Eval.evaluate();}},evaluate:function(){var js=$('debug-eval-box').value.trim();if(js=="")
return;log(eval(js));}};if(typeof Controls=="undefined")Controls={};Controls.TabPanel=new Class({tabClick:function(){this.parentNode.parentNode.tabPanel.activate(this);return false;},initialize:function(e){e=$(e);e.className="tab-panel";this.tabs=document.createElement("div");this.tabs.className="tabs";this.bodies=document.createElement("div");this.bodies.className="tab-bodies";e.appendChild(this.tabs);e.appendChild(this.bodies);e.tabPanel=this;},addTab:function(name,contentNode){var a=document.createElement('a');a.href="#";a.innerHTML=name;a.onclick=this.tabClick;a.className="tab";this.tabs.appendChild(a);var tab=document.createElement("div");tab.className="tab";tab.appendChild(contentNode);this.bodies.appendChild(tab);contentNode.style.height="200px";if(this.tabs.childNodes.length==1)
this.activate(a);},activate:function(a){var i=util.dom.indexOfChildByTagName(a,"A");var links=util.dom.childrenWithTagName(a.parentNode,"A");util.dom.removeClass(links,"active");$(a).addClass('active');var divs=a.parentNode.parentNode.getElementsByTagName("div");var tabBody=a.parentNode.nextSibling;divs=tabBody.getElementsByTagName("div");var divs=util.dom.childrenWithTagName(tabBody,"DIV");util.dom.removeClass(divs,"active");$(divs[i]).addClass("active");}});if(typeof Controls=="undefined")Controls={};Controls.FileMenu=new Class({initialize:function(){var args=arguments.length==1&&arguments[0]instanceof Array?arguments[0]:arguments;var itemCount=0;var d=document.createElement("div");d.id="menu";d.className="menu";var ul=$(document.createElement("ul"));for(var i=0;i<args.length;i++)
{if(!args[i].text){this.toggleButton=args[i].toggleButton;this.outsideClickHandler=args[i].outsideClick;this.limit=args[i].limit;continue;}
itemCount++;var e;if(args[i].disabled)
e=document.createElement("span");else{e=document.createElement("a");e.href="#";e.onclick=jjotutil.nullClick;if(args[i].handler)
util.attach(e,"click",this.makeClickHandler(args[i].handler));}
e.innerHTML=args[i].text;ul.appendChild(e);}
d.appendChild(ul);ul.getFirst().className="first";this.el=new Element(d);},makeClickHandler:function(userFunction){return function(ev){var res=userFunction(new Event(ev));Controls.FileMenu.active.hide();return res;};},display:function(target,options){Controls.FileMenu.init();Controls.FileMenu.active=this;options=options||{};target=$(target);var parent=target.getParent();var left,top,right;if(options.anchorRight){right=options.right||(target.getParent().getSize().size.x-
(target.getLeft()-parent.getLeft()+target.getSize().size.x)-3);}else{left=options.left||(target.getLeft()-parent.getLeft()-1);}
top=target.getTop()-parent.getTop()+target.getSize().size.y;top=options.top||target.getSize().size.y;var e=this.el;e.style.top=top+"px";if(options.anchorRight)
e.style.right=right+"px";else
e.style.left=left+"px";if(options.width)
e.style.width=e.getFirst().style.width=options.width.toInt()+"px";e.style.visibility="hidden";e.show();document.body.appendChild(e);var links=e.getElementsByTagName("a");if(this.limit&&links.length>this.limit)
{var itemSize=$(links[0]).getStyle("height").toInt();var padding=4;e.getFirst().style.height=Math.ceil(itemSize*this.limit)+padding+"px";e.getFirst().style.overflowY="auto";}
e.injectBefore(target);e.style.visibility="";},visible:function(){return this.el.getParent()&&this.el.style.display!="none";},highlight:function(index){var links=this.el.getElementsByTagName("a");for(var j=0;j<links.length;j++)
links[j].className=links[j].className.replace("highlight","");links[index].className+=" highlight";this.el.getFirst().scrollUntilVisible(links[index],0);this.el.getFirst().scrollLeft=0;},outsideClick:function(ev){return(this.outsideClickHandler)?this.outsideClickHandler(ev):true;},hide:function(){this.el.hide();if(Controls.FileMenu.active==this)Controls.FileMenu.active=null;this.fireEvent('hide',this);},destroy:function(){this.hide();if(this.el.getParent())
this.el.getParent().removeChild(this.el);}});Controls.FileMenu.implement(new Events());Controls.FileMenu.extendStatic({hideActive:function(ev){var a;if(a=Controls.FileMenu.active)
if(a.outsideClick(ev))a.hide();},click:function(ev){var a=Controls.FileMenu.active;if(!a)return;var ev=new Event(ev);if(ev.target!=a.toggleButton&&!util.dom.descendsFrom(ev.target,a.el)){Controls.FileMenu.hideActive(ev);}},init:function(){if(!this.setupEvents){document.addEvent('mousedown',Controls.FileMenu.click);rte.Events.addEvent('click',Controls.FileMenu.click);}
this.setupEvents=true;}});rte.Range={moveToElementText:function(range){var node=range.startContainer;var offset=range.startOffset;while(node.nodeType!=3){node=node.childNodes[offset];offset=0;}
range.setStart(node,offset);}};rte.Range.Extension=new Class({newRangeContaining:function(startNode,startOffset,endNode,endOffset){var r=this.newRange();if(typeof startOffset=="undefined"){r.selectNode(startNode);return r;}
r.setStart(startNode,startOffset);if(typeof endNode=="undefined")
r.setEnd(startNode,startOffset);else
r.setEnd(endNode,endOffset);return r;},newRange:function(){if(window.ie)
return new rte.Range.IERange(document.body.createTextRange());else
return this.documentNode().createRange();},placeCursorInside:function(node){if(window.ie){var s=document.body.createTextRange();s.moveToElementText(node);s.collapse(false);s.select();}else
this.setSelection(this.newRangeContaining(node,0));},setSelectionAfter:function(node){var sel;var sib=node.nextSibling;if(sib){sel=this.newRangeContaining(node.parentNode,util.dom.indexOfChild(sib));}
else
sel=this.newRangeContaining(node.parentNode,util.dom.indexOfChild(node)+1);this.setSelection(sel);return sel;},selectionAtEndOfNode:function(node){if(node.nodeType==3)
return this.newRangeContaining(node,node.nodeValue.length);else
if(node.lastChild)
return this.selectionAtEndOfNode(node.lastChild);else
return this.newRangeContaining(node.parentNode,util.dom.indexOfChild(node.parentNode,node)+1);}});rte.Range.IERange=Class({initialize:function(range){this._range=range;this.collapsed=null;this.commonAncestorContainer=null;this.startContainer=null;this.startOffset=null;this.endContainer=null;this.endOffset=null;var beginRange=this._range.duplicate();beginRange.collapse(true);if(typeof thr!="undefined"&&thr)throw"come debug me";var position=this._getPosition(beginRange);this.startContainer=position.node;this.startOffset=position.offset;var endRange=this._range.duplicate();endRange.collapse(false);position=this._getPosition(endRange);this.endContainer=position.node;this.endOffset=position.offset;this._commonAncestorContainer();this._collapsed();},isTextNode:function(type){return["textnode","whitespace"].test(type);},newRange:function(){return document.body.createTextRange();},_getPositionOriginal:function(textRange){var element=this._range.parentElement();var range=document.body.createTextRange();range.moveToElementText(element);range.setEndPoint("EndToStart",textRange);var rangeLength=range.text.length;if(rangeLength<element.innerText.length/2){var direction=1;var node=element.firstChild;}else{direction=-1;node=element.lastChild;range.moveToElementText(element);range.setEndPoint("StartToStart",textRange);rangeLength=range.text.length;}
while(node){var type=$type(node);var moveToSibling=true;switch(type){case"textnode":case"whitespace":nodeLength=node.data.length;if(nodeLength<rangeLength){var difference=rangeLength-nodeLength;if(direction==1)range.moveStart("character",difference);else range.moveEnd("character",-difference);rangeLength=difference;}
else{if(direction==1){if(typeof thr!="undefined"&&thr)throw"come debug me";return{node:node,offset:rangeLength};}
else{if(typeof thr!="undefined"&&thr)throw"come debug me";return{node:node,offset:nodeLength-rangeLength};}}
break;case"element":nodeLength=node.innerText.length;if(nodeLength>rangeLength){if(direction==1)node=node.firstChild;else node=node.lastChild;moveToSibling=false;}else{if(direction==1)range.moveStart("character",nodeLength);else range.moveEnd("character",-nodeLength);rangeLength=rangeLength-nodeLength;}
break;}
if(!moveToSibling)continue;if(direction==1)node=node.nextSibling;else node=node.previousSibling;}
if(typeof thr!="undefined"&&thr)throw"come debug me";return{node:element,offset:0};},junkChars:/[\n\r]/,junkCharsGlobal:/[\n\r]/g,filterRangeText:function(str){return str.replace(this.junkCharsGlobal,"");},_getPosition:function(textRange){var element=this._range.parentElement();var range=document.body.createTextRange();range.moveToElementText(element);range.setEndPoint("EndToStart",textRange);var rangeLength=this.filterRangeText(range.text).length;if(rangeLength<element.innerText.length/2){var direction=1;var node=element.firstChild;}else{direction=-1;node=element.lastChild;range.moveToElementText(element);range.setEndPoint("StartToStart",textRange);rangeLength=this.filterRangeText(range.text).length;}
while(node){if(direction==1){while(range.text.charAt(0).match(this.junkChars))
range.moveStart("character",1);}else{while(range.text.charAt(range.text.length-1).match(this.junkChars))
range.moveStart("character",-1);}
var type=$type(node);var moveToSibling=true;switch(type){case"textnode":case"whitespace":nodeLength=node.data.length;if(nodeLength<rangeLength){var difference=rangeLength-nodeLength;if(direction==1)range.moveStart("character",difference);else range.moveEnd("character",-difference);rangeLength=difference;}
else{if(direction==1){if(typeof thr!="undefined"&&thr)throw"come debug me";return{node:node,offset:rangeLength};}
else{if(typeof thr!="undefined"&&thr)throw"come debug me";return{node:node,offset:nodeLength-rangeLength};}}
break;case"element":nodeLength=this.filterRangeText(node.innerText).length;if(nodeLength>rangeLength){if(direction==1)node=node.firstChild;else node=node.lastChild;moveToSibling=false;}else{if(direction==1)range.moveStart("character",nodeLength);else range.moveEnd("character",-nodeLength);rangeLength=rangeLength-nodeLength;}
break;}
if(!moveToSibling)continue;if(direction==1)node=node.nextSibling;else node=node.previousSibling;}
if(typeof thr!="undefined"&&thr)throw"come debug me";return{node:element,offset:0};},_getOffset:function(startNode,startOffset){var node,moveCharacters;var t=$type(startNode);if(this.isTextNode(t)){moveCharacters=startOffset;node=startNode.previousSibling;}
else if(t=="element"){moveCharacters=0;if(startOffset>0)node=startNode.childNodes[startOffset-1];else return 0;}
else{log("bad node given, apparently");return 0;}
while(node){var nodeLength=0;var t=$type(node);if(t=="element"){nodeLength=node.innerText.length;if(this._isChildless(node))nodeLength=1;if(this._isBlock(node))nodeLength++;}
else if(this.isTextNode(t)){nodeLength=node.data.length;}
moveCharacters+=nodeLength;node=node.previousSibling;}
return moveCharacters;},_getOffsetFromParent:function(startNode,startOffset){var node,moveCharacters;var range=document.body.createTextRange();var t=$type(startNode);if(this.isTextNode(t)){moveCharacters=startOffset;node=startNode.previousSibling;}
else if(t=="element"){moveCharacters=0;if(startOffset>0)node=startNode.childNodes[startOffset-1];else return{moveCharacters:0};}
else{log("bad node given, apparently");return 0;}
while(node){var nodeLength=0;var t=$type(node);if(t=="element"){if(this._isBlock(node))moveCharacters++;range.moveToElementText(node);break;}
else if(this.isTextNode(t)){nodeLength=node.data.length;}
moveCharacters+=nodeLength;node=node.previousSibling;}
return{range:range,moveCharacters:moveCharacters};},_isBlock:function(node){switch(node.nodeName.toLowerCase()){case'p':case'div':case'h1':case'h2':case'h3':case'h4':case'h5':case'h6':case'pre':return true;}
return false;},_isChildless:function(node){switch(node.nodeName.toLowerCase()){case'img':case'br':case'hr':return true;}
return false;},setStart:function(startNode,startOffset){var container=startNode;if(typeof d2!="undefined"&&d2)throw"come debug me";if(this.isTextNode($type(startNode))){container=container.parentNode;}
var copyRange=this._range.duplicate();copyRange.moveToElementText(container);copyRange.collapse(true);var offsets=this._getOffsetFromParent(startNode,startOffset);if(offsets.range){offsets.range.collapse(false);copyRange.setEndPoint("EndToEnd",offsets.range);copyRange.collapse(false);}
copyRange.move("Character",offsets.moveCharacters);copyRange.move('Character',-1);this._range.setEndPoint('StartToStart',copyRange);this.startContainer=startNode;this.startOffset=startOffset;if(this.endContainer==null&&this.endOffset==null){this.endContainer=startNode;this.endOffset=startOffset;}
this._commonAncestorContainer();this._collapsed();},setEnd:function(endNode,endOffset){var copyRange=this._range.duplicate();copyRange.collapse(true);var container=endNode;if(this.isTextNode($type(endNode))){container=container.parentNode;}
copyRange=this._range.duplicate();copyRange.moveToElementText(container);copyRange.collapse(true);var offsets=this._getOffsetFromParent(endNode,endOffset);if(offsets.range){offsets.range.collapse(false);copyRange.setEndPoint("EndToEnd",offsets.range);copyRange.collapse(false);}
copyRange.move("Character",offsets.moveCharacters);copyRange.move('Character',-1);this._range.setEndPoint('EndToEnd',copyRange);this.endContainer=endNode;this.endOffset=endOffset;if(this.startContainer==null&&this.startOffset==null){this.startContainer=endNode;this.startOffset=endOffset;}
this._commonAncestorContainer();this._collapsed();},setStartBefore:function(referenceNode){this.setStart(referenceNode.parentNode,util.dom.indexOfChild(referenceNode));},setStartAfter:function(referenceNode){this.setStart(referenceNode.parentNode,util.dom.indexOfChild(referenceNode)+1);},setEndBefore:function(referenceNode){this.setEnd(referenceNode.parentNode,util.dom.indexOfChild(referenceNode));},setEndAfter:function(referenceNode){this.setEnd(referenceNode.parentNode,util.dom.indexOfChild(referenceNode)+1);},selectNode:function(referenceNode){this.setStartBefore(referenceNode);this.setEndAfter(referenceNode);},selectNodeContents:function(referenceNode){this.setStart(referenceNode,0);if($(referenceNode)=="textnode")
this.setEnd(referenceNode,referenceNode.data.length);else
this.setEnd(referenceNode,referenceNode.childNodes.length);},collapse:function(toStart){this._range.collapse(toStart);if(toStart){this.endContainer=this.startContainer;this.endOffset=this.startOffset;}else{this.startContainer=this.endContainer;this.startOffset=this.endOffset;}
this._commonAncestorContainer();this._collapsed();},cloneContents:function(){var df=document.createDocumentFragment();var container=this.commonAncestorContainer;if(this.isTextNode($type(container))){df.appendChild(document.createTextNode(this._range.text));return df;}
var endOffset=this.endOffset;var startNode=this.startContainer;if($type(startNode)!="textnode")
startNode=this.startContainer.childNodes[this.startOffset];var endNode=this.endContainer;if(!this.isTextNode($type(endNode))){endNode=this.endContainer.childNodes[this.endOffset-1];if(this.isTextNode($type(endNode)))
endOffset=endNode.data.length;else
endOffset=endNode.childNodes.length;}
if(startNode==endNode){if(this.isTextNode($type(startNode))){df.appendChild(document.createTextNode(startNode.data.substring(this.startOffset,endOffset)));}else{for(var i=this.startOffset;i<endOffset;i++)
df.appendChild(startNode.childNodes[i].cloneNode(true));log("warning: we should be copying all children in this case");if(typeof thr!="undefined"&&thr)throw("");}
return df;}
var current=container.firstChild;var parent=null;var clone;var content;while(current){if(!parent){if(this.isAncestorOf(current,startNode,container)){parent=df;}
else{current=current.nextSibling;continue;}}
if(current==startNode&&$type(this.startContainer)=="textnode"){content=this.startContainer.data.substring(this.startOffset);parent.appendChild(document.createTextNode(content));}
else if(current==endNode){if($type(this.endContainer)=="textnode"){content=this.endContainer.data.substring(0,endOffset);parent.appendChild(document.createTextNode(content));}
else parent.appendChild(endNode.cloneNode(false));break;}
else{clone=current.cloneNode(false);parent.appendChild(clone);}
if(current.firstChild){parent=clone;current=current.firstChild;}
else if(current.nextSibling){current=current.nextSibling;}
else while(current){if(current.parentNode){parent=parent.parentNode;current=current.parentNode;if(current.nextSibling){current=current.nextSibling;break;}}
else current=null;}}
return df;},deleteContents:function(){this._range.pasteHTML('');this.endContainer=this.startContainer;this.endOffset=this.startOffset;this._commonAncestorContainer();this._collapsed();},extractContents:function(){var fragment=this.cloneContents();this.deleteContents();return fragment;},insertNode:function(newNode){if(this.isTextNode($type(this.startContainer))){startOffset=this.startOffset>this.startContainer.data.length?this.startContainer.data.length:this.startOffset;this.startContainer.splitText(startOffset);this.startContainer.parentNode.insertBefore(newNode,this.startContainer.nextSibling);this.setStart(this.startContainer,startOffset);return;}else{var parentNode=this.startContainer.parentNode;if(this.startContainer.childNodes.length==this.startOffset){parentNode.appendChild(newNode);}else{this.startContainer.insertBefore(newNode,this.startContainer.childNodes.item(this.startOffset));this.setStart(this.startContainer,this.startOffset+1);return;}}},surroundContents:function(newNode){newNode.appendChild(this.extractContents());this.insertNode(newNode);},compareBoundaryPoints:function(how,sourceRange){alert('mozile.dom.InternetExplorerRange.compareBoundaryPoints() is not implemented yet');},cloneRange:function(){var r=new mozile.dom.InternetExplorerRange(this._range.duplicate());var properties=["startContainer","startOffset","endContainer","endOffset","commonAncestorContainer","collapsed"];for(var i=0;i<properties.length;i++){r[properties[i]]=this[properties[i]];}
return r;},detach:function(){},toString:function(){return this._range.text;},_commonAncestorContainer:function(){if(this.startContainer==null||this.endContainer==null){this.commonAncestorContainer=null;return;}
if(this.startContainer==this.endContainer){this.commonAncestorContainer=this.startContainer;}
else{this.commonAncestorContainer=this.getCommonAncestor(this.startContainer,this.endContainer);return null;}},isAncestorOf:function(ancestorNode,descendantNode,limitNode){var checkNode=descendantNode;while(checkNode){if(checkNode==ancestorNode)return true;else if(checkNode==limitNode)return false;else checkNode=checkNode.parentNode;}
return false;},getCommonAncestor:function(firstNode,secondNode){var ancestor=firstNode;while(ancestor){if(this.isAncestorOf(ancestor,secondNode))return ancestor;else ancestor=ancestor.parentNode;}
return null;},_collapsed:function(){this.collapsed=(this.startContainer==this.endContainer&&this.startOffset==this.endOffset);}});rte.Control=new Class({initialize:function(textarea){this.onMousemove=Class.empty;this.onChanged=Class.empty;this.textarea=$(textarea);this.textarea.setStyle('display','none');this.titlebar=$('c'+textarea.id+"_buttons");this.commands=new rte.Commands(this);this.toolbar=new rte.Toolbar(this.titlebar,this);this.toolbar.addButtons();if(typeof newNoteTimer!="undefined")log("content editable:",((new Date()).getTime()-newNoteTimer)/1000);this.createEditorElement();this.textarea.editor=this;this.editActions=0;},setupControl:function(){this.attachEvents();this.attachLinkHandlers();this.textarea.value=this.oldContent=this.bodyNode().innerHTML;this.undoManager=new rte.undo.Manager(this);if(this.queuedFunctions){this.queuedFunctions.each(function(f){f();});this.queuedFunctions=[];}},reinitializeContents:function(contents){this.textarea.value=this.oldContent=this.bodyNode().innerHTML=contents;this.undoManager=new rte.undo.Manager(this);this.textarea.title=this.getTitle();this.attachLinkHandlers();},attachEvents:function(){var d=this.containerDocument();var keyEvent=this.keyEvent.bindWithEvent(this);util.attach(d,'keydown',keyEvent);util.attach(d,'keypress',keyEvent);util.attach(d,'keyup',this.keyup.bindWithEvent(this));util.attach(d,'mouseup',this.toolbar.determineButtonStates.bindAsEventListener(this.toolbar));util.attach(d,'focus',this.editorFocused.bindAsEventListener(this));util.attach(d,'blur',this.editorBlurred.bindAsEventListener(this));},keyEvent:function(ev){if(rte.KeyListeners.runHandlerForKey(ev,this))
return;if(!this.ce&&(ev.control||ev.meta))
Page.Hotkeys.runHandlerForKey.pass([ev],Page.Hotkeys).delay(2);},keyup:function(ev){if(ev.code==16||ev.code==17||ev.code==18||ev.code==224)
return;if((ev.key=="z"||ev.key=="y")&&(ev.control||ev.meta)){}else if(ev.key!=""){if(this.bodyNode().innerHTML!=this.textarea.value){this.insertTitleIfMissing();}}
this.checkForChanges();this.toolbar.determineButtonStates();this.fireEvent('keypress',this);Debug.out(this.bodyNode(),true);},reflowTitleNode:function(){this.undoManager.saveState();var currentRange=this.selectedRange();log("reflowing title node");var titleNode=this.getTitleNode();if(!util.dom.descendsFrom(currentRange.startContainer,titleNode))
return false;var offsetFromBody=util.dom.indexOfChild(titleNode);var leftHalfRange=this.newRange();leftHalfRange.selectNodeContents(titleNode);leftHalfRange.setEnd(currentRange.startContainer,currentRange.startOffset);var leftHalf=leftHalfRange.cloneContents();var rightRange=this.newRange();rightRange.selectNodeContents(titleNode);rightRange.setStart(currentRange.startContainer,currentRange.startOffset);var rightHalf=rightRange.cloneContents();var rightHTML=util.dom.fragmentInnerHTML(rightHalf);if(rightHTML.length==0)rightHTML="<br/>";rightHTML="<p>"+rightHTML+"</p>";var newTitle="<p class='title'>"+util.dom.fragmentInnerHTML(leftHalf)+"</p>"+rightHTML;this.getTitleNode().remove();this.bodyNode().innerHTML=newTitle+this.bodyNode().innerHTML;if(window.ie)
this.placeCursorInside(this.getTitleNode());else
this.placeCursorInside(this.getTitleNode().nextSibling);this.undoManager.saveState();this.recentUndo=true;this.attachLinkHandlers();this.checkForChanges();return true;},insertTitleIfMissing:function(){var bodyNode=this.bodyNode();var firstChild=bodyNode.firstChild;var titleNodes=this.getTitleNodes();if(firstChild&&firstChild.className&&firstChild.className.contains("title")&&firstChild.tagName=="P"&&titleNodes.length==1)
return;for(var i=0;i<titleNodes.length;i++)
titleNodes[i].removeClass("title");if(!firstChild){bodyNode.innerHTML="<p class='title'></p>";this.placeCursorInside(this.getTitleNode());}else if(firstChild.tagName=="P"){firstChild.className="title";}else if(firstChild.nodeType==3){var replacing=firstChild.nodeValue?firstChild.nodeValue:firstChild.innerHTML;if(!replacing)replacing="<br/>";var newHTML="<p class='title'>"+replacing+"</p>";bodyNode.removeChild(firstChild);bodyNode.innerHTML=newHTML+bodyNode.innerHTML;if(!window.ie){var sel;if(replacing.match(/^<br\s*\/?>$/)){sel=this.newRangeContaining(this.getTitleNode(),0);}else{sel=this.selectionAtEndOfNode(this.getTitleNode());}
this.setSelection(sel);}else{this.placeCursorInside(this.getTitleNode());}}},getTitleNodes:function(){if(window.newFirefox)
return $A(this.cw.document.getElementsByClassName('title')).map(function(e){return $(e);});else
return $ES('.title',this.bodyNode());},getTitleNode:function(){if(window.newFirefox)
return $(this.cw.document.getElementsByClassName('title')[0]);else
return $E('.title',this.bodyNode());},cleanupText:function(text){return text.replace(rte.cleanupRegex,"");},getContents:function(){return this.textarea.value;},checkForChanges:function(){if(!this.editorIsReady())
return;this.textarea.value=this.cleanupText(this.bodyNode().innerHTML);this.textarea.title=this.getTitle();if(this.textarea.value!=this.oldContent)
{this.attachLinkHandlers();this.editActions++;if(this.recentUndo){this.recentUndo=false;this.editActions=0;}
else{var diff=Math.abs(this.oldContent.length-this.textarea.value.length);if(diff>50||this.editActions>7){this.undoManager.saveState();this.editActions=0;}else
this.undoManager.dirty();}
this.oldContent=this.textarea.value;this.fireEvent("changed",this);}},beforeDrag:function(){rte.dragging=true;if(!this.ce){this.saveScrollPosition();this.checkForChanges();}},afterDrag:function(){rte.dragging=false;if(window.ie)return;this.executeWhenReady(function(){this.restoreScrollPosition();}.bind(this));},saveScrollPosition:function(){this.savedScrollOffset=[this.cw.pageXOffset,this.cw.pageYOffset];},restoreScrollPosition:function(){this.cw.scrollBy(this.savedScrollOffset[0],this.savedScrollOffset[1]);this.savedScrollOffset=null;},editorIsReady:function(){if(this.ce)
return true;else
return this.cw&&this.cw.document?true:false;},editorFocused:function(ev){if(!Page.shared)
this.undoManager.focused();this.oldContent=this.textarea.value;rte.focusedEditor=this;this.fireEvent('focus',this);Debug.out(this.bodyNode(),true);},editorBlurred:function(ev){if(!this.editorIsReady())
return;this.checkForChanges();rte.focusedEditor=null;this.fireEvent('blur',this);},iframeMouseMove:function(ev){ev.relativeTo=this.iframe;rte.Events.fireEvent('mousemove',ev);this.fireEvent('mousemove',ev);},iframeMouseUp:function(ev){ev.relativeTo=this.iframe;rte.Events.fireEvent('mouseup',ev);},iframeClick:function(ev){rte.Events.fireEvent('click',ev);},executeWhenReady:function(funcs){if($type(funcs)=="function")
funcs=[funcs];this.queuedFunctions=this.queuedFunctions||[];this.queuedFunctions=this.queuedFunctions.concat(funcs);if(this.editorIsReady()){this.queuedFunctions.each(function(f){f();});this.queuedFunctions=[];}},selectAll:function(){var range=this.cw.document.createRange();range.selectNodeContents(this.bodyNode());this.setSelection(range);},selectTitleNode:function(){if(window.ie){var r=document.body.createTextRange();r.moveToElementText(this.getTitleNode());r.select();}else{var r=this.newRange();r.selectNode(this.getTitleNode().firstChild);r.selectNodeContents(this.getTitleNode());this.setSelection(r);}},focus:function(){if(this.ce)
this.containerDocument().focus();else
this.cw.focus();},setSelection:function(newRange){if(window.ie)
newRange._range.select();else{var selection=this.selection();selection.removeAllRanges();selection.addRange(newRange);}},selection:function(){if(!this.ce)
return this.cw.getSelection();else{return window.ie?document.selection:window.getSelection();}},editorElement:function(){return this.ce?this.div:this.iframe;},documentNode:function(){return this.ce?document:this.cw.document;},bodyNode:function(){return this.ce?this.div:this.cw.document.body;},execCommand:function(commandName,argument){var doc=this.ce?document:this.cw.document;if(window.ie&&commandName.toLowerCase()=="inserthtml")
this.selectedRange()._range.pasteHTML(argument);else
doc.execCommand(commandName,false,argument);},containerDocument:function(){if(this.ce)
return this.div;else
return this.cw.document;},selectedRange:function(){if(window.ie){var sel=document.selection;return new rte.Range.IERange(document.selection.createRange());try{return new rte.Range.IERange(document.selection.createRange());}catch(e){log("exception returning IERange");return null;}}else{var sel=this.selection();try{return sel.getRangeAt(0);}
catch(e){log("Mozilla exception while calling this.selection().getRangeAt(0)");}
return null;}},formatTitle:function(title){var t=title?rte.util.HTML.scrapeText(title):"";return t.replace(/&nbsp;/g," ").trim();},getTitle:function(){if(!this.editorIsReady())
return this.textarea.title;var titleNode=this.getTitleNode();return this.formatTitle(titleNode?titleNode.innerHTML:this.bodyNode().innerHTML.substring(0,60));},gc:function(){this.div=this.cw=null;this.textarea=this.textarea.editor=null;this.titlebar=this.commands=null;}});rte.ContentEditableControl=rte.Control.extend({createEditorElement:function(){this.ce=true;var d=$(document.createElement("div"));d.className="editor ce";d.innerHTML=this.textarea.value;d.injectBefore(this.textarea);if(!Page.shared)
d.contentEditable="true";this.div=d;this.setupControl();}});rte.IFrameControl=rte.Control.extend({createEditorElement:function(){this.iframe=new Element(document.createElement("iframe"));this.iframe.className="editor";this.iframe.id=this.textarea.id+"_if";this.cw=null;this.iframe.addEvent('load',this.iframeLoad.bindAsEventListener(this));this.iframe.injectBefore(this.textarea);},iframeLoad:function(){if(!this.buildIframe()){log("was not able to build iframe");return;}},buildIframe:function(){doc=this.iframe.contentWindow.document;var body=$(this.iframe.contentWindow.document.body);body.spellcheck=false;this.cw=this.iframe.contentWindow;var head=doc.getElementsByTagName("head")[0];if(window.newFirefox)
head.appendChild(doc.adoptNode(rte.styleSheetNode.cloneNode(true)));else
head.appendChild(rte.styleSheetNode.cloneNode(true));this.cw.log=console.log;var d=doc.createElement("script");d.innerHTML="window.mozFind=function(){try{window.find('hey')}catch(e){log(e);}};"
head.appendChild(d);body.innerHTML=this.textarea.value;doc.designMode="on";body.addEvent('mousemove',this.iframeMouseMove.bindAsEventListener(this));body.addEvent('click',this.iframeClick);body.addEvent('mouseup',this.iframeMouseUp.bindAsEventListener(this));this.setupControl();if(Page.shared)this.execCommand("contentReadOnly");this.execCommand("insertBrOnReturn",false);return true;}});rte.newControl=function(textarea){if(window.gecko)
return new rte.IFrameControl(textarea);else
return new rte.ContentEditableControl(textarea);};rte.KeyListeners={init:function(){this.keydown={};this.keypress={};var add=this.add.bind(this);var kd="keydown";var kp="keypress";add(kd,"tab",this.switchNote);add(kd,"shift_tab",this.switchNote);if(Page.shared){add(kd,"ctrl_k",function(){});return;}
add(kd,"ctrl_k",this.link);add(kd,"ctrl_l",this.link);add(kd,"ctrl_y",this.redo);add(kd,"ctrl_z",this.ctrlZ);add(kd,"ctrl_shift_z",this.ctrlZ);add(kd,"meta_z",this.ctrlZ);add(kd,"meta_shift_z",this.ctrlZ);add(kp,"enter",this.enter,{cancel:false});add(kp,"up",this.up,{cancel:false});if(!window.webkit)
{add(kd,"ctrl_b",function(){rte.focusedEditor.commands.bold();});add(kd,"ctrl_i",function(){rte.focusedEditor.commands.italic();});add(kd,"ctrl_u",function(){rte.focusedEditor.commands.unorderedList();});}},ctrlZ:function(ev,ed){if(ev.shift)
rte.KeyListeners.redo(ev,ed);else
rte.KeyListeners.undo(ev,ed);},undo:function(ev,ed){if(ed.undoManager.undo())
ed.recentUndo=true;},redo:function(ev,ed){if(ed.undoManager.redo())
ed.recentUndo=true;},link:function(ev,ed){ed.toolbarLink();},switchNote:function(ev,ed){var el=ed.textarea.note.element;var n=ev.shift?el.getPrevious():el.getNext();if(!n||!n.note){var na=$('note-area');n=ev.shift?na.getLast().getPrevious():na.getFirst();}
n.note.scrollIntoView(window.ie?0:100);n.note.focus(true);},bold:function(ev,ed){ed.commands.bold();},up:function(ev,ed){var previous=ed.getTitleNode().previousSibling;var noSibling=!previous||($type(previous)=="whitespace"&&!previous.previousSibling);if(noSibling&&util.dom.descendsFrom(ed.selectedRange().startContainer,ed.getTitleNode())){ed.setSelection(ed.newRangeContaining(ed.getTitleNode(),0));ev.stop();}},enter:function(ev,ed){ed.insertTitleIfMissing();if(ed.reflowTitleNode())
ev.stop();}};rte.KeyListeners=$extend(rte.KeyListeners,HotkeyManager);rte.Toolbar=new Class({initialize:function(titlebar,editor){this.editor=editor;this.titlebar=$(titlebar);},addButtons:function(){this.bold=this.titlebar.getElementsBySelector(".bold")[0];this.bold.title="Bold "+this.hotkeyString("B");this.link=this.titlebar.getElementsBySelector(".link")[0];this.link.title="Create link "+this.hotkeyString("K");this.bullets=this.titlebar.getElementsBySelector(".bullets")[0];this.bullets.title="Create bulleted list "+this.hotkeyString("U");if(window.webkit){this.bold.setStyle('display','none');this.link.setStyle('display','none');this.bullets.setStyle('display','none');return;}
if(!Page.shared){this.link.onclick=this.editor.toolbarLink.bind(this.editor);this.bold.onclick=this.editor.commands.bold.bind(this.editor.commands);this.bullets.onclick=this.editor.commands.unorderedList.bind(this.editor.commands);}else
this.link.onclick=this.bold.onclick=this.bullets.onclick=function(){return false;};GC.run(this.gc.bind(this));},hotkeyString:function(c){var str="Ctrl"+"+"+c;return"("+str+")";},toggled:function(button){var button=$('c'+this.editor.textarea.id+'_'+button);return button.hasClass('on');},setChecked:function(button,state){var button=$('c'+this.editor.textarea.id+'_'+button);if(!button.hasClass('on'))
button.addClass('on');},determineButtonStates:function(){var parent;if(window.ie){var sel=this.editor.selection();var range=sel.createRange();try{parent=range.parentElement();}catch(e){return false;}}else{var range=this.editor.selectedRange();if(!range)return;parent=range.commonAncestorContainer;parent=parent.parentNode;}
var children=this.titlebar.childNodes;$(this.titlebar).getChildren().each(function(child){if(child.hasClass('on'))
child.removeClass('on');});var d=this.editor.documentNode();if(d.queryCommandState('bold'))
$(this.bold).addClass('on');if(d.queryCommandState('unlink'))
$(this.link).addClass('on');if(parent&&rte.util.Node.findParentWithTag(parent,"A",this.editor.editorElement()))
$(this.link).addClass('on');return;if(this.editor.iframe.contentWindow.document.selection)
{selection=this.editor.selection();range=selection.createRange();try{parent=range.parentElement();}catch(e){return false;}}
else
{try{selection=this.editor.selection();}catch(e){console.log("exception: ",e);return false;}
range=selection.getRangeAt(0);if(!range.commonAncestorContainer)
log("!!no ancestor container");log(range);parent=range.commonAncestorContainer;}
while(parent.nodeType==3){parent=parent.parentNode;}
while(parent.nodeName.toLowerCase()!="body"){switch(parent.nodeName.toLowerCase()){case"span":if(parent.getAttribute("style").test("font-weight: bold;")){this.setChecked('bold',true);}
break;}
parent=parent.parentNode;}},gc:function(){this.titlebar=this.bold=this.link=this.bullets=null;}});rte.undo={cc:'\u2009',bookmark:"SELECTION",bookmark:'\u2009',undoNodeID:"jj-undobm"};rte.undo.Manager=new Class({initialize:function(editor){this.ed=editor;this.stack=[];this.save(0,false);this.current=0;this.isDirty=false;},newCursorNode:function(level){var span=this.ed.documentNode().createElement("span");span.id="rte-undo-"+level;span.innerHTML="HI";return span;},saveState:function(){this.save(++this.current);log("saved ",this.current);},focused:function(){if(this.focusedOnce||this.isDirty||this.current>0)return;this.focusedOnce=true;this.save(0);},dirty:function(){this.isDirty=true;},save:function(level,saveSelection){this.stack.splice(level);var undoState={};undoState.html=this.editorContents();if(saveSelection!=false){var sel=this.ed.selectedRange();if(sel&&this.ed.ce){if(!util.dom.descendsFrom(sel.commonAncestorContainer,this.ed.bodyNode()))
sel=null;}
if(sel){undoState=this.bookmarkedHTML(sel);}else
log("no valid selection to save during undo");}
this.stack[level]=undoState;this.isDirty=false;},bookmarkedHTML:function(sel){if(window.ie){var original=document.selection.createRange();var newSel=original.duplicate();newSel.collapse(true);newSel.text=rte.undo.bookmark;newSel.moveStart("character",-rte.undo.bookmark.length);html=this.editorContents();newSel.select();this.ed.execCommand("delete");original.select();return{html:html,opts:null};}else{var newDom;var saved=new rte.ClonedRange(this.ed.selectedRange(),this.ed);if(window.newFirefox){var newDom=document.importNode(this.ed.bodyNode(),true);newDom.style.display="none";document.body.appendChild(newDom);}else{var newDom=this.ed.bodyNode().cloneNode(true);}
var r=saved.createRange(newDom);if(window.newFirefox)
newDom.parentNode.removeChild(newDom);var opts={};var sc=r.startContainer;if(sc.nodeType==3){if(sc.previousSibling){sc=sc.previousSibling;opts.previousSibling=true;}
else{sc=sc.parentNode;opts.parentNode=true;}}
opts.offset=r.startOffset;sc.id=rte.undo.undoNodeID;return{html:newDom.innerHTML,opts:opts};var bookmark=this.ed.documentNode().createTextNode(rte.undo.bookmark);var saved=new rte.ClonedRange(this.ed.selectedRange(),this.ed);var newDom=this.ed.bodyNode().cloneNode(true);var r=saved.createRange(newDom);r.insertNode(bookmark);return newDom.innerHTML;if(!sel.collapsed)
this.ed.bodyNode().normalize();sel=this.ed.selectedRange();var bookmark=this.ed.cw.document.createTextNode(rte.undo.bookmark);var originallyCollapsed=sel.collapsed;var savedSelection=new rte.RangeContainer(sel);var r=sel.cloneRange();r.collapse(true);var bookmark=this.ed.documentNode().createTextNode(rte.undo.bookmark);r.insertNode(bookmark);html=this.editorContents();if(!originallyCollapsed)
this.ed.setSelection(r);if(this.ed.cw.mozFind(rte.undo.bookmark,false,false,true))
this.ed.cw.getSelection().deleteFromDocument();else
log("!did not find the bookmark we just inserted... find it going backwards?:",this.ed.cw.mozFind(rte.undo.bookmark,false,true,true));if(originallyCollapsed){this.ed.setSelection(sel);}else{this.ed.bodyNode().normalize();this.ed.setSelection(savedSelection.buildRange(this.ed.documentNode()));}}
return html;},undo:function(){log("doing undo");if(!this.isDirty){if(this.current>0)
this.current--;else
return false;}else{this.save(this.current+1);}
log("revert to state ",this.current);this.ed.bodyNode().innerHTML=this.stack[this.current].html;this.restoreSelection(this.current);this.ed.attachLinkHandlers();this.isDirty=false;return true;},restoreSelection:function(level){if(window.ie){var r=document.body.createTextRange();r.moveToElementText(this.ed.bodyNode());if(r.findText(rte.undo.bookmark)){r.select();this.ed.execCommand("delete");}
return;}else{var n=this.ed.documentNode().getElementById(rte.undo.undoNodeID);if(!n)
return;n.id=null;var opts=this.stack[level].opts;if(opts.parentNode)
n=n.firstChild;else if(opts.previousSibling)
n=n.nextSibling;var r=this.ed.newRangeContaining(n,opts.offset);this.ed.setSelection(r);return;if(this.ed.cw.mozFind(rte.undo.bookmark))
this.ed.cw.getSelection().getRangeAt(0).deleteContents();}},getCursorNode:function(level){var id="rte-undo-"+level;return $(this.ed.ce?this.ed.bodyNode().getElementById(id):this.ed.documentNode().getElementById(id));},editorContents:function(){return this.ed.bodyNode().innerHTML;},redo:function(){if(this.isDirty||this.stack.length<=this.current+1)
return false;this.current++;log("restoring level ",this.current);this.ed.bodyNode().innerHTML=this.stack[this.current].html;this.restoreSelection(this.current);this.isDirty=false;return true;}});