bhf 0.3.3 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -100,7 +100,7 @@ class Bhf::EntriesController < Bhf::ApplicationController
100
100
  params[:has_and_belongs_to_many].each_pair do |relation, ids|
101
101
  reflection = @model.reflections[relation.to_sym]
102
102
 
103
- @object.send(reflection.name).delete_all # TODO: not this
103
+ @object.send(reflection.name).delete_all # TODO: drop only the diff
104
104
 
105
105
  ids = ids.values.reject(&:blank?)
106
106
 
@@ -32,7 +32,7 @@ class Bhf::PagesController < Bhf::ApplicationController
32
32
  @platform.pagination = Bhf::Pagination.new(@platform.entries_per_page)
33
33
  paginate_platform_objects(@platform)
34
34
 
35
- render '_platform', :layout => false
35
+ render :layout => false, :partial => 'platform', :locals => {:platform => @platform}
36
36
  end
37
37
 
38
38
  def check_params(platform)
@@ -1,3 +1,15 @@
1
1
  -# TODO: markdown editor
2
+
2
3
  = node f, field do
3
- = f.text_area field.name, :class => 'markdown'
4
+ - if @quick_edit
5
+ = f.text_area field.name, :id => 'wmd-input', :class => 'markdown'
6
+ - else
7
+ = javascript_include_tag '/javascripts/bhf_includes/showdown.js'
8
+ #wmd-editor.wmd-pane
9
+ #wmd-button-bar
10
+ = f.text_area field.name, :id => 'wmd-input', :class => 'markdown'
11
+ %h6 Live Preview:
12
+ #wmd-preview.wmd-panel
13
+ %h6 HTML Preview:
14
+ #wmd-output.wmd-panel
15
+ = javascript_include_tag '/javascripts/bhf_includes/wmd.js'
@@ -1,3 +1,4 @@
1
+ -# TODO: reset seach on empty string
1
2
  = form_for platform.name, :html => {:method => 'get', :class => 'search'} do |f|
2
3
  - p = params[platform.name]
3
4
  = f.fields_for :search do |s|
@@ -7,8 +7,8 @@
7
7
  %link{:href => '/favicon.ico', :rel => 'icon', :type => 'image/x-icon'}
8
8
  - ([:bhf] + Bhf::Engine.config.css.to_a).each do |css|
9
9
  = stylesheet_link_tag "/stylesheets/#{css}"
10
- = javascript_include_tag "/javascripts/bhf"
11
- =# javascript_include_tag 'bhf/mootools-core-1.3.2-full-compat-yc.js', 'bhf/mootools-more-1.3.2.1.js', 'bhf/mootools_rails_driver-0.4.1.js', 'bhf/class/BrowserUpdate', 'bhf/class/Ajaxify', 'bhf/class/AjaxEdit', 'bhf/class/MooEditable', 'bhf/class/Datepicker', 'bhf/class/MultipleFields', 'bhf/bhf_application'
10
+ = javascript_include_tag '/javascripts/bhf'
11
+ =# javascript_include_tag '/javascripts/bhf/mootools-core-1.3.2-full-compat-yc.js', '/javascripts/bhf/mootools-more-1.3.2.1.js', '/javascripts/bhf/mootools_rails_driver-0.4.1.js', '/javascripts/bhf/class/BrowserUpdate', '/javascripts/bhf/class/Ajaxify', '/javascripts/bhf/class/AjaxEdit', '/javascripts/bhf/class/MooEditable', '/javascripts/bhf/class/Datepicker', '/javascripts/bhf/class/MultipleFields', '/javascripts/bhf/bhf_application'
12
12
  %body
13
13
  %header
14
14
  %h1= link_to image_tag('/images/logo_bhf.png'), root_url
Binary file
@@ -596,4 +596,4 @@ if(!r){r=[];}for(var h=0,g=m.length;h<g;h++){if(r.contains(m[h])){continue;}r.in
596
596
  return this;},get:function(i,h,g){if(h){i+="."+h;}return f.get(i,g);}});})();Locale.define("en-US","Date",{months:["January","February","March","April","May","June","July","August","September","October","November","December"],months_abbr:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],days_abbr:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dateOrder:["month","date","year"],shortDate:"%m/%d/%Y",shortTime:"%I:%M%p",AM:"AM",PM:"PM",firstDayOfWeek:0,ordinal:function(a){return(a>3&&a<21)?"th":["th","st","nd","rd","th"][Math.min(a%10,4)];
597
597
  },lessThanMinuteAgo:"less than a minute ago",minuteAgo:"about a minute ago",minutesAgo:"{delta} minutes ago",hourAgo:"about an hour ago",hoursAgo:"about {delta} hours ago",dayAgo:"1 day ago",daysAgo:"{delta} days ago",weekAgo:"1 week ago",weeksAgo:"{delta} weeks ago",monthAgo:"1 month ago",monthsAgo:"{delta} months ago",yearAgo:"1 year ago",yearsAgo:"{delta} years ago",lessThanMinuteUntil:"less than a minute from now",minuteUntil:"about a minute from now",minutesUntil:"{delta} minutes from now",hourUntil:"about an hour from now",hoursUntil:"about {delta} hours from now",dayUntil:"1 day from now",daysUntil:"{delta} days from now",weekUntil:"1 week from now",weeksUntil:"{delta} weeks from now",monthUntil:"1 month from now",monthsUntil:"{delta} months from now",yearUntil:"1 year from now",yearsUntil:"{delta} years from now"});
598
598
  Locale.define("de-DE","Date",{months:["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"],months_abbr:["Jan","Feb","Mär","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez"],days:["Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag"],days_abbr:["So.","Mo.","Di.","Mi.","Do.","Fr.","Sa."],dateOrder:["date","month","year"],shortDate:"%d.%m.%Y",shortTime:"%H:%M",AM:"vormittags",PM:"nachmittags",firstDayOfWeek:1,ordinal:".",lessThanMinuteAgo:"vor weniger als einer Minute",minuteAgo:"vor einer Minute",minutesAgo:"vor {delta} Minuten",hourAgo:"vor einer Stunde",hoursAgo:"vor {delta} Stunden",dayAgo:"vor einem Tag",daysAgo:"vor {delta} Tagen",weekAgo:"vor einer Woche",weeksAgo:"vor {delta} Wochen",monthAgo:"vor einem Monat",monthsAgo:"vor {delta} Monaten",yearAgo:"vor einem Jahr",yearsAgo:"vor {delta} Jahren",lessThanMinuteUntil:"in weniger als einer Minute",minuteUntil:"in einer Minute",minutesUntil:"in {delta} Minuten",hourUntil:"in ca. einer Stunde",hoursUntil:"in ca. {delta} Stunden",dayUntil:"in einem Tag",daysUntil:"in {delta} Tagen",weekUntil:"in einer Woche",weeksUntil:"in {delta} Wochen",monthUntil:"in einem Monat",monthsUntil:"in {delta} Monaten",yearUntil:"in einem Jahr",yearsUntil:"in {delta} Jahren"});
599
- (function($){window.rails={applyEvents:function(el){el=$(el||document.body);var apply=function(selector,action,callback){el.getElements(selector).addEvent(action,callback)};apply('form[data-remote="true"]',"submit",rails.handleRemote);apply('a[data-remote="true"], input[data-remote="true"]',"click",rails.handleRemote);apply("a[data-method][data-remote!=true]","click",function(e){e.preventDefault();if(rails.confirmed(this)){var form=new Element("form",{method:"post",action:this.get("href"),styles:{display:"none"}}).inject(this,"after");var methodInput=new Element("input",{type:"hidden",name:"_method",value:this.get("data-method")});var csrfInput=new Element("input",{type:"hidden",name:rails.csrf.param,value:rails.csrf.token});form.adopt(methodInput,csrfInput).submit()}});var noMethodNorRemoteConfirm=":not([data-method]):not([data-remote=true])[data-confirm]";apply("a"+noMethodNorRemoteConfirm+",input"+noMethodNorRemoteConfirm,"click",function(){return rails.confirmed(this)})},getCsrf:function(name){var meta=document.getElement("meta[name=csrf-"+name+"]");return(meta?meta.get("content"):null)},confirmed:function(el){var confirmMessage=el.get("data-confirm");if(confirmMessage&&!confirm(confirmMessage)){return false}return true},disable:function(el){var button=el.get("data-disable-with")?el:el.getElement("[data-disable-with]");if(button){var enableWith=button.get("value");el.addEvent("ajax:complete",function(){button.set({value:enableWith,disabled:false})});button.set({value:button.get("data-disable-with"),disabled:true})}},handleRemote:function(e){e.preventDefault();if(rails.confirmed(this)){this.request=new Request.Rails(this);rails.disable(this);this.request.send()}}};Request.Rails=new Class({Extends:Request,initialize:function(element,options){this.el=element;this.parent(Object.merge({},{method:this.el.get("method")||this.el.get("data-method")||"get",url:this.el.get("action")||this.el.get("href")},options));this.headers.Accept="*/*";this.addRailsEvents()},send:function(options){this.el.fireEvent("ajax:before");if(this.el.get("tag")=="form"){this.options.data=this.el}this.parent(options);this.el.fireEvent("ajax:after",this.xhr)},addRailsEvents:function(){this.addEvent("request",function(){this.el.fireEvent("ajax:loading",this.xhr)});this.addEvent("success",function(){this.el.fireEvent("ajax:success",this.xhr)});this.addEvent("complete",function(){this.el.fireEvent("ajax:complete",this.xhr);this.el.fireEvent("ajax:loaded",this.xhr)});this.addEvent("failure",function(){this.el.fireEvent("ajax:failure",this.xhr)})}})})(document.id);window.addEvent("domready",function(){rails.csrf={token:rails.getCsrf("token"),param:rails.getCsrf("param")};rails.applyEvents()});var BrowserUpdate=new Class({initialize:function(op,test){var b,jsv=5,n=window.navigator;this.op=op||{};this.op.l=op.l||n.language||n.userLanguage||document.documentElement.getAttribute("lang")||"en";this.op.vsakt={i:8,f:3.6,o:10.6,s:5,n:10};this.op.vsdefault={i:6,f:2,o:9.64,s:3,n:10};this.op.vs=op.vs||this.op.vsdefault;for(b in this.op.vsakt){if(this.op.vs[b]>=this.op.vsakt[b]){this.op.vs[b]=this.op.vsdefault[b]}}if(!op.reminder||op.reminder<0.1){this.op.reminder=0}else{this.op.reminder=op.reminder||24}this.op.onshow=op.onshow||function(o){};this.op.url=op.url||"http://browser-update.org/update.html";this.op.pageurl=op.pageurl||window.location.hostname||"unknown";this.op.newwindow=op.newwindow||false;this.op.test=test||op.test||false;if(window.location.hash=="#test-bu"){this.op.test=true}function getBrowser(){var n,v,t,ua=navigator.userAgent,names={i:"Internet Explorer",f:"Firefox",o:"Opera",s:"Apple Safari",n:"Netscape Navigator",c:"Chrome",x:"Other"};if(/like firefox|chromeframe|seamonkey|opera mini|meego|netfront|moblin|maemo|arora|camino|flot|k-meleon|fennec|kazehakase|galeon|android|mobile|iphone|ipod|ipad|symbian|webos/i.test(ua)){n="x"}else{if(/MSIE (\d+\.\d+);/.test(ua)){n="i"}else{if(/Chrome.(\d+\.\d+)/i.test(ua)){n="c"}else{if(/Firefox.(\d+\.\d+)/i.test(ua)){n="f"}else{if(/Version.(\d+.\d+).{0,10}Safari/i.test(ua)){n="s"}else{if(/Safari.(\d+)/i.test(ua)){n="so"}else{if(/Opera.*Version.(\d+\.\d+)/i.test(ua)){n="o"}else{if(/Opera.(\d+\.\d+)/i.test(ua)){n="o"}else{if(/Netscape.(\d+)/i.test(ua)){n="n"}else{return{n:"x",v:0,t:names[n]}}}}}}}}}}if(n=="x"){return{n:"x",v:0,t:names[n]}}v=new Number(RegExp.$1);if(n=="so"){v=((v<100)&&1)||((v<130)&&1.2)||((v<320)&&1.3)||((v<520)&&2)||((v<524)&&3)||((v<526)&&3.2)||4;n="s"}if(n=="i"&&v==7&&window.XDomainRequest){v=8}return{n:n,v:v,t:names[n]+" "+v}}this.op.browser=getBrowser();if(!this.op.test&&(!this.op.browser||!this.op.browser.n||this.op.browser.n=="x"||this.op.browser.n=="c"||document.cookie.indexOf("browserupdateorg=pause")>-1||this.op.browser.v>this.op.vs[this.op.browser.n])){return}if(this.op.reminder>0){var d=new Date(new Date().getTime()+1000*3600*this.op.reminder);document.cookie="browserupdateorg=pause; expires="+d.toGMTString()+"; path=/"}var ll=this.op.l.substr(0,2);var languages="de,en";if(languages.indexOf(ll)!==false){this.op.url="http://browser-update.org/"+ll+"/update.html#"+jsv}var tar="";if(this.op.newwindow){tar=' target="_blank"'}function busprintf(){var args=arguments;var data=args[0];for(var k=1;k<args.length;++k){data=data.replace(/%s/,args[k])}return data}ll=(window.Locale)?Locale.getCurrent().name:"en-US";var t="Your browser (%s) is <b>out of date</b>. It has known <b>security flaws</b> and may <b>not display all features</b> of this and other websites. <a%s>Learn how to update your browser</a>";if(ll=="de-DE"){t="Sie verwenden einen <b>veralteten Browser</b> (%s) mit <b>Sicherheitsschwachstellen</b> und <b>k&ouml;nnen nicht alle Funktionen dieser Webseite nutzen</b>. <a%s>Hier erfahren Sie, wie einfach Sie Ihren Browser aktualisieren k&ouml;nnen</a>."}if(op.text){t=op.text}this.op.text=busprintf(t,this.op.browser.t,' href="'+this.op.url+'"'+tar);var div=document.createElement("div");this.op.div=div;div.id="buorg";div.className="buorg";div.innerHTML="<div>"+this.op.text+'<div id="buorgclose">X</div></div>';var sheet=document.createElement("style");var style=".buorg {position:absolute;z-index:111111; width:100%; top:0px; left:0px; border-bottom:1px solid #A29330; background:#FDF2AB no-repeat 10px center url(http://browser-update.org/img/dialog-warning.gif); text-align:left; cursor:pointer; font-family: Arial,Helvetica,sans-serif; color:#000; font-size: 12px;} .buorg div { padding:5px 36px 5px 40px; } .buorg a,.buorg a:visited {color:#E25600; text-decoration: underline;} #buorgclose { position: absolute; right: .5em; top:.2em; height: 20px; width: 12px; font-weight: bold;font-size:14px; padding:0; }";document.body.insertBefore(div,document.body.firstChild);document.getElementsByTagName("head")[0].appendChild(sheet);try{sheet.innerText=style;sheet.innerHTML=style}catch(e){try{sheet.styleSheet.cssText=style}catch(e){return}}var me=this;div.onclick=function(){if(me.op.newwindow){window.open(me.op.url,"_blank")}else{window.location.href=me.op.url}return false};div.getElementsByTagName("a")[0].onclick=function(e){var e=e||window.event;if(e.stopPropagation){e.stopPropagation()}else{e.cancelBubble=true}return true};this.op.bodymt=document.body.style.paddingTop;document.body.style.paddingTop=(div.clientHeight)+"px";document.getElementById("buorgclose").onclick=function(e){var e=e||window.event;if(e.stopPropagation){e.stopPropagation()}else{e.cancelBubble=true}me.op.div.style.display="none";document.body.style.paddingTop=me.op.bodymt;return true};op.onshow(this.op)}});var Ajaxify=new Class({version:0.2,Implements:[Options,Events],options:{events:{loading:{name:"ajax:loading",text:"Loading…"},success:{name:"ajax:success",text:"Changes successfully saved!"},failure:{name:"ajax:failure",text:"Oops, something went wrong…"}},holder:new Element("div#ajax_holder"),fadeOutDuration:2000},initialize:function(_options){this.setOptions(_options);this.holder=this.options.holder.inject(document.body)},applyEvents:function(el){el=document.id(el||document.body);var apply=function(action,callback){el.getElements('[data-remote="true"]').addEvent(action,callback)};apply(this.options.events.loading.name,this.loading.bind(this));apply(this.options.events.success.name,this.success.bind(this));apply(this.options.events.failure.name,this.failure.bind(this))},loading:function(xhr){this.setMessage("loading",false)},success:function(xhr){this.setMessage("success",true)},failure:function(xhr){this.setMessage("failure",true)},setMessage:function(status,fadeOut){this.holder.set("text",this.options.events[status].text).set("class",status);if(fadeOut){this.holder.addClass("fadeout");setTimeout(function(){this.holder.erase("class")}.bind(this),this.options.fadeOutDuration)}}});var AjaxEdit=new Class({version:0.2,options:{holderParent:document.body},Implements:[Options,Events],holder:new Element("div.quick_edit_holder"),initialize:function(_options){this.setOptions(_options);this.holder.addEvents({"click:relay(.open)":function(e){e.preventDefault();location.href=this.wrapElement.getElement("a").get("href")}.bind(this),"click:relay(.cancel)":function(e){e.preventDefault();this.close()}.bind(this),"click:relay(.save_and_next)":function(e){e.preventDefault();this.submit(["successAndChange","successAndNext"])}.bind(this),"click:relay(.save)":function(e){e.preventDefault();this.submit(["successAndChange"])}.bind(this),"submit:relay(form)":function(e){e.preventDefault();this.submit(["successAndChange"])}.bind(this)})},startEdit:function(element,wrapElement){this.clean();this.wrapElement=wrapElement?wrapElement:element;this.wrapElement.addClass("live_edit");this.fireEvent("startRequest");new Request.HTML({method:"get",evalScripts:false,url:element.get("href"),onSuccess:function(responseTree,responseElements,responseHTML,responseJavaScript){this.injectForm(responseHTML);eval(responseJavaScript)}.bind(this)}).send()},submit:function(eventNames){var form=this.holder.getElement("form");this.fireEvent("beforeSubmit");new Request.JSON({method:form.get("method"),url:form.get("action"),evalScripts:true,onRequest:function(){this.disableButtons()}.bind(this),onFailure:function(invalidForm){this.injectForm(invalidForm.response);invalidForm.response.stripScripts(function(script){eval(script)})}.bind(this),onSuccess:function(json){if(!eventNames.contains("successAndNext")){this.close()}eventNames.each(function(eventName){this.fireEvent(eventName,[json])}.bind(this));this.fireEvent("save")}.bind(this)}).send({data:form})},disableButtons:function(){this.holder.getElements(".open, .cancel, .save_and_next, .save").set("disabled","disabled")},clean:function(){document.body.getElements(".live_edit").removeClass("live_edit")},close:function(){this.clean();this.holder.dispose()},injectForm:function(form){this.holder.innerHTML=form;this.holder.inject(this.options.holderParent);this.fireEvent("formInjected",[this.holder])}});(function(){var blockEls=/^(H[1-6]|HR|P|DIV|ADDRESS|PRE|FORM|TABLE|LI|OL|UL|TD|CAPTION|BLOCKQUOTE|CENTER|DL|DT|DD|SCRIPT|NOSCRIPT|STYLE)$/i;var urlRegex=/^(https?|ftp|rmtp|mms):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i;var protectRegex=/<(script|noscript|style)[\u0000-\uFFFF]*?<\/(script|noscript|style)>/g;this.MooEditable=new Class({Implements:[Events,Options],options:{toolbar:true,cleanup:true,paragraphise:true,xhtml:true,semantics:true,actions:"bold italic underline strikethrough | insertunorderedlist insertorderedlist indent outdent | undo redo | createlink unlink | urlimage | toggleview",handleSubmit:true,handleLabel:true,disabled:false,baseCSS:"html{ height: 100%; cursor: text; } body{ font-family: sans-serif; }",extraCSS:"",externalCSS:"",html:'<!DOCTYPE html><html><head><meta charset="UTF-8">{BASEHREF}<style>{BASECSS} {EXTRACSS}</style>{EXTERNALCSS}</head><body></body></html>',rootElement:"p",baseURL:"",dimensions:null},initialize:function(el,options){this.setOptions(options);this.textarea=document.id(el);this.textarea.store("MooEditable",this);this.actions=this.options.actions.clean().split(" ");this.keys={};this.dialogs={};this.protectedElements=[];this.actions.each(function(action){var act=MooEditable.Actions[action];if(!act){return}if(act.options){var key=act.options.shortcut;if(key){this.keys[key]=action}}if(act.dialogs){Object.each(act.dialogs,function(dialog,name){dialog=dialog.attempt(this);dialog.name=action+":"+name;if(typeOf(this.dialogs[action])!="object"){this.dialogs[action]={}}this.dialogs[action][name]=dialog},this)}if(act.events){Object.each(act.events,function(fn,event){this.addEvent(event,fn)},this)}}.bind(this));this.render()},toElement:function(){return this.textarea},render:function(){var self=this;var dimensions=this.options.dimensions||this.textarea.getSize();this.container=new Element("div",{id:(this.textarea.id)?this.textarea.id+"-mooeditable-container":null,"class":"mooeditable-container",styles:{width:dimensions.x}});this.textarea.addClass("mooeditable-textarea").setStyle("height",dimensions.y);this.iframe=new IFrame({"class":"mooeditable-iframe",frameBorder:0,src:'javascript:""',styles:{height:dimensions.y}});this.toolbar=new MooEditable.UI.Toolbar({onItemAction:function(){var args=Array.from(arguments);var item=args[0];self.action(item.name,args)}});this.attach.delay(1,this);if(this.options.handleLabel&&this.textarea.id){$$('label[for="'+this.textarea.id+'"]').addEvent("click",function(e){if(self.mode!="iframe"){return}e.preventDefault();self.focus()})}if(this.options.handleSubmit){this.form=this.textarea.getParent("form");if(!this.form){return}this.form.addEvent("submit",function(){if(self.mode=="iframe"){self.saveContent()}})}this.fireEvent("render",this)},attach:function(){var self=this;this.mode="iframe";this.editorDisabled=false;this.container.wraps(this.textarea);this.textarea.setStyle("display","none");this.iframe.setStyle("display","").inject(this.textarea,"before");Object.each(this.dialogs,function(action,name){Object.each(action,function(dialog){document.id(dialog).inject(self.iframe,"before");var range;dialog.addEvents({open:function(){range=self.selection.getRange();self.editorDisabled=true;self.toolbar.disable(name);self.fireEvent("dialogOpen",this)},close:function(){self.toolbar.enable();self.editorDisabled=false;self.focus();if(range){self.selection.setRange(range)}self.fireEvent("dialogClose",this)}})})});this.win=this.iframe.contentWindow;this.doc=this.win.document;if(Browser.firefox){this.doc.designMode="On"}var docHTML=this.options.html.substitute({BASECSS:this.options.baseCSS,EXTRACSS:this.options.extraCSS,EXTERNALCSS:(this.options.externalCSS)?'<link rel="stylesheet" href="'+this.options.externalCSS+'">':"",BASEHREF:(this.options.baseURL)?'<base href="'+this.options.baseURL+'" />':""});this.doc.open();this.doc.write(docHTML);this.doc.close();(Browser.ie)?this.doc.body.contentEditable=true:this.doc.designMode="On";Object.append(this.win,new Window);Object.append(this.doc,new Document);if(Browser.Element){var winElement=this.win.Element.prototype;for(var method in Element){if(!method.test(/^[A-Z]|\$|prototype|mooEditable/)){winElement[method]=Element.prototype[method]}}}else{document.id(this.doc.body)}this.setContent(this.textarea.get("value"));this.doc.addEvents({mouseup:this.editorMouseUp.bind(this),mousedown:this.editorMouseDown.bind(this),mouseover:this.editorMouseOver.bind(this),mouseout:this.editorMouseOut.bind(this),mouseenter:this.editorMouseEnter.bind(this),mouseleave:this.editorMouseLeave.bind(this),contextmenu:this.editorContextMenu.bind(this),click:this.editorClick.bind(this),dblclick:this.editorDoubleClick.bind(this),keypress:this.editorKeyPress.bind(this),keyup:this.editorKeyUp.bind(this),keydown:this.editorKeyDown.bind(this),focus:this.editorFocus.bind(this),blur:this.editorBlur.bind(this)});this.win.addEvents({focus:this.editorFocus.bind(this),blur:this.editorBlur.bind(this)});["cut","copy","paste"].each(function(event){self.doc.body.addListener(event,self["editor"+event.capitalize()].bind(self))});this.textarea.addEvent("keypress",this.textarea.retrieve("mooeditable:textareaKeyListener",this.keyListener.bind(this)));if(Browser.firefox2){this.doc.addEvent("focus",function(){self.win.fireEvent("focus").focus()})}if(this.doc.addEventListener){this.doc.addEventListener("focus",function(){self.win.fireEvent("focus")},true)}if(!Browser.ie&&!Browser.opera){var styleCSS=function(){self.execute("styleWithCSS",false,false);self.doc.removeEvent("focus",styleCSS)};this.win.addEvent("focus",styleCSS)}if(this.options.toolbar){document.id(this.toolbar).inject(this.container,"top");this.toolbar.render(this.actions)}if(this.options.disabled){this.disable()}this.selection=new MooEditable.Selection(this.win);this.oldContent=this.getContent();this.fireEvent("attach",this);return this},detach:function(){this.saveContent();this.textarea.setStyle("display","").removeClass("mooeditable-textarea").inject(this.container,"before");this.textarea.removeEvent("keypress",this.textarea.retrieve("mooeditable:textareaKeyListener"));this.container.dispose();this.fireEvent("detach",this);return this},enable:function(){this.editorDisabled=false;this.toolbar.enable();return this},disable:function(){this.editorDisabled=true;this.toolbar.disable();return this},editorFocus:function(e){this.oldContent="";this.fireEvent("editorFocus",[e,this])},editorBlur:function(e){this.oldContent=this.saveContent().getContent();this.fireEvent("editorBlur",[e,this])},editorMouseUp:function(e){if(this.editorDisabled){e.stop();return}if(this.options.toolbar){this.checkStates()}this.fireEvent("editorMouseUp",[e,this])},editorMouseDown:function(e){if(this.editorDisabled){e.stop();return}this.fireEvent("editorMouseDown",[e,this])},editorMouseOver:function(e){if(this.editorDisabled){e.stop();return}this.fireEvent("editorMouseOver",[e,this])},editorMouseOut:function(e){if(this.editorDisabled){e.stop();return}this.fireEvent("editorMouseOut",[e,this])},editorMouseEnter:function(e){if(this.editorDisabled){e.stop();return}if(this.oldContent&&this.getContent()!=this.oldContent){this.focus();this.fireEvent("editorPaste",[e,this])}this.fireEvent("editorMouseEnter",[e,this])},editorMouseLeave:function(e){if(this.editorDisabled){e.stop();return}this.fireEvent("editorMouseLeave",[e,this])},editorContextMenu:function(e){if(this.editorDisabled){e.stop();return}this.fireEvent("editorContextMenu",[e,this])},editorClick:function(e){if(Browser.safari||Browser.chrome){var el=e.target;if(Element.get(el,"tag")=="img"){if(this.options.baseURL){if(el.getProperty("src").indexOf("http://")==-1){el.setProperty("src",this.options.baseURL+el.getProperty("src"))}}this.selection.selectNode(el);this.checkStates()}}this.fireEvent("editorClick",[e,this])},editorDoubleClick:function(e){this.fireEvent("editorDoubleClick",[e,this])},editorKeyPress:function(e){if(this.editorDisabled){e.stop();return}this.keyListener(e);this.fireEvent("editorKeyPress",[e,this])},editorKeyUp:function(e){if(this.editorDisabled){e.stop();return}var c=e.code;if(this.options.toolbar&&(/^enter|left|up|right|down|delete|backspace$/i.test(e.key)||(c>=33&&c<=36)||c==45||e.meta||e.control)){if(Browser.ie6){clearTimeout(this.checkStatesDelay);this.checkStatesDelay=this.checkStates.delay(500,this)}else{this.checkStates()}}this.fireEvent("editorKeyUp",[e,this])},editorKeyDown:function(e){if(this.editorDisabled){e.stop();return}if(e.key=="enter"){if(this.options.paragraphise){if(e.shift&&(Browser.safari||Browser.chrome)){var s=this.selection;var r=s.getRange();var br=this.doc.createElement("br");r.insertNode(br);r.setStartAfter(br);r.setEndAfter(br);s.setRange(r);if(s.getSelection().focusNode==br.previousSibling){var nbsp=this.doc.createTextNode("\u00a0");var p=br.parentNode;var ns=br.nextSibling;(ns)?p.insertBefore(nbsp,ns):p.appendChild(nbsp);s.selectNode(nbsp);s.collapse(1)}this.win.scrollTo(0,Element.getOffsets(s.getRange().startContainer).y);e.preventDefault()}else{if(Browser.firefox||Browser.safari||Browser.chrome){var node=this.selection.getNode();var isBlock=Element.getParents(node).include(node).some(function(el){return el.nodeName.test(blockEls)});if(!isBlock){this.execute("insertparagraph")}}}}else{if(Browser.ie){var r=this.selection.getRange();var node=this.selection.getNode();if(r&&node.get("tag")!="li"){this.selection.insertContent("<br>");this.selection.collapse(false)}e.preventDefault()}}}if(Browser.opera){var ctrlmeta=e.control||e.meta;if(ctrlmeta&&e.key=="x"){this.fireEvent("editorCut",[e,this])}else{if(ctrlmeta&&e.key=="c"){this.fireEvent("editorCopy",[e,this])}else{if((ctrlmeta&&e.key=="v")||(e.shift&&e.code==45)){this.fireEvent("editorPaste",[e,this])}}}}this.fireEvent("editorKeyDown",[e,this])},editorCut:function(e){if(this.editorDisabled){e.stop();return}this.fireEvent("editorCut",[e,this])},editorCopy:function(e){if(this.editorDisabled){e.stop();return}this.fireEvent("editorCopy",[e,this])},editorPaste:function(e){if(this.editorDisabled){e.stop();return}this.fireEvent("editorPaste",[e,this])},keyListener:function(e){var key=(Browser.Platform.mac)?e.meta:e.control;if(!key||!this.keys[e.key]){return}e.preventDefault();var item=this.toolbar.getItem(this.keys[e.key]);item.action(e)},focus:function(){(this.mode=="iframe"?this.win:this.textarea).focus();this.fireEvent("focus",this);return this},action:function(command,args){var action=MooEditable.Actions[command];if(action.command&&typeOf(action.command)=="function"){action.command.apply(this,args)}else{this.focus();this.execute(command,false,args);if(this.mode=="iframe"){this.checkStates()}}},execute:function(command,param1,param2){if(this.busy){return}this.busy=true;this.doc.execCommand(command,param1,param2);this.saveContent();this.busy=false;return false},toggleView:function(){this.fireEvent("beforeToggleView",this);if(this.mode=="textarea"){this.mode="iframe";this.iframe.setStyle("display","");this.setContent(this.textarea.value);this.textarea.setStyle("display","none")}else{this.saveContent();this.mode="textarea";this.textarea.setStyle("display","");this.iframe.setStyle("display","none")}this.fireEvent("toggleView",this);this.focus.delay(10,this);return this},getContent:function(){var protect=this.protectedElements;var html=this.doc.body.get("html").replace(/<!-- mooeditable:protect:([0-9]+) -->/g,function(a,b){return protect[b.toInt()]});return this.cleanup(this.ensureRootElement(html))},setContent:function(content){var protect=this.protectedElements;content=content.replace(protectRegex,function(a){protect.push(a);return"<!-- mooeditable:protect:"+(protect.length-1)+" -->"});this.doc.body.set("html",this.ensureRootElement(content));return this},saveContent:function(){if(this.mode=="iframe"){this.textarea.set("value",this.getContent())}return this},ensureRootElement:function(val){if(this.options.rootElement){var el=new Element("div",{html:val.trim()});var start=-1;var create=false;var html="";var length=el.childNodes.length;for(var i=0;i<length;i++){var childNode=el.childNodes[i];var nodeName=childNode.nodeName;if(!nodeName.test(blockEls)&&nodeName!=="#comment"){if(nodeName==="#text"){if(childNode.nodeValue.trim()){if(start<0){start=i}html+=childNode.nodeValue}}else{if(start<0){start=i}html+=new Element("div").adopt($(childNode).clone()).get("html")}}else{create=true}if(i==(length-1)){create=true}if(start>=0&&create){var newel=new Element(this.options.rootElement,{html:html});el.replaceChild(newel,el.childNodes[start]);for(var k=start+1;k<i;k++){el.removeChild(el.childNodes[k]);length--;i--;k--}start=-1;create=false;html=""}}val=el.get("html").replace(/\n\n/g,"")}return val},checkStates:function(){var element=this.selection.getNode();if(!element){return}if(typeOf(element)!="element"){return}this.actions.each(function(action){var item=this.toolbar.getItem(action);if(!item){return}item.deactivate();var states=MooEditable.Actions[action]["states"];if(!states){return}if(typeOf(states)=="function"){states.attempt([document.id(element),item],this);return}try{if(this.doc.queryCommandState(action)){item.activate();return}}catch(e){}if(states.tags){var el=element;do{var tag=el.tagName.toLowerCase();if(states.tags.contains(tag)){item.activate(tag);break}}while((el=Element.getParent(el))!=null)}if(states.css){var el=element;do{var found=false;for(var prop in states.css){var css=states.css[prop];if(el.style[prop.camelCase()].contains(css)){item.activate(css);found=true}}if(found||el.tagName.test(blockEls)){break}}while((el=Element.getParent(el))!=null)}}.bind(this))},cleanup:function(source){if(!this.options.cleanup){return source.trim()}do{var oSource=source;if(this.options.baseURL){source=source.replace('="'+this.options.baseURL,'="')}source=source.replace(/<br class\="webkit-block-placeholder">/gi,"<br />");source=source.replace(/<span class="Apple-style-span">(.*)<\/span>/gi,"$1");source=source.replace(/ class="Apple-style-span"/gi,"");source=source.replace(/<span style="">/gi,"");source=source.replace(/<p>\s*<br ?\/?>\s*<\/p>/gi,"<p>\u00a0</p>");source=source.replace(/<p>(&nbsp;|\s)*<\/p>/gi,"<p>\u00a0</p>");if(!this.options.semantics){source=source.replace(/\s*<br ?\/?>\s*<\/p>/gi,"</p>")}if(this.options.xhtml){source=source.replace(/<br>/gi,"<br />")}if(this.options.semantics){if(Browser.ie){source=source.replace(/<li>\s*<div>(.+?)<\/div><\/li>/g,"<li>$1</li>")}if(Browser.safari||Browser.chrome){source=source.replace(/^([\w\s]+.*?)<div>/i,"<p>$1</p><div>");source=source.replace(/<div>(.+?)<\/div>/ig,"<p>$1</p>")}if(!Browser.ie){source=source.replace(/<p>[\s\n]*(<(?:ul|ol)>.*?<\/(?:ul|ol)>)(.*?)<\/p>/ig,"$1<p>$2</p>");source=source.replace(/<\/(ol|ul)>\s*(?!<(?:p|ol|ul|img).*?>)((?:<[^>]*>)?\w.*)$/g,"</$1><p>$2</p>")}source=source.replace(/<br[^>]*><\/p>/g,"</p>");source=source.replace(/<p>\s*(<img[^>]+>)\s*<\/p>/ig,"$1\n");source=source.replace(/<p([^>]*)>(.*?)<\/p>(?!\n)/g,"<p$1>$2</p>\n");source=source.replace(/<\/(ul|ol|p)>(?!\n)/g,"</$1>\n");source=source.replace(/><li>/g,">\n\t<li>");source=source.replace(/([^\n])<\/(ol|ul)>/g,"$1\n</$2>");source=source.replace(/([^\n])<img/ig,"$1\n<img");source=source.replace(/^\s*$/g,"")}source=source.replace(/<br ?\/?>$/gi,"");source=source.replace(/^<br ?\/?>/gi,"");if(this.options.paragraphise){source=source.replace(/(h[1-6]|p|div|address|pre|li|ol|ul|blockquote|center|dl|dt|dd)><br ?\/?>/gi,"$1>")}source=source.replace(/<br ?\/?>\s*<\/(h1|h2|h3|h4|h5|h6|li|p)/gi,"</$1");source=source.replace(/<span style="font-weight: bold;">(.*)<\/span>/gi,"<strong>$1</strong>");source=source.replace(/<span style="font-style: italic;">(.*)<\/span>/gi,"<em>$1</em>");source=source.replace(/<b\b[^>]*>(.*?)<\/b[^>]*>/gi,"<strong>$1</strong>");source=source.replace(/<i\b[^>]*>(.*?)<\/i[^>]*>/gi,"<em>$1</em>");source=source.replace(/<u\b[^>]*>(.*?)<\/u[^>]*>/gi,'<span style="text-decoration: underline;">$1</span>');source=source.replace(/<strong><span style="font-weight: normal;">(.*)<\/span><\/strong>/gi,"$1");source=source.replace(/<em><span style="font-weight: normal;">(.*)<\/span><\/em>/gi,"$1");source=source.replace(/<span style="text-decoration: underline;"><span style="font-weight: normal;">(.*)<\/span><\/span>/gi,"$1");source=source.replace(/<strong style="font-weight: normal;">(.*)<\/strong>/gi,"$1");source=source.replace(/<em style="font-weight: normal;">(.*)<\/em>/gi,"$1");source=source.replace(/<[^> ]*/g,function(match){return match.toLowerCase()});source=source.replace(/<[^>]*>/g,function(match){match=match.replace(/ [^=]+=/g,function(match2){return match2.toLowerCase()});return match});source=source.replace(/<[^!][^>]*>/g,function(match){match=match.replace(/( [^=]+=)([^"][^ >]*)/g,'$1"$2"');return match});if(this.options.xhtml){source=source.replace(/<img([^>]+)(\s*[^\/])>(<\/img>)*/gi,"<img$1$2 />")}source=source.replace(/<p>(?:\s*)<p>/g,"<p>");source=source.replace(/<\/p>\s*<\/p>/g,"</p>");source=source.replace(/<pre[^>]*>.*?<\/pre>/gi,function(match){return match.replace(/<br ?\/?>/gi,"\n")});source=source.trim()}while(source!=oSource);return source}});MooEditable.Selection=new Class({initialize:function(win){this.win=win},getSelection:function(){this.win.focus();return(this.win.getSelection)?this.win.getSelection():this.win.document.selection},getRange:function(){var s=this.getSelection();if(!s){return null}try{return s.rangeCount>0?s.getRangeAt(0):(s.createRange?s.createRange():null)}catch(e){return this.doc.body.createTextRange()}},setRange:function(range){if(range.select){Function.attempt(function(){range.select()})}else{var s=this.getSelection();if(s.addRange){s.removeAllRanges();s.addRange(range)}}},selectNode:function(node,collapse){var r=this.getRange();var s=this.getSelection();if(r.moveToElementText){Function.attempt(function(){r.moveToElementText(node);r.select()})}else{if(s.addRange){collapse?r.selectNodeContents(node):r.selectNode(node);s.removeAllRanges();s.addRange(r)}else{s.setBaseAndExtent(node,0,node,1)}}return node},isCollapsed:function(){var r=this.getRange();if(r.item){return false}return r.boundingWidth==0||this.getSelection().isCollapsed},collapse:function(toStart){var r=this.getRange();var s=this.getSelection();if(r.select){r.collapse(toStart);r.select()}else{toStart?s.collapseToStart():s.collapseToEnd()}},getContent:function(){var r=this.getRange();var body=new Element("body");if(this.isCollapsed()){return""}if(r.cloneContents){body.appendChild(r.cloneContents())}else{if(r.item!=undefined||r.htmlText!=undefined){body.set("html",r.item?r.item(0).outerHTML:r.htmlText)}else{body.set("html",r.toString())}}var content=body.get("html");return content},getText:function(){var r=this.getRange();var s=this.getSelection();return this.isCollapsed()?"":r.text||(s.toString?s.toString():"")},getNode:function(){var r=this.getRange();if(!Browser.ie||Browser.version>=9){var el=null;if(r){el=r.commonAncestorContainer;if(!r.collapsed){if(r.startContainer==r.endContainer){if(r.startOffset-r.endOffset<2){if(r.startContainer.hasChildNodes()){el=r.startContainer.childNodes[r.startOffset]}}}}while(typeOf(el)!="element"){el=el.parentNode}}return document.id(el)}return document.id(r.item?r.item(0):r.parentElement())},insertContent:function(content){if(Browser.ie){var r=this.getRange();if(r.pasteHTML){r.pasteHTML(content);r.collapse(false);r.select()}else{if(r.insertNode){r.deleteContents();if(r.createContextualFragment){r.insertNode(r.createContextualFragment(content))}else{var doc=this.win.document;var fragment=doc.createDocumentFragment();var temp=doc.createElement("div");fragment.appendChild(temp);temp.outerHTML=content;r.insertNode(fragment)}}}}else{this.win.document.execCommand("insertHTML",false,content)}}});var phrases={};MooEditable.Locale={define:function(key,value){if(typeOf(window.Locale)!="null"){return Locale.define("en-US","MooEditable",key,value)}if(typeOf(key)=="object"){Object.merge(phrases,key)}else{phrases[key]=value}},get:function(key){if(typeOf(window.Locale)!="null"){return Locale.get("MooEditable."+key)}return key?phrases[key]:""}};MooEditable.Locale.define({ok:"OK",cancel:"Cancel",bold:"Bold",italic:"Italic",underline:"Underline",strikethrough:"Strikethrough",unorderedList:"Unordered List",orderedList:"Ordered List",indent:"Indent",outdent:"Outdent",undo:"Undo",redo:"Redo",removeHyperlink:"Remove Hyperlink",addHyperlink:"Add Hyperlink",selectTextHyperlink:"Please select the text you wish to hyperlink.",enterURL:"Enter URL",enterImageURL:"Enter image URL",addImage:"Add Image",toggleView:"Toggle View"});MooEditable.UI={};MooEditable.UI.Toolbar=new Class({Implements:[Events,Options],options:{"class":""},initialize:function(options){this.setOptions(options);this.el=new Element("div",{"class":"mooeditable-ui-toolbar "+this.options["class"]});this.items={};this.content=null},toElement:function(){return this.el},render:function(actions){if(this.content){this.el.adopt(this.content)}else{this.content=actions.map(function(action){return(action=="|")?this.addSeparator():this.addItem(action)}.bind(this))}return this},addItem:function(action){var self=this;var act=MooEditable.Actions[action];if(!act){return}var type=act.type||"button";var options=act.options||{};var item=new MooEditable.UI[type.camelCase().capitalize()](Object.append(options,{name:action,"class":action+"-item toolbar-item",title:act.title,onAction:self.itemAction.bind(self)}));this.items[action]=item;document.id(item).inject(this.el);return item},getItem:function(action){return this.items[action]},addSeparator:function(){return new Element("span",{"class":"toolbar-separator"}).inject(this.el)},itemAction:function(){this.fireEvent("itemAction",arguments)},disable:function(except){Object.each(this.items,function(item){(item.name==except)?item.activate():item.deactivate().disable()});return this},enable:function(){Object.each(this.items,function(item){item.enable()});return this},show:function(){this.el.setStyle("display","");return this},hide:function(){this.el.setStyle("display","none");return this}});MooEditable.UI.Button=new Class({Implements:[Events,Options],options:{title:"",name:"",text:"Button","class":"",shortcut:"",mode:"icon"},initialize:function(options){this.setOptions(options);this.name=this.options.name;this.render()},toElement:function(){return this.el},render:function(){var self=this;var key=(Browser.Platform.mac)?"Cmd":"Ctrl";var shortcut=(this.options.shortcut)?" ( "+key+"+"+this.options.shortcut.toUpperCase()+" )":"";var text=this.options.title||name;var title=text+shortcut;this.el=new Element("button",{"class":"mooeditable-ui-button "+self.options["class"],title:title,html:'<span class="button-icon"></span><span class="button-text">'+text+"</span>",events:{click:self.click.bind(self),mousedown:function(e){e.preventDefault()}}});if(this.options.mode!="icon"){this.el.addClass("mooeditable-ui-button-"+this.options.mode)}this.active=false;this.disabled=false;if(Browser.ie){this.el.addEvents({mouseenter:function(e){this.addClass("hover")},mouseleave:function(e){this.removeClass("hover")}})}return this},click:function(e){e.preventDefault();if(this.disabled){return}this.action(e)},action:function(){this.fireEvent("action",[this].concat(Array.from(arguments)))},enable:function(){if(this.active){this.el.removeClass("onActive")}if(!this.disabled){return}this.disabled=false;this.el.removeClass("disabled").set({disabled:false,opacity:1});return this},disable:function(){if(this.disabled){return}this.disabled=true;this.el.addClass("disabled").set({disabled:true,opacity:0.4});return this},activate:function(){if(this.disabled){return}this.active=true;this.el.addClass("onActive");return this},deactivate:function(){this.active=false;this.el.removeClass("onActive");return this}});MooEditable.UI.Dialog=new Class({Implements:[Events,Options],options:{"class":"",contentClass:""},initialize:function(html,options){this.setOptions(options);this.html=html;var self=this;this.el=new Element("div",{"class":"mooeditable-ui-dialog "+self.options["class"],html:'<div class="dialog-content '+self.options.contentClass+'">'+html+"</div>",styles:{display:"none"},events:{click:self.click.bind(self)}})},toElement:function(){return this.el},click:function(){this.fireEvent("click",arguments);return this},open:function(){this.el.setStyle("display","");this.fireEvent("open",this);return this},close:function(){this.el.setStyle("display","none");this.fireEvent("close",this);return this}});MooEditable.UI.AlertDialog=function(alertText){if(!alertText){return}var html=alertText+' <button class="dialog-ok-button">'+MooEditable.Locale.get("ok")+"</button>";return new MooEditable.UI.Dialog(html,{"class":"mooeditable-alert-dialog",onOpen:function(){var button=this.el.getElement(".dialog-ok-button");(function(){button.focus()}).delay(10)},onClick:function(e){e.preventDefault();if(e.target.tagName.toLowerCase()!="button"){return}if(document.id(e.target).hasClass("dialog-ok-button")){this.close()}}})};MooEditable.UI.PromptDialog=function(questionText,answerText,fn){if(!questionText){return}var html='<label class="dialog-label">'+questionText+' <input type="text" class="text dialog-input" value="'+answerText+'"></label> <button class="dialog-button dialog-ok-button">'+MooEditable.Locale.get("ok")+'</button><button class="dialog-button dialog-cancel-button">'+MooEditable.Locale.get("cancel")+"</button>";return new MooEditable.UI.Dialog(html,{"class":"mooeditable-prompt-dialog",onOpen:function(){var input=this.el.getElement(".dialog-input");(function(){input.focus();input.select()}).delay(10)},onClick:function(e){e.preventDefault();if(e.target.tagName.toLowerCase()!="button"){return}var button=document.id(e.target);var input=this.el.getElement(".dialog-input");if(button.hasClass("dialog-cancel-button")){input.set("value",answerText);this.close()}else{if(button.hasClass("dialog-ok-button")){var answer=input.get("value");input.set("value",answerText);this.close();if(fn){fn.attempt(answer,this)}}}}})};MooEditable.Actions={bold:{title:MooEditable.Locale.get("bold"),options:{shortcut:"b"},states:{tags:["b","strong"],css:{"font-weight":"bold"}},events:{beforeToggleView:function(){if(Browser.firefox){var value=this.textarea.get("value");var newValue=value.replace(/<strong([^>]*)>/gi,"<b$1>").replace(/<\/strong>/gi,"</b>");if(value!=newValue){this.textarea.set("value",newValue)}}},attach:function(){if(Browser.firefox){var value=this.textarea.get("value");var newValue=value.replace(/<strong([^>]*)>/gi,"<b$1>").replace(/<\/strong>/gi,"</b>");if(value!=newValue){this.textarea.set("value",newValue);this.setContent(newValue)}}}}},italic:{title:MooEditable.Locale.get("italic"),options:{shortcut:"i"},states:{tags:["i","em"],css:{"font-style":"italic"}},events:{beforeToggleView:function(){if(Browser.firefox){var value=this.textarea.get("value");var newValue=value.replace(/<embed([^>]*)>/gi,"<tmpembed$1>").replace(/<em([^>]*)>/gi,"<i$1>").replace(/<tmpembed([^>]*)>/gi,"<embed$1>").replace(/<\/em>/gi,"</i>");if(value!=newValue){this.textarea.set("value",newValue)}}},attach:function(){if(Browser.firefox){var value=this.textarea.get("value");var newValue=value.replace(/<embed([^>]*)>/gi,"<tmpembed$1>").replace(/<em([^>]*)>/gi,"<i$1>").replace(/<tmpembed([^>]*)>/gi,"<embed$1>").replace(/<\/em>/gi,"</i>");if(value!=newValue){this.textarea.set("value",newValue);this.setContent(newValue)}}}}},underline:{title:MooEditable.Locale.get("underline"),options:{shortcut:"u"},states:{tags:["u"],css:{"text-decoration":"underline"}}},strikethrough:{title:MooEditable.Locale.get("strikethrough"),options:{shortcut:"s"},states:{tags:["s","strike"],css:{"text-decoration":"line-through"}}},insertunorderedlist:{title:MooEditable.Locale.get("unorderedList"),states:{tags:["ul"]}},insertorderedlist:{title:MooEditable.Locale.get("orderedList"),states:{tags:["ol"]}},indent:{title:MooEditable.Locale.get("indent"),states:{tags:["blockquote"]}},outdent:{title:MooEditable.Locale.get("outdent")},undo:{title:MooEditable.Locale.get("undo"),options:{shortcut:"z"}},redo:{title:MooEditable.Locale.get("redo"),options:{shortcut:"y"}},unlink:{title:MooEditable.Locale.get("removeHyperlink")},createlink:{title:MooEditable.Locale.get("addHyperlink"),options:{shortcut:"l"},states:{tags:["a"]},dialogs:{alert:MooEditable.UI.AlertDialog.pass(MooEditable.Locale.get("selectTextHyperlink")),prompt:function(editor){return MooEditable.UI.PromptDialog(MooEditable.Locale.get("enterURL"),"http://",function(url){editor.execute("createlink",false,url.trim())})}},command:function(){var selection=this.selection;var dialogs=this.dialogs.createlink;if(selection.isCollapsed()){var node=selection.getNode();if(node.get("tag")=="a"&&node.get("href")){selection.selectNode(node);var prompt=dialogs.prompt;prompt.el.getElement(".dialog-input").set("value",node.get("href"));prompt.open()}else{dialogs.alert.open()}}else{var text=selection.getText();var prompt=dialogs.prompt;if(urlRegex.test(text)){prompt.el.getElement(".dialog-input").set("value",text)}prompt.open()}}},urlimage:{title:MooEditable.Locale.get("addImage"),options:{shortcut:"m"},dialogs:{prompt:function(editor){return MooEditable.UI.PromptDialog(MooEditable.Locale.get("enterImageURL"),"http://",function(url){editor.execute("insertimage",false,url.trim())})}},command:function(){this.dialogs.urlimage.prompt.open()}},toggleview:{title:MooEditable.Locale.get("toggleView"),command:function(){(this.mode=="textarea")?this.toolbar.enable():this.toolbar.disable("toggleview");this.toggleView()}}};MooEditable.Actions.Settings={};Element.Properties.mooeditable={get:function(){return this.retrieve("MooEditable")}};Element.implement({mooEditable:function(options){var mooeditable=this.get("mooeditable");if(!mooeditable){mooeditable=new MooEditable(this,options)}return mooeditable}})})();var DatePicker=new Class({Implements:Options,d:"",today:"",choice:{},bodysize:{},limit:{},attachTo:null,picker:null,slider:null,oldContents:null,newContents:null,input:null,visual:null,options:{pickerClass:"datepicker",days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],dayShort:2,monthShort:3,startDay:1,timePicker:false,timePickerOnly:false,yearPicker:true,yearsPerPage:20,format:"d-m-Y",allowEmpty:false,inputOutputFormat:"U",animationDuration:400,useFadeInOut:!Browser.Engine.trident,startView:"month",positionOffset:{x:0,y:0},minDate:null,maxDate:null,debug:false,toggleElements:null,onShow:$empty,onClose:$empty,onSelect:$empty},initialize:function(attachTo,options){this.attachTo=attachTo;this.setOptions(options).attach();if(this.options.timePickerOnly){this.options.timePicker=true;this.options.startView="time"}this.formatMinMaxDates();document.addEvent("mousedown",this.close.bind(this))},formatMinMaxDates:function(){if(this.options.minDate&&this.options.minDate.format){this.options.minDate=this.unformat(this.options.minDate.date,this.options.minDate.format)}if(this.options.maxDate&&this.options.maxDate.format){this.options.maxDate=this.unformat(this.options.maxDate.date,this.options.maxDate.format);this.options.maxDate.setHours(23);this.options.maxDate.setMinutes(59);this.options.maxDate.setSeconds(59)}},attach:function(){if($chk(this.options.toggleElements)){var togglers=$$(this.options.toggleElements);document.addEvents({keydown:function(e){if(e.key=="tab"){this.close(null,true)}}.bind(this)})}$$(this.attachTo).each(function(item,index){if(item.retrieve("datepicker")){return}if($chk(item.get("value"))){var init_clone_val=this.format(new Date(this.unformat(item.get("value"),this.options.inputOutputFormat)),this.options.format)}else{if(!this.options.allowEmpty){var init_clone_val=this.format(new Date(),this.options.format)}else{var init_clone_val=""}}var display=item.getStyle("display");var clone=item.setStyle("display",this.options.debug?display:"none").store("datepicker",true).clone().store("datepicker",true).removeProperty("name").setStyle("display",display).set("value",init_clone_val).inject(item,"after");if($chk(this.options.toggleElements)){togglers[index].setStyle("cursor","pointer").addEvents({click:function(e){this.onFocus(item,clone)}.bind(this)});clone.addEvents({blur:function(){item.set("value",clone.get("value"))}})}else{clone.addEvents({keydown:function(e){if(this.options.allowEmpty&&(e.key=="delete"||e.key=="backspace")){item.set("value","");e.target.set("value","");this.close(null,true)}else{if(e.key=="tab"){this.close(null,true)}else{e.stop()}}}.bind(this),focus:function(e){this.onFocus(item,clone)}.bind(this)})}}.bind(this))},onFocus:function(original_input,visual_input){var init_visual_date,d=visual_input.getCoordinates();if($chk(original_input.get("value"))){init_visual_date=this.unformat(original_input.get("value"),this.options.inputOutputFormat).valueOf()}else{init_visual_date=new Date();if($chk(this.options.maxDate)&&init_visual_date.valueOf()>this.options.maxDate.valueOf()){init_visual_date=new Date(this.options.maxDate.valueOf())}if($chk(this.options.minDate)&&init_visual_date.valueOf()<this.options.minDate.valueOf()){init_visual_date=new Date(this.options.minDate.valueOf())}}this.show({left:d.left+this.options.positionOffset.x,top:d.top+d.height+this.options.positionOffset.y},init_visual_date);this.input=original_input;this.visual=visual_input;this.options.onShow()},dateToObject:function(d){return{year:d.getFullYear(),month:d.getMonth(),day:d.getDate(),hours:d.getHours(),minutes:d.getMinutes(),seconds:d.getSeconds()}},dateFromObject:function(values){var d=new Date();d.setDate(1);["year","month","day","hours","minutes","seconds"].each(function(type){var v=values[type];if(!$chk(v)){return}switch(type){case"day":d.setDate(v);break;case"month":d.setMonth(v);break;case"year":d.setFullYear(v);break;case"hours":d.setHours(v);break;case"minutes":d.setMinutes(v);break;case"seconds":d.setSeconds(v);break}});return d},show:function(position,timestamp){this.formatMinMaxDates();if($chk(timestamp)){this.d=new Date(timestamp)}else{this.d=new Date()}this.today=new Date();this.choice=this.dateToObject(this.d);this.mode=(this.options.startView=="time"&&!this.options.timePicker)?"month":this.options.startView;this.render();this.picker.setStyles(position)},render:function(fx){if(!$chk(this.picker)){this.constructPicker()}else{var o=this.oldContents;this.oldContents=this.newContents;this.newContents=o;this.newContents.empty()}var startDate=new Date(this.d.getTime());this.limit={right:false,left:false};if(this.mode=="decades"){this.renderDecades()}else{if(this.mode=="year"){this.renderYear()}else{if(this.mode=="time"){this.renderTime();this.limit={right:true,left:true}}else{this.renderMonth()}}}this.picker.getElement(".previous").setStyle("visibility",this.limit.left?"hidden":"visible");this.picker.getElement(".next").setStyle("visibility",this.limit.right?"hidden":"visible");this.picker.getElement(".titleText").setStyle("cursor",this.allowZoomOut()?"pointer":"default");this.d=startDate;if(this.picker.getStyle("opacity")==0){this.picker.tween("opacity",0,1)}if($chk(fx)){this.fx(fx)}},fx:function(fx){if(fx=="right"){this.oldContents.setStyles({left:0,opacity:1});this.newContents.setStyles({left:this.bodysize.x,opacity:1});this.slider.setStyle("left",0).tween("left",0,-this.bodysize.x)}else{if(fx=="left"){this.oldContents.setStyles({left:this.bodysize.x,opacity:1});this.newContents.setStyles({left:0,opacity:1});this.slider.setStyle("left",-this.bodysize.x).tween("left",-this.bodysize.x,0)}else{if(fx=="fade"){this.slider.setStyle("left",0);this.oldContents.setStyle("left",0).set("tween",{duration:this.options.animationDuration/2}).tween("opacity",1,0);this.newContents.setStyles({opacity:0,left:0}).set("tween",{duration:this.options.animationDuration}).tween("opacity",0,1)}}}},constructPicker:function(){this.picker=new Element("div",{"class":this.options.pickerClass}).inject(document.body);if(this.options.useFadeInOut){this.picker.setStyle("opacity",0).set("tween",{duration:this.options.animationDuration})}var h=new Element("div",{"class":"header"}).inject(this.picker);var titlecontainer=new Element("div",{"class":"title"}).inject(h);new Element("div",{"class":"previous"}).addEvent("click",this.previous.bind(this)).set("text","«").inject(h);new Element("div",{"class":"next"}).addEvent("click",this.next.bind(this)).set("text","»").inject(h);new Element("div",{"class":"closeButton"}).addEvent("click",this.close.bindWithEvent(this,true)).set("text","x").inject(h);new Element("span",{"class":"titleText"}).addEvent("click",this.zoomOut.bind(this)).inject(titlecontainer);var b=new Element("div",{"class":"body"}).inject(this.picker);this.bodysize=b.getSize();this.slider=new Element("div",{styles:{position:"absolute",top:0,left:0,width:2*this.bodysize.x,height:this.bodysize.y}}).set("tween",{duration:this.options.animationDuration,transition:Fx.Transitions.Quad.easeInOut}).inject(b);this.oldContents=new Element("div",{styles:{position:"absolute",top:0,left:this.bodysize.x,width:this.bodysize.x,height:this.bodysize.y}}).inject(this.slider);this.newContents=new Element("div",{styles:{position:"absolute",top:0,left:0,width:this.bodysize.x,height:this.bodysize.y}}).inject(this.slider)},renderTime:function(){var container=new Element("div",{"class":"time"}).inject(this.newContents);if(this.options.timePickerOnly){this.picker.getElement(".titleText").set("text","Select a time")}else{this.picker.getElement(".titleText").set("text",this.format(this.d,"j M, Y"))}new Element("input",{type:"text","class":"hour"}).set("value",this.leadZero(this.d.getHours())).addEvents({mousewheel:function(e){var i=e.target,v=i.get("value").toInt();i.focus();if(e.wheel>0){v=(v<23)?v+1:0}else{v=(v>0)?v-1:23}i.set("value",this.leadZero(v));e.stop()}.bind(this)}).set("maxlength",2).inject(container);new Element("input",{type:"text","class":"minutes"}).set("value",this.leadZero(this.d.getMinutes())).addEvents({mousewheel:function(e){var i=e.target,v=i.get("value").toInt();i.focus();if(e.wheel>0){v=(v<59)?v+1:0}else{v=(v>0)?v-1:59}i.set("value",this.leadZero(v));e.stop()}.bind(this)}).set("maxlength",2).inject(container);new Element("div",{"class":"separator"}).set("text",":").inject(container);new Element("input",{type:"submit",value:"OK","class":"ok"}).addEvents({click:function(e){e.stop();this.select($merge(this.dateToObject(this.d),{hours:this.picker.getElement(".hour").get("value").toInt(),minutes:this.picker.getElement(".minutes").get("value").toInt()}))}.bind(this)}).set("maxlength",2).inject(container)},renderMonth:function(){var month=this.d.getMonth();this.picker.getElement(".titleText").set("text",this.options.months[month]+" "+this.d.getFullYear());this.d.setDate(1);while(this.d.getDay()!=this.options.startDay){this.d.setDate(this.d.getDate()-1)}var container=new Element("div",{"class":"days"}).inject(this.newContents);var titles=new Element("div",{"class":"titles"}).inject(container);var d,i,classes,e,weekcontainer;for(d=this.options.startDay;d<(this.options.startDay+7);d++){new Element("div",{"class":"title day day"+(d%7)}).set("text",this.options.days[(d%7)].substring(0,this.options.dayShort)).inject(titles)}var available=false;var t=this.today.toDateString();var currentChoice=this.dateFromObject(this.choice).toDateString();for(i=0;i<42;i++){classes=[];classes.push("day");classes.push("day"+this.d.getDay());if(this.d.toDateString()==t){classes.push("today")}if(this.d.toDateString()==currentChoice){classes.push("selected")}if(this.d.getMonth()!=month){classes.push("otherMonth")}if(i%7==0){weekcontainer=new Element("div",{"class":"week week"+(Math.floor(i/7))}).inject(container)}e=new Element("div",{"class":classes.join(" ")}).set("text",this.d.getDate()).inject(weekcontainer);if(this.limited("date")){e.addClass("unavailable");if(available){this.limit.right=true}else{if(this.d.getMonth()==month){this.limit.left=true}}}else{available=true;e.addEvent("click",function(e,d){if(this.options.timePicker){this.d.setDate(d.day);this.d.setMonth(d.month);this.mode="time";this.render("fade")}else{this.select(d)}}.bindWithEvent(this,{day:this.d.getDate(),month:this.d.getMonth(),year:this.d.getFullYear()}))}this.d.setDate(this.d.getDate()+1)}if(!available){this.limit.right=true}},renderYear:function(){var month=this.today.getMonth();var thisyear=this.d.getFullYear()==this.today.getFullYear();var selectedyear=this.d.getFullYear()==this.choice.year;this.picker.getElement(".titleText").set("text",this.d.getFullYear());this.d.setMonth(0);var i,e;var available=false;var container=new Element("div",{"class":"months"}).inject(this.newContents);for(i=0;i<=11;i++){e=new Element("div",{"class":"month month"+(i+1)+(i==month&&thisyear?" today":"")+(i==this.choice.month&&selectedyear?" selected":"")}).set("text",this.options.monthShort?this.options.months[i].substring(0,this.options.monthShort):this.options.months[i]).inject(container);if(this.limited("month")){e.addClass("unavailable");if(available){this.limit.right=true}else{this.limit.left=true}}else{available=true;e.addEvent("click",function(e,d){this.d.setDate(1);this.d.setMonth(d);this.mode="month";this.render("fade")}.bindWithEvent(this,i))}this.d.setMonth(i)}if(!available){this.limit.right=true}},renderDecades:function(){while(this.d.getFullYear()%this.options.yearsPerPage>0){this.d.setFullYear(this.d.getFullYear()-1)}this.picker.getElement(".titleText").set("text",this.d.getFullYear()+"-"+(this.d.getFullYear()+this.options.yearsPerPage-1));var i,y,e;var available=false;var container=new Element("div",{"class":"years"}).inject(this.newContents);if($chk(this.options.minDate)&&this.d.getFullYear()<=this.options.minDate.getFullYear()){this.limit.left=true}for(i=0;i<this.options.yearsPerPage;i++){y=this.d.getFullYear();e=new Element("div",{"class":"year year"+i+(y==this.today.getFullYear()?" today":"")+(y==this.choice.year?" selected":"")}).set("text",y).inject(container);if(this.limited("year")){e.addClass("unavailable");if(available){this.limit.right=true}else{this.limit.left=true}}else{available=true;e.addEvent("click",function(e,d){this.d.setFullYear(d);this.mode="year";this.render("fade")}.bindWithEvent(this,y))}this.d.setFullYear(this.d.getFullYear()+1)}if(!available){this.limit.right=true}if($chk(this.options.maxDate)&&this.d.getFullYear()>=this.options.maxDate.getFullYear()){this.limit.right=true}},limited:function(type){var cs=$chk(this.options.minDate);var ce=$chk(this.options.maxDate);if(!cs&&!ce){return false}switch(type){case"year":return(cs&&this.d.getFullYear()<this.options.minDate.getFullYear())||(ce&&this.d.getFullYear()>this.options.maxDate.getFullYear());case"month":var ms=(""+this.d.getFullYear()+this.leadZero(this.d.getMonth())).toInt();return cs&&ms<(""+this.options.minDate.getFullYear()+this.leadZero(this.options.minDate.getMonth())).toInt()||ce&&ms>(""+this.options.maxDate.getFullYear()+this.leadZero(this.options.maxDate.getMonth())).toInt();case"date":return(cs&&this.d<this.options.minDate)||(ce&&this.d>this.options.maxDate)}},allowZoomOut:function(){if(this.mode=="time"&&this.options.timePickerOnly){return false}if(this.mode=="decades"){return false}if(this.mode=="year"&&!this.options.yearPicker){return false}return true},zoomOut:function(){if(!this.allowZoomOut()){return}if(this.mode=="year"){this.mode="decades"}else{if(this.mode=="time"){this.mode="month"}else{this.mode="year"}}this.render("fade")},previous:function(){if(this.mode=="decades"){this.d.setFullYear(this.d.getFullYear()-this.options.yearsPerPage)}else{if(this.mode=="year"){this.d.setFullYear(this.d.getFullYear()-1)}else{if(this.mode=="month"){this.d.setMonth(this.d.getMonth()-1)}}}this.render("left")},next:function(){if(this.mode=="decades"){this.d.setFullYear(this.d.getFullYear()+this.options.yearsPerPage)}else{if(this.mode=="year"){this.d.setFullYear(this.d.getFullYear()+1)}else{if(this.mode=="month"){this.d.setMonth(this.d.getMonth()+1)}}}this.render("right")},close:function(e,force){if(!$(this.picker)){return}var clickOutside=($chk(e)&&e.target!=this.picker&&!this.picker.hasChild(e.target)&&e.target!=this.visual);if(force||clickOutside){if(this.options.useFadeInOut){this.picker.set("tween",{duration:this.options.animationDuration/2,onComplete:this.destroy.bind(this)}).tween("opacity",1,0)}else{this.destroy()}}},destroy:function(){this.picker.destroy();this.picker=null;this.options.onClose()},select:function(values){this.choice=$merge(this.choice,values);var d=this.dateFromObject(this.choice);this.input.set("value",this.format(d,this.options.inputOutputFormat));this.visual.set("value",this.format(d,this.options.format));this.options.onSelect(d);this.close(null,true)},leadZero:function(v){return v<10?"0"+v:v},format:function(t,format){var f="";var h=t.getHours();var m=t.getMonth();for(var i=0;i<format.length;i++){switch(format.charAt(i)){case"\\":i++;f+=format.charAt(i);break;case"y":f+=(100+t.getYear()+"").substring(1);break;case"Y":f+=t.getFullYear();break;case"m":f+=this.leadZero(m+1);break;case"n":f+=(m+1);break;case"M":f+=this.options.months[m].substring(0,this.options.monthShort);break;case"F":f+=this.options.months[m];break;case"d":f+=this.leadZero(t.getDate());break;case"j":f+=t.getDate();break;case"D":f+=this.options.days[t.getDay()].substring(0,this.options.dayShort);break;case"l":f+=this.options.days[t.getDay()];break;case"G":f+=h;break;case"H":f+=this.leadZero(h);break;case"g":f+=(h%12?h%12:12);break;case"h":f+=this.leadZero(h%12?h%12:12);break;case"a":f+=(h>11?"pm":"am");break;case"A":f+=(h>11?"PM":"AM");break;case"i":f+=this.leadZero(t.getMinutes());break;case"s":f+=this.leadZero(t.getSeconds());break;case"U":f+=Math.floor(t.valueOf()/1000);break;default:f+=format.charAt(i)}}return f},unformat:function(t,format){var d=new Date();var a={};var c,m;t=t.toString();for(var i=0;i<format.length;i++){c=format.charAt(i);switch(c){case"\\":r=null;i++;break;case"y":r="[0-9]{2}";break;case"Y":r="[0-9]{4}";break;case"m":r="0[1-9]|1[012]";break;case"n":r="[1-9]|1[012]";break;case"M":r="[A-Za-z]{"+this.options.monthShort+"}";break;case"F":r="[A-Za-z]+";break;case"d":r="0[1-9]|[12][0-9]|3[01]";break;case"j":r="[1-9]|[12][0-9]|3[01]";break;case"D":r="[A-Za-z]{"+this.options.dayShort+"}";break;case"l":r="[A-Za-z]+";break;case"G":case"H":case"g":case"h":r="[0-9]{1,2}";break;case"a":r="(am|pm)";break;case"A":r="(AM|PM)";break;case"i":case"s":r="[012345][0-9]";break;case"U":r="-?[0-9]+$";break;default:r=null}if($chk(r)){m=t.match("^"+r);if($chk(m)){a[c]=m[0];t=t.substring(a[c].length)}else{if(this.options.debug){alert("Fatal Error in DatePicker\n\nUnexpected format at: '"+t+"' expected format character '"+c+"' (pattern '"+r+"')")}return d}}else{t=t.substring(1)}}for(c in a){var v=a[c];switch(c){case"y":d.setFullYear(v<30?2000+v.toInt():1900+v.toInt());break;case"Y":d.setFullYear(v);break;case"m":case"n":d.setMonth(v-1);break;case"M":v=this.options.months.filter(function(item,index){return item.substring(0,this.options.monthShort)==v}.bind(this))[0];case"F":d.setMonth(this.options.months.indexOf(v));break;case"d":case"j":d.setDate(v);break;case"G":case"H":d.setHours(v);break;case"g":case"h":if(a.a=="pm"||a.A=="PM"){d.setHours(v==12?0:v.toInt()+12)}else{d.setHours(v)}break;case"i":d.setMinutes(v);break;case"s":d.setSeconds(v);break;case"U":d=new Date(v.toInt()*1000)}}return d}});var MultipleFields=new Class({version:0.1,options:{spliter:";"},initialize:function(_object,_options){if(!_object){return}if(_object.get("data-spliter")){this.options.spliter=_object.get("data-spliter")}this.inputFields=_object;this.inputFields.each(function(elem){var template=elem.clone().erase("name").erase("id").erase("data-spliter").erase("value").addClass("template");elem.set("type","hidden");new Element("span.add_field",{text:"+"}).inject(elem,"after").addEvent("click",function(e){this.addField(elem,template)}.bind(this));elem.get("value").toString().split(this.options.spliter).each(function(data){this.addField(elem,template,data)}.bind(this))}.bind(this))},addField:function(elem,template,data){template.clone().set("value",data).addEvent("change",function(e){var values=[];e.target.getParent(".input").getElements(".template").each(function(template){if(template.value.trim()){values.push(template.value.trim())}});elem.set("value",values.join(this.options.spliter))}.bind(this)).inject(elem.getParent(".input").getElement(".add_field"),"before")}});window.addEvent("domready",function(){var ajaxNote=new Ajaxify();var lang=document.html.get("lang");if(lang==="en"){lang="en-US"}else{lang=lang+"-"+lang.toUpperCase()}Locale.use(lang);var wysiwyg=[];var setupJsForm=function(scope){scope.getElements(".wysiwyg").each(function(elem){wysiwyg.push(elem.mooEditable())});new MultipleFields(scope.getElements(".multiple_fields"));var dateFormat=Locale.get("Date.shortDate").replace(/%/g,"");var timeFormat="H:i";var dateMonths=Locale.get("Date.months");var dateDays=Locale.get("Date.days");new DatePicker(scope.getElements(".picker.datetime, .picker.timestamp"),{allowEmpty:true,inputOutputFormat:"Y-m-d H:i",months:dateMonths,days:dateDays,timePicker:true,format:dateFormat+" "+timeFormat});new DatePicker(scope.getElements(".picker.date"),{allowEmpty:true,inputOutputFormat:"Y-m-d H:i",months:dateMonths,days:dateDays,format:dateFormat});new DatePicker(scope.getElements(".picker.time"),{allowEmpty:true,inputOutputFormat:"Y-m-d H:i",months:dateMonths,days:dateDays,timePickerOnly:true,format:timeFormat})};var quickEdit=new AjaxEdit({holderParent:$("content"),onStartRequest:function(form){ajaxNote.loading()},onFormInjected:function(form){setupJsForm(form);ajaxNote.success()},onSave:function(form){ajaxNote.success()},onBeforeSubmit:function(){ajaxNote.loading();wysiwyg.each(function(elem){elem.saveContent()})}});var platforms=document.body.getElements(".platform");var main_form=document.id("main_form");if(platforms.length){var setupSortables=function(scope){new Sortables(scope.getElements(".sortable"),{handle:".handle",onStart:function(element,clone){element.addClass("dragged")},onComplete:function(element){element.removeClass("dragged");new Request({method:"get",url:this.element.getParent("tbody").get("data-sort-url")}).send({data:{order:this.serialize()}})}})};var updatePlatform=function(href,platform,callback){ajaxNote.loading();new Request({method:"get",url:href,onSuccess:function(html){platform.innerHTML=html;if(callback){callback.call()}setupSortables(platform);ajaxNote.success()}}).send()};platforms.addEvents({"click:relay(.pagination a, thead a)":function(e){e.preventDefault();updatePlatform(this.get("href"),this.getParent(".platform"))},"submit:relay(.search)":function(e){ajaxNote.loading();e.preventDefault();var parent=this.getParent(".platform");new Request({method:"get",url:this.get("action"),onSuccess:function(html){parent.innerHTML=html;setupSortables(parent);ajaxNote.success()}}).send({data:this})},"click:relay(.quick_edit)":function(e){e.preventDefault();quickEdit.startEdit(this,this.getParent("tr"))},"click:relay(.action a)":function(e){e.target.addClass("clicked")},"ajax:complete:relay(a[data-method=delete][data-remote])":function(e){e.preventDefault();this.getParent("tr").dispose()}});quickEdit.addEvents({successAndChange:function(json){var tr=this.wrapElement;tr.getElements("td").each(function(td){var name=td.get("data-column-name");if(!name){return}var a=td.getElement("a");(a?a:td).innerHTML=json[name]||""})},successAndNext:function(json){var tr=this.wrapElement;var nextTr=tr.getNext("tr");if(nextTr){quickEdit.startEdit(nextTr.getElement("a"),nextTr)}else{var platform=tr.getParent(".platform");var loadMore=platform.getElement(".load_more");if(loadMore){trIndex=tr.getParent("tbody").getElements("tr").indexOf(tr);updatePlatform(loadMore.get("href"),platform,function(){platform.getElements("tbody tr").each(function(newTr,index){if(trIndex===index){nextTr=newTr.getNext("tr");quickEdit.startEdit(nextTr.getElement("a"),nextTr)}})})}else{nextTr=platform.getElements("tbody tr")[0];quickEdit.startEdit(nextTr.getElement("a"),nextTr)}}}});setupSortables(document.body)}else{if(main_form){setupJsForm(main_form);main_form.addEvents({"click:relay(.quick_edit)":function(e){e.preventDefault();quickEdit.startEdit(this)}});quickEdit.addEvents({successAndChange:function(json){this.wrapElement.set("text",json.to_bhf_s||"")},successAndNext:function(json){var a=this.wrapElement;var li=a.getParent("li");if(!li){this.close();return}var holder=li.getNext("li");if(!holder){holder=li.getParent("ul")}quickEdit.startEdit(holder.getElement("a"))}})}}var dbch=document.body.clientHeight;window.onresize=function(e){dbch=document.body.clientHeight};window.onscroll=function(e){var innerForm=quickEdit.holder.getElement("form");if(!innerForm){return}var scroll=document.body.scrollTop-70;if(scroll<10){scroll=10}if(scroll+innerForm.getSize().y>dbch){return}quickEdit.holder.setStyle("padding-top",scroll)};var fm=$("flash_massages");if(fm){fm.addClass("show").removeClass.delay(4000,fm,"show")}new BrowserUpdate({vs:{i:8,f:3,o:10.01,s:2,n:9}})});
599
+ (function($){window.rails={applyEvents:function(el){el=$(el||document.body);var apply=function(selector,action,callback){el.getElements(selector).addEvent(action,callback)};apply('form[data-remote="true"]',"submit",rails.handleRemote);apply('a[data-remote="true"], input[data-remote="true"]',"click",rails.handleRemote);apply("a[data-method][data-remote!=true]","click",function(e){e.preventDefault();if(rails.confirmed(this)){var form=new Element("form",{method:"post",action:this.get("href"),styles:{display:"none"}}).inject(this,"after");var methodInput=new Element("input",{type:"hidden",name:"_method",value:this.get("data-method")});var csrfInput=new Element("input",{type:"hidden",name:rails.csrf.param,value:rails.csrf.token});form.adopt(methodInput,csrfInput).submit()}});var noMethodNorRemoteConfirm=":not([data-method]):not([data-remote=true])[data-confirm]";apply("a"+noMethodNorRemoteConfirm+",input"+noMethodNorRemoteConfirm,"click",function(){return rails.confirmed(this)})},getCsrf:function(name){var meta=document.getElement("meta[name=csrf-"+name+"]");return(meta?meta.get("content"):null)},confirmed:function(el){var confirmMessage=el.get("data-confirm");if(confirmMessage&&!confirm(confirmMessage)){return false}return true},disable:function(el){var button=el.get("data-disable-with")?el:el.getElement("[data-disable-with]");if(button){var enableWith=button.get("value");el.addEvent("ajax:complete",function(){button.set({value:enableWith,disabled:false})});button.set({value:button.get("data-disable-with"),disabled:true})}},handleRemote:function(e){e.preventDefault();if(rails.confirmed(this)){this.request=new Request.Rails(this);rails.disable(this);this.request.send()}}};Request.Rails=new Class({Extends:Request,initialize:function(element,options){this.el=element;this.parent(Object.merge({},{method:this.el.get("method")||this.el.get("data-method")||"get",url:this.el.get("action")||this.el.get("href")},options));this.headers.Accept="*/*";this.addRailsEvents()},send:function(options){this.el.fireEvent("ajax:before");if(this.el.get("tag")=="form"){this.options.data=this.el}this.parent(options);this.el.fireEvent("ajax:after",this.xhr)},addRailsEvents:function(){this.addEvent("request",function(){this.el.fireEvent("ajax:loading",this.xhr)});this.addEvent("success",function(){this.el.fireEvent("ajax:success",this.xhr)});this.addEvent("complete",function(){this.el.fireEvent("ajax:complete",this.xhr);this.el.fireEvent("ajax:loaded",this.xhr)});this.addEvent("failure",function(){this.el.fireEvent("ajax:failure",this.xhr)})}})})(document.id);window.addEvent("domready",function(){rails.csrf={token:rails.getCsrf("token"),param:rails.getCsrf("param")};rails.applyEvents()});var BrowserUpdate=new Class({initialize:function(op,test){var b,jsv=5,n=window.navigator;this.op=op||{};this.op.l=op.l||n.language||n.userLanguage||document.documentElement.getAttribute("lang")||"en";this.op.vsakt={i:8,f:3.6,o:10.6,s:5,n:10};this.op.vsdefault={i:6,f:2,o:9.64,s:3,n:10};this.op.vs=op.vs||this.op.vsdefault;for(b in this.op.vsakt){if(this.op.vs[b]>=this.op.vsakt[b]){this.op.vs[b]=this.op.vsdefault[b]}}if(!op.reminder||op.reminder<0.1){this.op.reminder=0}else{this.op.reminder=op.reminder||24}this.op.onshow=op.onshow||function(o){};this.op.url=op.url||"http://browser-update.org/update.html";this.op.pageurl=op.pageurl||window.location.hostname||"unknown";this.op.newwindow=op.newwindow||false;this.op.test=test||op.test||false;if(window.location.hash=="#test-bu"){this.op.test=true}function getBrowser(){var n,v,t,ua=navigator.userAgent,names={i:"Internet Explorer",f:"Firefox",o:"Opera",s:"Apple Safari",n:"Netscape Navigator",c:"Chrome",x:"Other"};if(/like firefox|chromeframe|seamonkey|opera mini|meego|netfront|moblin|maemo|arora|camino|flot|k-meleon|fennec|kazehakase|galeon|android|mobile|iphone|ipod|ipad|symbian|webos/i.test(ua)){n="x"}else{if(/MSIE (\d+\.\d+);/.test(ua)){n="i"}else{if(/Chrome.(\d+\.\d+)/i.test(ua)){n="c"}else{if(/Firefox.(\d+\.\d+)/i.test(ua)){n="f"}else{if(/Version.(\d+.\d+).{0,10}Safari/i.test(ua)){n="s"}else{if(/Safari.(\d+)/i.test(ua)){n="so"}else{if(/Opera.*Version.(\d+\.\d+)/i.test(ua)){n="o"}else{if(/Opera.(\d+\.\d+)/i.test(ua)){n="o"}else{if(/Netscape.(\d+)/i.test(ua)){n="n"}else{return{n:"x",v:0,t:names[n]}}}}}}}}}}if(n=="x"){return{n:"x",v:0,t:names[n]}}v=new Number(RegExp.$1);if(n=="so"){v=((v<100)&&1)||((v<130)&&1.2)||((v<320)&&1.3)||((v<520)&&2)||((v<524)&&3)||((v<526)&&3.2)||4;n="s"}if(n=="i"&&v==7&&window.XDomainRequest){v=8}return{n:n,v:v,t:names[n]+" "+v}}this.op.browser=getBrowser();if(!this.op.test&&(!this.op.browser||!this.op.browser.n||this.op.browser.n=="x"||this.op.browser.n=="c"||document.cookie.indexOf("browserupdateorg=pause")>-1||this.op.browser.v>this.op.vs[this.op.browser.n])){return}if(this.op.reminder>0){var d=new Date(new Date().getTime()+1000*3600*this.op.reminder);document.cookie="browserupdateorg=pause; expires="+d.toGMTString()+"; path=/"}var ll=this.op.l.substr(0,2);var languages="de,en";if(languages.indexOf(ll)!==false){this.op.url="http://browser-update.org/"+ll+"/update.html#"+jsv}var tar="";if(this.op.newwindow){tar=' target="_blank"'}function busprintf(){var args=arguments;var data=args[0];for(var k=1;k<args.length;++k){data=data.replace(/%s/,args[k])}return data}ll=(window.Locale)?Locale.getCurrent().name:"en-US";var t="Your browser (%s) is <b>out of date</b>. It has known <b>security flaws</b> and may <b>not display all features</b> of this and other websites. <a%s>Learn how to update your browser</a>";if(ll=="de-DE"){t="Sie verwenden einen <b>veralteten Browser</b> (%s) mit <b>Sicherheitsschwachstellen</b> und <b>k&ouml;nnen nicht alle Funktionen dieser Webseite nutzen</b>. <a%s>Hier erfahren Sie, wie einfach Sie Ihren Browser aktualisieren k&ouml;nnen</a>."}if(op.text){t=op.text}this.op.text=busprintf(t,this.op.browser.t,' href="'+this.op.url+'"'+tar);var div=document.createElement("div");this.op.div=div;div.id="buorg";div.className="buorg";div.innerHTML="<div>"+this.op.text+'<div id="buorgclose">X</div></div>';var sheet=document.createElement("style");var style=".buorg {position:absolute;z-index:111111; width:100%; top:0px; left:0px; border-bottom:1px solid #A29330; background:#FDF2AB no-repeat 10px center url(http://browser-update.org/img/dialog-warning.gif); text-align:left; cursor:pointer; font-family: Arial,Helvetica,sans-serif; color:#000; font-size: 12px;} .buorg div { padding:5px 36px 5px 40px; } .buorg a,.buorg a:visited {color:#E25600; text-decoration: underline;} #buorgclose { position: absolute; right: .5em; top:.2em; height: 20px; width: 12px; font-weight: bold;font-size:14px; padding:0; }";document.body.insertBefore(div,document.body.firstChild);document.getElementsByTagName("head")[0].appendChild(sheet);try{sheet.innerText=style;sheet.innerHTML=style}catch(e){try{sheet.styleSheet.cssText=style}catch(e){return}}var me=this;div.onclick=function(){if(me.op.newwindow){window.open(me.op.url,"_blank")}else{window.location.href=me.op.url}return false};div.getElementsByTagName("a")[0].onclick=function(e){var e=e||window.event;if(e.stopPropagation){e.stopPropagation()}else{e.cancelBubble=true}return true};this.op.bodymt=document.body.style.paddingTop;document.body.style.paddingTop=(div.clientHeight)+"px";document.getElementById("buorgclose").onclick=function(e){var e=e||window.event;if(e.stopPropagation){e.stopPropagation()}else{e.cancelBubble=true}me.op.div.style.display="none";document.body.style.paddingTop=me.op.bodymt;return true};op.onshow(this.op)}});var Ajaxify=new Class({version:0.2,Implements:[Options,Events],options:{events:{loading:{name:"ajax:loading",text:"Loading…"},success:{name:"ajax:success",text:"Changes successfully saved!"},failure:{name:"ajax:failure",text:"Oops, something went wrong…"}},holder:new Element("div#ajax_holder"),fadeOutDuration:2000},initialize:function(_options){this.setOptions(_options);this.holder=this.options.holder.inject(document.body)},applyEvents:function(el){el=document.id(el||document.body);var apply=function(action,callback){el.getElements('[data-remote="true"]').addEvent(action,callback)};apply(this.options.events.loading.name,this.loading.bind(this));apply(this.options.events.success.name,this.success.bind(this));apply(this.options.events.failure.name,this.failure.bind(this))},loading:function(xhr){this.setMessage("loading",false)},success:function(xhr){this.setMessage("success",true)},failure:function(xhr){this.setMessage("failure",true)},setMessage:function(status,fadeOut){this.holder.set("text",this.options.events[status].text).set("class",status);if(fadeOut){this.holder.addClass("fadeout");setTimeout(function(){this.holder.erase("class")}.bind(this),this.options.fadeOutDuration)}}});var AjaxEdit=new Class({version:0.2,options:{holderParent:document.body},Implements:[Options,Events],holder:new Element("div.quick_edit_holder"),initialize:function(_options){this.setOptions(_options);this.holder.addEvents({"click:relay(.open)":function(e){e.preventDefault();location.href=this.wrapElement.getElement("a").get("href")}.bind(this),"click:relay(.cancel)":function(e){e.preventDefault();this.close()}.bind(this),"click:relay(.save_and_next)":function(e){e.preventDefault();this.submit(["successAndChange","successAndNext"])}.bind(this),"click:relay(.save)":function(e){e.preventDefault();this.submit(["successAndChange"])}.bind(this),"submit:relay(form)":function(e){e.preventDefault();this.submit(["successAndChange"])}.bind(this)})},startEdit:function(element,wrapElement){this.clean();this.wrapElement=wrapElement?wrapElement:element;this.wrapElement.addClass("live_edit");this.fireEvent("startRequest");new Request.HTML({method:"get",evalScripts:false,url:element.get("href"),onSuccess:function(responseTree,responseElements,responseHTML,responseJavaScript){this.injectForm(responseHTML);eval(responseJavaScript)}.bind(this)}).send()},submit:function(eventNames){var form=this.holder.getElement("form");this.fireEvent("beforeSubmit");new Request.JSON({method:form.get("method"),url:form.get("action"),evalScripts:true,onRequest:function(){this.disableButtons()}.bind(this),onFailure:function(invalidForm){this.injectForm(invalidForm.response);invalidForm.response.stripScripts(function(script){eval(script)})}.bind(this),onSuccess:function(json){if(!eventNames.contains("successAndNext")){this.close()}eventNames.each(function(eventName){this.fireEvent(eventName,[json])}.bind(this));this.fireEvent("save")}.bind(this)}).send({data:form})},disableButtons:function(){this.holder.getElements(".open, .cancel, .save_and_next, .save").set("disabled","disabled")},clean:function(){document.body.getElements(".live_edit").removeClass("live_edit")},close:function(){this.clean();this.holder.dispose()},injectForm:function(form){this.holder.innerHTML=form;this.holder.inject(this.options.holderParent);this.fireEvent("formInjected",[this.holder])}});(function(){var blockEls=/^(H[1-6]|HR|P|DIV|ADDRESS|PRE|FORM|TABLE|LI|OL|UL|TD|CAPTION|BLOCKQUOTE|CENTER|DL|DT|DD|SCRIPT|NOSCRIPT|STYLE)$/i;var urlRegex=/^(https?|ftp|rmtp|mms):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i;var protectRegex=/<(script|noscript|style)[\u0000-\uFFFF]*?<\/(script|noscript|style)>/g;this.MooEditable=new Class({Implements:[Events,Options],options:{toolbar:true,cleanup:true,paragraphise:true,xhtml:true,semantics:true,actions:"bold italic underline strikethrough | insertunorderedlist insertorderedlist indent outdent | undo redo | createlink unlink | urlimage | toggleview",handleSubmit:true,handleLabel:true,disabled:false,baseCSS:"html{ height: 100%; cursor: text; } body{ font-family: sans-serif; }",extraCSS:"",externalCSS:"",html:'<!DOCTYPE html><html><head><meta charset="UTF-8">{BASEHREF}<style>{BASECSS} {EXTRACSS}</style>{EXTERNALCSS}</head><body></body></html>',rootElement:"p",baseURL:"",dimensions:null},initialize:function(el,options){this.setOptions(options);this.textarea=document.id(el);this.textarea.store("MooEditable",this);this.actions=this.options.actions.clean().split(" ");this.keys={};this.dialogs={};this.protectedElements=[];this.actions.each(function(action){var act=MooEditable.Actions[action];if(!act){return}if(act.options){var key=act.options.shortcut;if(key){this.keys[key]=action}}if(act.dialogs){Object.each(act.dialogs,function(dialog,name){dialog=dialog.attempt(this);dialog.name=action+":"+name;if(typeOf(this.dialogs[action])!="object"){this.dialogs[action]={}}this.dialogs[action][name]=dialog},this)}if(act.events){Object.each(act.events,function(fn,event){this.addEvent(event,fn)},this)}}.bind(this));this.render()},toElement:function(){return this.textarea},render:function(){var self=this;var dimensions=this.options.dimensions||this.textarea.getSize();this.container=new Element("div",{id:(this.textarea.id)?this.textarea.id+"-mooeditable-container":null,"class":"mooeditable-container",styles:{width:dimensions.x}});this.textarea.addClass("mooeditable-textarea").setStyle("height",dimensions.y);this.iframe=new IFrame({"class":"mooeditable-iframe",frameBorder:0,src:'javascript:""',styles:{height:dimensions.y}});this.toolbar=new MooEditable.UI.Toolbar({onItemAction:function(){var args=Array.from(arguments);var item=args[0];self.action(item.name,args)}});this.attach.delay(1,this);if(this.options.handleLabel&&this.textarea.id){$$('label[for="'+this.textarea.id+'"]').addEvent("click",function(e){if(self.mode!="iframe"){return}e.preventDefault();self.focus()})}if(this.options.handleSubmit){this.form=this.textarea.getParent("form");if(!this.form){return}this.form.addEvent("submit",function(){if(self.mode=="iframe"){self.saveContent()}})}this.fireEvent("render",this)},attach:function(){var self=this;this.mode="iframe";this.editorDisabled=false;this.container.wraps(this.textarea);this.textarea.setStyle("display","none");this.iframe.setStyle("display","").inject(this.textarea,"before");Object.each(this.dialogs,function(action,name){Object.each(action,function(dialog){document.id(dialog).inject(self.iframe,"before");var range;dialog.addEvents({open:function(){range=self.selection.getRange();self.editorDisabled=true;self.toolbar.disable(name);self.fireEvent("dialogOpen",this)},close:function(){self.toolbar.enable();self.editorDisabled=false;self.focus();if(range){self.selection.setRange(range)}self.fireEvent("dialogClose",this)}})})});this.win=this.iframe.contentWindow;this.doc=this.win.document;if(Browser.firefox){this.doc.designMode="On"}var docHTML=this.options.html.substitute({BASECSS:this.options.baseCSS,EXTRACSS:this.options.extraCSS,EXTERNALCSS:(this.options.externalCSS)?'<link rel="stylesheet" href="'+this.options.externalCSS+'">':"",BASEHREF:(this.options.baseURL)?'<base href="'+this.options.baseURL+'" />':""});this.doc.open();this.doc.write(docHTML);this.doc.close();(Browser.ie)?this.doc.body.contentEditable=true:this.doc.designMode="On";Object.append(this.win,new Window);Object.append(this.doc,new Document);if(Browser.Element){var winElement=this.win.Element.prototype;for(var method in Element){if(!method.test(/^[A-Z]|\$|prototype|mooEditable/)){winElement[method]=Element.prototype[method]}}}else{document.id(this.doc.body)}this.setContent(this.textarea.get("value"));this.doc.addEvents({mouseup:this.editorMouseUp.bind(this),mousedown:this.editorMouseDown.bind(this),mouseover:this.editorMouseOver.bind(this),mouseout:this.editorMouseOut.bind(this),mouseenter:this.editorMouseEnter.bind(this),mouseleave:this.editorMouseLeave.bind(this),contextmenu:this.editorContextMenu.bind(this),click:this.editorClick.bind(this),dblclick:this.editorDoubleClick.bind(this),keypress:this.editorKeyPress.bind(this),keyup:this.editorKeyUp.bind(this),keydown:this.editorKeyDown.bind(this),focus:this.editorFocus.bind(this),blur:this.editorBlur.bind(this)});this.win.addEvents({focus:this.editorFocus.bind(this),blur:this.editorBlur.bind(this)});["cut","copy","paste"].each(function(event){self.doc.body.addListener(event,self["editor"+event.capitalize()].bind(self))});this.textarea.addEvent("keypress",this.textarea.retrieve("mooeditable:textareaKeyListener",this.keyListener.bind(this)));if(Browser.firefox2){this.doc.addEvent("focus",function(){self.win.fireEvent("focus").focus()})}if(this.doc.addEventListener){this.doc.addEventListener("focus",function(){self.win.fireEvent("focus")},true)}if(!Browser.ie&&!Browser.opera){var styleCSS=function(){self.execute("styleWithCSS",false,false);self.doc.removeEvent("focus",styleCSS)};this.win.addEvent("focus",styleCSS)}if(this.options.toolbar){document.id(this.toolbar).inject(this.container,"top");this.toolbar.render(this.actions)}if(this.options.disabled){this.disable()}this.selection=new MooEditable.Selection(this.win);this.oldContent=this.getContent();this.fireEvent("attach",this);return this},detach:function(){this.saveContent();this.textarea.setStyle("display","").removeClass("mooeditable-textarea").inject(this.container,"before");this.textarea.removeEvent("keypress",this.textarea.retrieve("mooeditable:textareaKeyListener"));this.container.dispose();this.fireEvent("detach",this);return this},enable:function(){this.editorDisabled=false;this.toolbar.enable();return this},disable:function(){this.editorDisabled=true;this.toolbar.disable();return this},editorFocus:function(e){this.oldContent="";this.fireEvent("editorFocus",[e,this])},editorBlur:function(e){this.oldContent=this.saveContent().getContent();this.fireEvent("editorBlur",[e,this])},editorMouseUp:function(e){if(this.editorDisabled){e.stop();return}if(this.options.toolbar){this.checkStates()}this.fireEvent("editorMouseUp",[e,this])},editorMouseDown:function(e){if(this.editorDisabled){e.stop();return}this.fireEvent("editorMouseDown",[e,this])},editorMouseOver:function(e){if(this.editorDisabled){e.stop();return}this.fireEvent("editorMouseOver",[e,this])},editorMouseOut:function(e){if(this.editorDisabled){e.stop();return}this.fireEvent("editorMouseOut",[e,this])},editorMouseEnter:function(e){if(this.editorDisabled){e.stop();return}if(this.oldContent&&this.getContent()!=this.oldContent){this.focus();this.fireEvent("editorPaste",[e,this])}this.fireEvent("editorMouseEnter",[e,this])},editorMouseLeave:function(e){if(this.editorDisabled){e.stop();return}this.fireEvent("editorMouseLeave",[e,this])},editorContextMenu:function(e){if(this.editorDisabled){e.stop();return}this.fireEvent("editorContextMenu",[e,this])},editorClick:function(e){if(Browser.safari||Browser.chrome){var el=e.target;if(Element.get(el,"tag")=="img"){if(this.options.baseURL){if(el.getProperty("src").indexOf("http://")==-1){el.setProperty("src",this.options.baseURL+el.getProperty("src"))}}this.selection.selectNode(el);this.checkStates()}}this.fireEvent("editorClick",[e,this])},editorDoubleClick:function(e){this.fireEvent("editorDoubleClick",[e,this])},editorKeyPress:function(e){if(this.editorDisabled){e.stop();return}this.keyListener(e);this.fireEvent("editorKeyPress",[e,this])},editorKeyUp:function(e){if(this.editorDisabled){e.stop();return}var c=e.code;if(this.options.toolbar&&(/^enter|left|up|right|down|delete|backspace$/i.test(e.key)||(c>=33&&c<=36)||c==45||e.meta||e.control)){if(Browser.ie6){clearTimeout(this.checkStatesDelay);this.checkStatesDelay=this.checkStates.delay(500,this)}else{this.checkStates()}}this.fireEvent("editorKeyUp",[e,this])},editorKeyDown:function(e){if(this.editorDisabled){e.stop();return}if(e.key=="enter"){if(this.options.paragraphise){if(e.shift&&(Browser.safari||Browser.chrome)){var s=this.selection;var r=s.getRange();var br=this.doc.createElement("br");r.insertNode(br);r.setStartAfter(br);r.setEndAfter(br);s.setRange(r);if(s.getSelection().focusNode==br.previousSibling){var nbsp=this.doc.createTextNode("\u00a0");var p=br.parentNode;var ns=br.nextSibling;(ns)?p.insertBefore(nbsp,ns):p.appendChild(nbsp);s.selectNode(nbsp);s.collapse(1)}this.win.scrollTo(0,Element.getOffsets(s.getRange().startContainer).y);e.preventDefault()}else{if(Browser.firefox||Browser.safari||Browser.chrome){var node=this.selection.getNode();var isBlock=Element.getParents(node).include(node).some(function(el){return el.nodeName.test(blockEls)});if(!isBlock){this.execute("insertparagraph")}}}}else{if(Browser.ie){var r=this.selection.getRange();var node=this.selection.getNode();if(r&&node.get("tag")!="li"){this.selection.insertContent("<br>");this.selection.collapse(false)}e.preventDefault()}}}if(Browser.opera){var ctrlmeta=e.control||e.meta;if(ctrlmeta&&e.key=="x"){this.fireEvent("editorCut",[e,this])}else{if(ctrlmeta&&e.key=="c"){this.fireEvent("editorCopy",[e,this])}else{if((ctrlmeta&&e.key=="v")||(e.shift&&e.code==45)){this.fireEvent("editorPaste",[e,this])}}}}this.fireEvent("editorKeyDown",[e,this])},editorCut:function(e){if(this.editorDisabled){e.stop();return}this.fireEvent("editorCut",[e,this])},editorCopy:function(e){if(this.editorDisabled){e.stop();return}this.fireEvent("editorCopy",[e,this])},editorPaste:function(e){if(this.editorDisabled){e.stop();return}this.fireEvent("editorPaste",[e,this])},keyListener:function(e){var key=(Browser.Platform.mac)?e.meta:e.control;if(!key||!this.keys[e.key]){return}e.preventDefault();var item=this.toolbar.getItem(this.keys[e.key]);item.action(e)},focus:function(){(this.mode=="iframe"?this.win:this.textarea).focus();this.fireEvent("focus",this);return this},action:function(command,args){var action=MooEditable.Actions[command];if(action.command&&typeOf(action.command)=="function"){action.command.apply(this,args)}else{this.focus();this.execute(command,false,args);if(this.mode=="iframe"){this.checkStates()}}},execute:function(command,param1,param2){if(this.busy){return}this.busy=true;this.doc.execCommand(command,param1,param2);this.saveContent();this.busy=false;return false},toggleView:function(){this.fireEvent("beforeToggleView",this);if(this.mode=="textarea"){this.mode="iframe";this.iframe.setStyle("display","");this.setContent(this.textarea.value);this.textarea.setStyle("display","none")}else{this.saveContent();this.mode="textarea";this.textarea.setStyle("display","");this.iframe.setStyle("display","none")}this.fireEvent("toggleView",this);this.focus.delay(10,this);return this},getContent:function(){var protect=this.protectedElements;var html=this.doc.body.get("html").replace(/<!-- mooeditable:protect:([0-9]+) -->/g,function(a,b){return protect[b.toInt()]});return this.cleanup(this.ensureRootElement(html))},setContent:function(content){var protect=this.protectedElements;content=content.replace(protectRegex,function(a){protect.push(a);return"<!-- mooeditable:protect:"+(protect.length-1)+" -->"});this.doc.body.set("html",this.ensureRootElement(content));return this},saveContent:function(){if(this.mode=="iframe"){this.textarea.set("value",this.getContent())}return this},ensureRootElement:function(val){if(this.options.rootElement){var el=new Element("div",{html:val.trim()});var start=-1;var create=false;var html="";var length=el.childNodes.length;for(var i=0;i<length;i++){var childNode=el.childNodes[i];var nodeName=childNode.nodeName;if(!nodeName.test(blockEls)&&nodeName!=="#comment"){if(nodeName==="#text"){if(childNode.nodeValue.trim()){if(start<0){start=i}html+=childNode.nodeValue}}else{if(start<0){start=i}html+=new Element("div").adopt($(childNode).clone()).get("html")}}else{create=true}if(i==(length-1)){create=true}if(start>=0&&create){var newel=new Element(this.options.rootElement,{html:html});el.replaceChild(newel,el.childNodes[start]);for(var k=start+1;k<i;k++){el.removeChild(el.childNodes[k]);length--;i--;k--}start=-1;create=false;html=""}}val=el.get("html").replace(/\n\n/g,"")}return val},checkStates:function(){var element=this.selection.getNode();if(!element){return}if(typeOf(element)!="element"){return}this.actions.each(function(action){var item=this.toolbar.getItem(action);if(!item){return}item.deactivate();var states=MooEditable.Actions[action]["states"];if(!states){return}if(typeOf(states)=="function"){states.attempt([document.id(element),item],this);return}try{if(this.doc.queryCommandState(action)){item.activate();return}}catch(e){}if(states.tags){var el=element;do{var tag=el.tagName.toLowerCase();if(states.tags.contains(tag)){item.activate(tag);break}}while((el=Element.getParent(el))!=null)}if(states.css){var el=element;do{var found=false;for(var prop in states.css){var css=states.css[prop];if(el.style[prop.camelCase()].contains(css)){item.activate(css);found=true}}if(found||el.tagName.test(blockEls)){break}}while((el=Element.getParent(el))!=null)}}.bind(this))},cleanup:function(source){if(!this.options.cleanup){return source.trim()}do{var oSource=source;if(this.options.baseURL){source=source.replace('="'+this.options.baseURL,'="')}source=source.replace(/<br class\="webkit-block-placeholder">/gi,"<br />");source=source.replace(/<span class="Apple-style-span">(.*)<\/span>/gi,"$1");source=source.replace(/ class="Apple-style-span"/gi,"");source=source.replace(/<span style="">/gi,"");source=source.replace(/<p>\s*<br ?\/?>\s*<\/p>/gi,"<p>\u00a0</p>");source=source.replace(/<p>(&nbsp;|\s)*<\/p>/gi,"<p>\u00a0</p>");if(!this.options.semantics){source=source.replace(/\s*<br ?\/?>\s*<\/p>/gi,"</p>")}if(this.options.xhtml){source=source.replace(/<br>/gi,"<br />")}if(this.options.semantics){if(Browser.ie){source=source.replace(/<li>\s*<div>(.+?)<\/div><\/li>/g,"<li>$1</li>")}if(Browser.safari||Browser.chrome){source=source.replace(/^([\w\s]+.*?)<div>/i,"<p>$1</p><div>");source=source.replace(/<div>(.+?)<\/div>/ig,"<p>$1</p>")}if(!Browser.ie){source=source.replace(/<p>[\s\n]*(<(?:ul|ol)>.*?<\/(?:ul|ol)>)(.*?)<\/p>/ig,"$1<p>$2</p>");source=source.replace(/<\/(ol|ul)>\s*(?!<(?:p|ol|ul|img).*?>)((?:<[^>]*>)?\w.*)$/g,"</$1><p>$2</p>")}source=source.replace(/<br[^>]*><\/p>/g,"</p>");source=source.replace(/<p>\s*(<img[^>]+>)\s*<\/p>/ig,"$1\n");source=source.replace(/<p([^>]*)>(.*?)<\/p>(?!\n)/g,"<p$1>$2</p>\n");source=source.replace(/<\/(ul|ol|p)>(?!\n)/g,"</$1>\n");source=source.replace(/><li>/g,">\n\t<li>");source=source.replace(/([^\n])<\/(ol|ul)>/g,"$1\n</$2>");source=source.replace(/([^\n])<img/ig,"$1\n<img");source=source.replace(/^\s*$/g,"")}source=source.replace(/<br ?\/?>$/gi,"");source=source.replace(/^<br ?\/?>/gi,"");if(this.options.paragraphise){source=source.replace(/(h[1-6]|p|div|address|pre|li|ol|ul|blockquote|center|dl|dt|dd)><br ?\/?>/gi,"$1>")}source=source.replace(/<br ?\/?>\s*<\/(h1|h2|h3|h4|h5|h6|li|p)/gi,"</$1");source=source.replace(/<span style="font-weight: bold;">(.*)<\/span>/gi,"<strong>$1</strong>");source=source.replace(/<span style="font-style: italic;">(.*)<\/span>/gi,"<em>$1</em>");source=source.replace(/<b\b[^>]*>(.*?)<\/b[^>]*>/gi,"<strong>$1</strong>");source=source.replace(/<i\b[^>]*>(.*?)<\/i[^>]*>/gi,"<em>$1</em>");source=source.replace(/<u\b[^>]*>(.*?)<\/u[^>]*>/gi,'<span style="text-decoration: underline;">$1</span>');source=source.replace(/<strong><span style="font-weight: normal;">(.*)<\/span><\/strong>/gi,"$1");source=source.replace(/<em><span style="font-weight: normal;">(.*)<\/span><\/em>/gi,"$1");source=source.replace(/<span style="text-decoration: underline;"><span style="font-weight: normal;">(.*)<\/span><\/span>/gi,"$1");source=source.replace(/<strong style="font-weight: normal;">(.*)<\/strong>/gi,"$1");source=source.replace(/<em style="font-weight: normal;">(.*)<\/em>/gi,"$1");source=source.replace(/<[^> ]*/g,function(match){return match.toLowerCase()});source=source.replace(/<[^>]*>/g,function(match){match=match.replace(/ [^=]+=/g,function(match2){return match2.toLowerCase()});return match});source=source.replace(/<[^!][^>]*>/g,function(match){match=match.replace(/( [^=]+=)([^"][^ >]*)/g,'$1"$2"');return match});if(this.options.xhtml){source=source.replace(/<img([^>]+)(\s*[^\/])>(<\/img>)*/gi,"<img$1$2 />")}source=source.replace(/<p>(?:\s*)<p>/g,"<p>");source=source.replace(/<\/p>\s*<\/p>/g,"</p>");source=source.replace(/<pre[^>]*>.*?<\/pre>/gi,function(match){return match.replace(/<br ?\/?>/gi,"\n")});source=source.trim()}while(source!=oSource);return source}});MooEditable.Selection=new Class({initialize:function(win){this.win=win},getSelection:function(){this.win.focus();return(this.win.getSelection)?this.win.getSelection():this.win.document.selection},getRange:function(){var s=this.getSelection();if(!s){return null}try{return s.rangeCount>0?s.getRangeAt(0):(s.createRange?s.createRange():null)}catch(e){return this.doc.body.createTextRange()}},setRange:function(range){if(range.select){Function.attempt(function(){range.select()})}else{var s=this.getSelection();if(s.addRange){s.removeAllRanges();s.addRange(range)}}},selectNode:function(node,collapse){var r=this.getRange();var s=this.getSelection();if(r.moveToElementText){Function.attempt(function(){r.moveToElementText(node);r.select()})}else{if(s.addRange){collapse?r.selectNodeContents(node):r.selectNode(node);s.removeAllRanges();s.addRange(r)}else{s.setBaseAndExtent(node,0,node,1)}}return node},isCollapsed:function(){var r=this.getRange();if(r.item){return false}return r.boundingWidth==0||this.getSelection().isCollapsed},collapse:function(toStart){var r=this.getRange();var s=this.getSelection();if(r.select){r.collapse(toStart);r.select()}else{toStart?s.collapseToStart():s.collapseToEnd()}},getContent:function(){var r=this.getRange();var body=new Element("body");if(this.isCollapsed()){return""}if(r.cloneContents){body.appendChild(r.cloneContents())}else{if(r.item!=undefined||r.htmlText!=undefined){body.set("html",r.item?r.item(0).outerHTML:r.htmlText)}else{body.set("html",r.toString())}}var content=body.get("html");return content},getText:function(){var r=this.getRange();var s=this.getSelection();return this.isCollapsed()?"":r.text||(s.toString?s.toString():"")},getNode:function(){var r=this.getRange();if(!Browser.ie||Browser.version>=9){var el=null;if(r){el=r.commonAncestorContainer;if(!r.collapsed){if(r.startContainer==r.endContainer){if(r.startOffset-r.endOffset<2){if(r.startContainer.hasChildNodes()){el=r.startContainer.childNodes[r.startOffset]}}}}while(typeOf(el)!="element"){el=el.parentNode}}return document.id(el)}return document.id(r.item?r.item(0):r.parentElement())},insertContent:function(content){if(Browser.ie){var r=this.getRange();if(r.pasteHTML){r.pasteHTML(content);r.collapse(false);r.select()}else{if(r.insertNode){r.deleteContents();if(r.createContextualFragment){r.insertNode(r.createContextualFragment(content))}else{var doc=this.win.document;var fragment=doc.createDocumentFragment();var temp=doc.createElement("div");fragment.appendChild(temp);temp.outerHTML=content;r.insertNode(fragment)}}}}else{this.win.document.execCommand("insertHTML",false,content)}}});var phrases={};MooEditable.Locale={define:function(key,value){if(typeOf(window.Locale)!="null"){return Locale.define("en-US","MooEditable",key,value)}if(typeOf(key)=="object"){Object.merge(phrases,key)}else{phrases[key]=value}},get:function(key){if(typeOf(window.Locale)!="null"){return Locale.get("MooEditable."+key)}return key?phrases[key]:""}};MooEditable.Locale.define({ok:"OK",cancel:"Cancel",bold:"Bold",italic:"Italic",underline:"Underline",strikethrough:"Strikethrough",unorderedList:"Unordered List",orderedList:"Ordered List",indent:"Indent",outdent:"Outdent",undo:"Undo",redo:"Redo",removeHyperlink:"Remove Hyperlink",addHyperlink:"Add Hyperlink",selectTextHyperlink:"Please select the text you wish to hyperlink.",enterURL:"Enter URL",enterImageURL:"Enter image URL",addImage:"Add Image",toggleView:"Toggle View"});MooEditable.UI={};MooEditable.UI.Toolbar=new Class({Implements:[Events,Options],options:{"class":""},initialize:function(options){this.setOptions(options);this.el=new Element("div",{"class":"mooeditable-ui-toolbar "+this.options["class"]});this.items={};this.content=null},toElement:function(){return this.el},render:function(actions){if(this.content){this.el.adopt(this.content)}else{this.content=actions.map(function(action){return(action=="|")?this.addSeparator():this.addItem(action)}.bind(this))}return this},addItem:function(action){var self=this;var act=MooEditable.Actions[action];if(!act){return}var type=act.type||"button";var options=act.options||{};var item=new MooEditable.UI[type.camelCase().capitalize()](Object.append(options,{name:action,"class":action+"-item toolbar-item",title:act.title,onAction:self.itemAction.bind(self)}));this.items[action]=item;document.id(item).inject(this.el);return item},getItem:function(action){return this.items[action]},addSeparator:function(){return new Element("span",{"class":"toolbar-separator"}).inject(this.el)},itemAction:function(){this.fireEvent("itemAction",arguments)},disable:function(except){Object.each(this.items,function(item){(item.name==except)?item.activate():item.deactivate().disable()});return this},enable:function(){Object.each(this.items,function(item){item.enable()});return this},show:function(){this.el.setStyle("display","");return this},hide:function(){this.el.setStyle("display","none");return this}});MooEditable.UI.Button=new Class({Implements:[Events,Options],options:{title:"",name:"",text:"Button","class":"",shortcut:"",mode:"icon"},initialize:function(options){this.setOptions(options);this.name=this.options.name;this.render()},toElement:function(){return this.el},render:function(){var self=this;var key=(Browser.Platform.mac)?"Cmd":"Ctrl";var shortcut=(this.options.shortcut)?" ( "+key+"+"+this.options.shortcut.toUpperCase()+" )":"";var text=this.options.title||name;var title=text+shortcut;this.el=new Element("button",{"class":"mooeditable-ui-button "+self.options["class"],title:title,html:'<span class="button-icon"></span><span class="button-text">'+text+"</span>",events:{click:self.click.bind(self),mousedown:function(e){e.preventDefault()}}});if(this.options.mode!="icon"){this.el.addClass("mooeditable-ui-button-"+this.options.mode)}this.active=false;this.disabled=false;if(Browser.ie){this.el.addEvents({mouseenter:function(e){this.addClass("hover")},mouseleave:function(e){this.removeClass("hover")}})}return this},click:function(e){e.preventDefault();if(this.disabled){return}this.action(e)},action:function(){this.fireEvent("action",[this].concat(Array.from(arguments)))},enable:function(){if(this.active){this.el.removeClass("onActive")}if(!this.disabled){return}this.disabled=false;this.el.removeClass("disabled").set({disabled:false,opacity:1});return this},disable:function(){if(this.disabled){return}this.disabled=true;this.el.addClass("disabled").set({disabled:true,opacity:0.4});return this},activate:function(){if(this.disabled){return}this.active=true;this.el.addClass("onActive");return this},deactivate:function(){this.active=false;this.el.removeClass("onActive");return this}});MooEditable.UI.Dialog=new Class({Implements:[Events,Options],options:{"class":"",contentClass:""},initialize:function(html,options){this.setOptions(options);this.html=html;var self=this;this.el=new Element("div",{"class":"mooeditable-ui-dialog "+self.options["class"],html:'<div class="dialog-content '+self.options.contentClass+'">'+html+"</div>",styles:{display:"none"},events:{click:self.click.bind(self)}})},toElement:function(){return this.el},click:function(){this.fireEvent("click",arguments);return this},open:function(){this.el.setStyle("display","");this.fireEvent("open",this);return this},close:function(){this.el.setStyle("display","none");this.fireEvent("close",this);return this}});MooEditable.UI.AlertDialog=function(alertText){if(!alertText){return}var html=alertText+' <button class="dialog-ok-button">'+MooEditable.Locale.get("ok")+"</button>";return new MooEditable.UI.Dialog(html,{"class":"mooeditable-alert-dialog",onOpen:function(){var button=this.el.getElement(".dialog-ok-button");(function(){button.focus()}).delay(10)},onClick:function(e){e.preventDefault();if(e.target.tagName.toLowerCase()!="button"){return}if(document.id(e.target).hasClass("dialog-ok-button")){this.close()}}})};MooEditable.UI.PromptDialog=function(questionText,answerText,fn){if(!questionText){return}var html='<label class="dialog-label">'+questionText+' <input type="text" class="text dialog-input" value="'+answerText+'"></label> <button class="dialog-button dialog-ok-button">'+MooEditable.Locale.get("ok")+'</button><button class="dialog-button dialog-cancel-button">'+MooEditable.Locale.get("cancel")+"</button>";return new MooEditable.UI.Dialog(html,{"class":"mooeditable-prompt-dialog",onOpen:function(){var input=this.el.getElement(".dialog-input");(function(){input.focus();input.select()}).delay(10)},onClick:function(e){e.preventDefault();if(e.target.tagName.toLowerCase()!="button"){return}var button=document.id(e.target);var input=this.el.getElement(".dialog-input");if(button.hasClass("dialog-cancel-button")){input.set("value",answerText);this.close()}else{if(button.hasClass("dialog-ok-button")){var answer=input.get("value");input.set("value",answerText);this.close();if(fn){fn.attempt(answer,this)}}}}})};MooEditable.Actions={bold:{title:MooEditable.Locale.get("bold"),options:{shortcut:"b"},states:{tags:["b","strong"],css:{"font-weight":"bold"}},events:{beforeToggleView:function(){if(Browser.firefox){var value=this.textarea.get("value");var newValue=value.replace(/<strong([^>]*)>/gi,"<b$1>").replace(/<\/strong>/gi,"</b>");if(value!=newValue){this.textarea.set("value",newValue)}}},attach:function(){if(Browser.firefox){var value=this.textarea.get("value");var newValue=value.replace(/<strong([^>]*)>/gi,"<b$1>").replace(/<\/strong>/gi,"</b>");if(value!=newValue){this.textarea.set("value",newValue);this.setContent(newValue)}}}}},italic:{title:MooEditable.Locale.get("italic"),options:{shortcut:"i"},states:{tags:["i","em"],css:{"font-style":"italic"}},events:{beforeToggleView:function(){if(Browser.firefox){var value=this.textarea.get("value");var newValue=value.replace(/<embed([^>]*)>/gi,"<tmpembed$1>").replace(/<em([^>]*)>/gi,"<i$1>").replace(/<tmpembed([^>]*)>/gi,"<embed$1>").replace(/<\/em>/gi,"</i>");if(value!=newValue){this.textarea.set("value",newValue)}}},attach:function(){if(Browser.firefox){var value=this.textarea.get("value");var newValue=value.replace(/<embed([^>]*)>/gi,"<tmpembed$1>").replace(/<em([^>]*)>/gi,"<i$1>").replace(/<tmpembed([^>]*)>/gi,"<embed$1>").replace(/<\/em>/gi,"</i>");if(value!=newValue){this.textarea.set("value",newValue);this.setContent(newValue)}}}}},underline:{title:MooEditable.Locale.get("underline"),options:{shortcut:"u"},states:{tags:["u"],css:{"text-decoration":"underline"}}},strikethrough:{title:MooEditable.Locale.get("strikethrough"),options:{shortcut:"s"},states:{tags:["s","strike"],css:{"text-decoration":"line-through"}}},insertunorderedlist:{title:MooEditable.Locale.get("unorderedList"),states:{tags:["ul"]}},insertorderedlist:{title:MooEditable.Locale.get("orderedList"),states:{tags:["ol"]}},indent:{title:MooEditable.Locale.get("indent"),states:{tags:["blockquote"]}},outdent:{title:MooEditable.Locale.get("outdent")},undo:{title:MooEditable.Locale.get("undo"),options:{shortcut:"z"}},redo:{title:MooEditable.Locale.get("redo"),options:{shortcut:"y"}},unlink:{title:MooEditable.Locale.get("removeHyperlink")},createlink:{title:MooEditable.Locale.get("addHyperlink"),options:{shortcut:"l"},states:{tags:["a"]},dialogs:{alert:MooEditable.UI.AlertDialog.pass(MooEditable.Locale.get("selectTextHyperlink")),prompt:function(editor){return MooEditable.UI.PromptDialog(MooEditable.Locale.get("enterURL"),"http://",function(url){editor.execute("createlink",false,url.trim())})}},command:function(){var selection=this.selection;var dialogs=this.dialogs.createlink;if(selection.isCollapsed()){var node=selection.getNode();if(node.get("tag")=="a"&&node.get("href")){selection.selectNode(node);var prompt=dialogs.prompt;prompt.el.getElement(".dialog-input").set("value",node.get("href"));prompt.open()}else{dialogs.alert.open()}}else{var text=selection.getText();var prompt=dialogs.prompt;if(urlRegex.test(text)){prompt.el.getElement(".dialog-input").set("value",text)}prompt.open()}}},urlimage:{title:MooEditable.Locale.get("addImage"),options:{shortcut:"m"},dialogs:{prompt:function(editor){return MooEditable.UI.PromptDialog(MooEditable.Locale.get("enterImageURL"),"http://",function(url){editor.execute("insertimage",false,url.trim())})}},command:function(){this.dialogs.urlimage.prompt.open()}},toggleview:{title:MooEditable.Locale.get("toggleView"),command:function(){(this.mode=="textarea")?this.toolbar.enable():this.toolbar.disable("toggleview");this.toggleView()}}};MooEditable.Actions.Settings={};Element.Properties.mooeditable={get:function(){return this.retrieve("MooEditable")}};Element.implement({mooEditable:function(options){var mooeditable=this.get("mooeditable");if(!mooeditable){mooeditable=new MooEditable(this,options)}return mooeditable}})})();var DatePicker=new Class({Implements:Options,d:"",today:"",choice:{},bodysize:{},limit:{},attachTo:null,picker:null,slider:null,oldContents:null,newContents:null,input:null,visual:null,options:{pickerClass:"datepicker",days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],dayShort:2,monthShort:3,startDay:1,timePicker:false,timePickerOnly:false,yearPicker:true,yearsPerPage:20,format:"d-m-Y",allowEmpty:false,inputOutputFormat:"U",animationDuration:400,useFadeInOut:!Browser.Engine.trident,startView:"month",positionOffset:{x:0,y:0},minDate:null,maxDate:null,debug:false,toggleElements:null,onShow:$empty,onClose:$empty,onSelect:$empty},initialize:function(attachTo,options){this.attachTo=attachTo;this.setOptions(options).attach();if(this.options.timePickerOnly){this.options.timePicker=true;this.options.startView="time"}this.formatMinMaxDates();document.addEvent("mousedown",this.close.bind(this))},formatMinMaxDates:function(){if(this.options.minDate&&this.options.minDate.format){this.options.minDate=this.unformat(this.options.minDate.date,this.options.minDate.format)}if(this.options.maxDate&&this.options.maxDate.format){this.options.maxDate=this.unformat(this.options.maxDate.date,this.options.maxDate.format);this.options.maxDate.setHours(23);this.options.maxDate.setMinutes(59);this.options.maxDate.setSeconds(59)}},attach:function(){if($chk(this.options.toggleElements)){var togglers=$$(this.options.toggleElements);document.addEvents({keydown:function(e){if(e.key=="tab"){this.close(null,true)}}.bind(this)})}$$(this.attachTo).each(function(item,index){if(item.retrieve("datepicker")){return}if($chk(item.get("value"))){var init_clone_val=this.format(new Date(this.unformat(item.get("value"),this.options.inputOutputFormat)),this.options.format)}else{if(!this.options.allowEmpty){var init_clone_val=this.format(new Date(),this.options.format)}else{var init_clone_val=""}}var display=item.getStyle("display");var clone=item.setStyle("display",this.options.debug?display:"none").store("datepicker",true).clone().store("datepicker",true).removeProperty("name").setStyle("display",display).set("value",init_clone_val).inject(item,"after");if($chk(this.options.toggleElements)){togglers[index].setStyle("cursor","pointer").addEvents({click:function(e){this.onFocus(item,clone)}.bind(this)});clone.addEvents({blur:function(){item.set("value",clone.get("value"))}})}else{clone.addEvents({keydown:function(e){if(this.options.allowEmpty&&(e.key=="delete"||e.key=="backspace")){item.set("value","");e.target.set("value","");this.close(null,true)}else{if(e.key=="tab"){this.close(null,true)}else{e.stop()}}}.bind(this),focus:function(e){this.onFocus(item,clone)}.bind(this)})}}.bind(this))},onFocus:function(original_input,visual_input){var init_visual_date,d=visual_input.getCoordinates();if($chk(original_input.get("value"))){init_visual_date=this.unformat(original_input.get("value"),this.options.inputOutputFormat).valueOf()}else{init_visual_date=new Date();if($chk(this.options.maxDate)&&init_visual_date.valueOf()>this.options.maxDate.valueOf()){init_visual_date=new Date(this.options.maxDate.valueOf())}if($chk(this.options.minDate)&&init_visual_date.valueOf()<this.options.minDate.valueOf()){init_visual_date=new Date(this.options.minDate.valueOf())}}this.show({left:d.left+this.options.positionOffset.x,top:d.top+d.height+this.options.positionOffset.y},init_visual_date);this.input=original_input;this.visual=visual_input;this.options.onShow()},dateToObject:function(d){return{year:d.getFullYear(),month:d.getMonth(),day:d.getDate(),hours:d.getHours(),minutes:d.getMinutes(),seconds:d.getSeconds()}},dateFromObject:function(values){var d=new Date();d.setDate(1);["year","month","day","hours","minutes","seconds"].each(function(type){var v=values[type];if(!$chk(v)){return}switch(type){case"day":d.setDate(v);break;case"month":d.setMonth(v);break;case"year":d.setFullYear(v);break;case"hours":d.setHours(v);break;case"minutes":d.setMinutes(v);break;case"seconds":d.setSeconds(v);break}});return d},show:function(position,timestamp){this.formatMinMaxDates();if($chk(timestamp)){this.d=new Date(timestamp)}else{this.d=new Date()}this.today=new Date();this.choice=this.dateToObject(this.d);this.mode=(this.options.startView=="time"&&!this.options.timePicker)?"month":this.options.startView;this.render();this.picker.setStyles(position)},render:function(fx){if(!$chk(this.picker)){this.constructPicker()}else{var o=this.oldContents;this.oldContents=this.newContents;this.newContents=o;this.newContents.empty()}var startDate=new Date(this.d.getTime());this.limit={right:false,left:false};if(this.mode=="decades"){this.renderDecades()}else{if(this.mode=="year"){this.renderYear()}else{if(this.mode=="time"){this.renderTime();this.limit={right:true,left:true}}else{this.renderMonth()}}}this.picker.getElement(".previous").setStyle("visibility",this.limit.left?"hidden":"visible");this.picker.getElement(".next").setStyle("visibility",this.limit.right?"hidden":"visible");this.picker.getElement(".titleText").setStyle("cursor",this.allowZoomOut()?"pointer":"default");this.d=startDate;if(this.picker.getStyle("opacity")==0){this.picker.tween("opacity",0,1)}if($chk(fx)){this.fx(fx)}},fx:function(fx){if(fx=="right"){this.oldContents.setStyles({left:0,opacity:1});this.newContents.setStyles({left:this.bodysize.x,opacity:1});this.slider.setStyle("left",0).tween("left",0,-this.bodysize.x)}else{if(fx=="left"){this.oldContents.setStyles({left:this.bodysize.x,opacity:1});this.newContents.setStyles({left:0,opacity:1});this.slider.setStyle("left",-this.bodysize.x).tween("left",-this.bodysize.x,0)}else{if(fx=="fade"){this.slider.setStyle("left",0);this.oldContents.setStyle("left",0).set("tween",{duration:this.options.animationDuration/2}).tween("opacity",1,0);this.newContents.setStyles({opacity:0,left:0}).set("tween",{duration:this.options.animationDuration}).tween("opacity",0,1)}}}},constructPicker:function(){this.picker=new Element("div",{"class":this.options.pickerClass}).inject(document.body);if(this.options.useFadeInOut){this.picker.setStyle("opacity",0).set("tween",{duration:this.options.animationDuration})}var h=new Element("div",{"class":"header"}).inject(this.picker);var titlecontainer=new Element("div",{"class":"title"}).inject(h);new Element("div",{"class":"previous"}).addEvent("click",this.previous.bind(this)).set("text","«").inject(h);new Element("div",{"class":"next"}).addEvent("click",this.next.bind(this)).set("text","»").inject(h);new Element("div",{"class":"closeButton"}).addEvent("click",this.close.bindWithEvent(this,true)).set("text","x").inject(h);new Element("span",{"class":"titleText"}).addEvent("click",this.zoomOut.bind(this)).inject(titlecontainer);var b=new Element("div",{"class":"body"}).inject(this.picker);this.bodysize=b.getSize();this.slider=new Element("div",{styles:{position:"absolute",top:0,left:0,width:2*this.bodysize.x,height:this.bodysize.y}}).set("tween",{duration:this.options.animationDuration,transition:Fx.Transitions.Quad.easeInOut}).inject(b);this.oldContents=new Element("div",{styles:{position:"absolute",top:0,left:this.bodysize.x,width:this.bodysize.x,height:this.bodysize.y}}).inject(this.slider);this.newContents=new Element("div",{styles:{position:"absolute",top:0,left:0,width:this.bodysize.x,height:this.bodysize.y}}).inject(this.slider)},renderTime:function(){var container=new Element("div",{"class":"time"}).inject(this.newContents);if(this.options.timePickerOnly){this.picker.getElement(".titleText").set("text","Select a time")}else{this.picker.getElement(".titleText").set("text",this.format(this.d,"j M, Y"))}new Element("input",{type:"text","class":"hour"}).set("value",this.leadZero(this.d.getHours())).addEvents({mousewheel:function(e){var i=e.target,v=i.get("value").toInt();i.focus();if(e.wheel>0){v=(v<23)?v+1:0}else{v=(v>0)?v-1:23}i.set("value",this.leadZero(v));e.stop()}.bind(this)}).set("maxlength",2).inject(container);new Element("input",{type:"text","class":"minutes"}).set("value",this.leadZero(this.d.getMinutes())).addEvents({mousewheel:function(e){var i=e.target,v=i.get("value").toInt();i.focus();if(e.wheel>0){v=(v<59)?v+1:0}else{v=(v>0)?v-1:59}i.set("value",this.leadZero(v));e.stop()}.bind(this)}).set("maxlength",2).inject(container);new Element("div",{"class":"separator"}).set("text",":").inject(container);new Element("input",{type:"submit",value:"OK","class":"ok"}).addEvents({click:function(e){e.stop();this.select($merge(this.dateToObject(this.d),{hours:this.picker.getElement(".hour").get("value").toInt(),minutes:this.picker.getElement(".minutes").get("value").toInt()}))}.bind(this)}).set("maxlength",2).inject(container)},renderMonth:function(){var month=this.d.getMonth();this.picker.getElement(".titleText").set("text",this.options.months[month]+" "+this.d.getFullYear());this.d.setDate(1);while(this.d.getDay()!=this.options.startDay){this.d.setDate(this.d.getDate()-1)}var container=new Element("div",{"class":"days"}).inject(this.newContents);var titles=new Element("div",{"class":"titles"}).inject(container);var d,i,classes,e,weekcontainer;for(d=this.options.startDay;d<(this.options.startDay+7);d++){new Element("div",{"class":"title day day"+(d%7)}).set("text",this.options.days[(d%7)].substring(0,this.options.dayShort)).inject(titles)}var available=false;var t=this.today.toDateString();var currentChoice=this.dateFromObject(this.choice).toDateString();for(i=0;i<42;i++){classes=[];classes.push("day");classes.push("day"+this.d.getDay());if(this.d.toDateString()==t){classes.push("today")}if(this.d.toDateString()==currentChoice){classes.push("selected")}if(this.d.getMonth()!=month){classes.push("otherMonth")}if(i%7==0){weekcontainer=new Element("div",{"class":"week week"+(Math.floor(i/7))}).inject(container)}e=new Element("div",{"class":classes.join(" ")}).set("text",this.d.getDate()).inject(weekcontainer);if(this.limited("date")){e.addClass("unavailable");if(available){this.limit.right=true}else{if(this.d.getMonth()==month){this.limit.left=true}}}else{available=true;e.addEvent("click",function(e,d){if(this.options.timePicker){this.d.setDate(d.day);this.d.setMonth(d.month);this.mode="time";this.render("fade")}else{this.select(d)}}.bindWithEvent(this,{day:this.d.getDate(),month:this.d.getMonth(),year:this.d.getFullYear()}))}this.d.setDate(this.d.getDate()+1)}if(!available){this.limit.right=true}},renderYear:function(){var month=this.today.getMonth();var thisyear=this.d.getFullYear()==this.today.getFullYear();var selectedyear=this.d.getFullYear()==this.choice.year;this.picker.getElement(".titleText").set("text",this.d.getFullYear());this.d.setMonth(0);var i,e;var available=false;var container=new Element("div",{"class":"months"}).inject(this.newContents);for(i=0;i<=11;i++){e=new Element("div",{"class":"month month"+(i+1)+(i==month&&thisyear?" today":"")+(i==this.choice.month&&selectedyear?" selected":"")}).set("text",this.options.monthShort?this.options.months[i].substring(0,this.options.monthShort):this.options.months[i]).inject(container);if(this.limited("month")){e.addClass("unavailable");if(available){this.limit.right=true}else{this.limit.left=true}}else{available=true;e.addEvent("click",function(e,d){this.d.setDate(1);this.d.setMonth(d);this.mode="month";this.render("fade")}.bindWithEvent(this,i))}this.d.setMonth(i)}if(!available){this.limit.right=true}},renderDecades:function(){while(this.d.getFullYear()%this.options.yearsPerPage>0){this.d.setFullYear(this.d.getFullYear()-1)}this.picker.getElement(".titleText").set("text",this.d.getFullYear()+"-"+(this.d.getFullYear()+this.options.yearsPerPage-1));var i,y,e;var available=false;var container=new Element("div",{"class":"years"}).inject(this.newContents);if($chk(this.options.minDate)&&this.d.getFullYear()<=this.options.minDate.getFullYear()){this.limit.left=true}for(i=0;i<this.options.yearsPerPage;i++){y=this.d.getFullYear();e=new Element("div",{"class":"year year"+i+(y==this.today.getFullYear()?" today":"")+(y==this.choice.year?" selected":"")}).set("text",y).inject(container);if(this.limited("year")){e.addClass("unavailable");if(available){this.limit.right=true}else{this.limit.left=true}}else{available=true;e.addEvent("click",function(e,d){this.d.setFullYear(d);this.mode="year";this.render("fade")}.bindWithEvent(this,y))}this.d.setFullYear(this.d.getFullYear()+1)}if(!available){this.limit.right=true}if($chk(this.options.maxDate)&&this.d.getFullYear()>=this.options.maxDate.getFullYear()){this.limit.right=true}},limited:function(type){var cs=$chk(this.options.minDate);var ce=$chk(this.options.maxDate);if(!cs&&!ce){return false}switch(type){case"year":return(cs&&this.d.getFullYear()<this.options.minDate.getFullYear())||(ce&&this.d.getFullYear()>this.options.maxDate.getFullYear());case"month":var ms=(""+this.d.getFullYear()+this.leadZero(this.d.getMonth())).toInt();return cs&&ms<(""+this.options.minDate.getFullYear()+this.leadZero(this.options.minDate.getMonth())).toInt()||ce&&ms>(""+this.options.maxDate.getFullYear()+this.leadZero(this.options.maxDate.getMonth())).toInt();case"date":return(cs&&this.d<this.options.minDate)||(ce&&this.d>this.options.maxDate)}},allowZoomOut:function(){if(this.mode=="time"&&this.options.timePickerOnly){return false}if(this.mode=="decades"){return false}if(this.mode=="year"&&!this.options.yearPicker){return false}return true},zoomOut:function(){if(!this.allowZoomOut()){return}if(this.mode=="year"){this.mode="decades"}else{if(this.mode=="time"){this.mode="month"}else{this.mode="year"}}this.render("fade")},previous:function(){if(this.mode=="decades"){this.d.setFullYear(this.d.getFullYear()-this.options.yearsPerPage)}else{if(this.mode=="year"){this.d.setFullYear(this.d.getFullYear()-1)}else{if(this.mode=="month"){this.d.setMonth(this.d.getMonth()-1)}}}this.render("left")},next:function(){if(this.mode=="decades"){this.d.setFullYear(this.d.getFullYear()+this.options.yearsPerPage)}else{if(this.mode=="year"){this.d.setFullYear(this.d.getFullYear()+1)}else{if(this.mode=="month"){this.d.setMonth(this.d.getMonth()+1)}}}this.render("right")},close:function(e,force){if(!$(this.picker)){return}var clickOutside=($chk(e)&&e.target!=this.picker&&!this.picker.hasChild(e.target)&&e.target!=this.visual);if(force||clickOutside){if(this.options.useFadeInOut){this.picker.set("tween",{duration:this.options.animationDuration/2,onComplete:this.destroy.bind(this)}).tween("opacity",1,0)}else{this.destroy()}}},destroy:function(){this.picker.destroy();this.picker=null;this.options.onClose()},select:function(values){this.choice=$merge(this.choice,values);var d=this.dateFromObject(this.choice);this.input.set("value",this.format(d,this.options.inputOutputFormat));this.visual.set("value",this.format(d,this.options.format));this.options.onSelect(d);this.close(null,true)},leadZero:function(v){return v<10?"0"+v:v},format:function(t,format){var f="";var h=t.getHours();var m=t.getMonth();for(var i=0;i<format.length;i++){switch(format.charAt(i)){case"\\":i++;f+=format.charAt(i);break;case"y":f+=(100+t.getYear()+"").substring(1);break;case"Y":f+=t.getFullYear();break;case"m":f+=this.leadZero(m+1);break;case"n":f+=(m+1);break;case"M":f+=this.options.months[m].substring(0,this.options.monthShort);break;case"F":f+=this.options.months[m];break;case"d":f+=this.leadZero(t.getDate());break;case"j":f+=t.getDate();break;case"D":f+=this.options.days[t.getDay()].substring(0,this.options.dayShort);break;case"l":f+=this.options.days[t.getDay()];break;case"G":f+=h;break;case"H":f+=this.leadZero(h);break;case"g":f+=(h%12?h%12:12);break;case"h":f+=this.leadZero(h%12?h%12:12);break;case"a":f+=(h>11?"pm":"am");break;case"A":f+=(h>11?"PM":"AM");break;case"i":f+=this.leadZero(t.getMinutes());break;case"s":f+=this.leadZero(t.getSeconds());break;case"U":f+=Math.floor(t.valueOf()/1000);break;default:f+=format.charAt(i)}}return f},unformat:function(t,format){var d=new Date();var a={};var c,m;t=t.toString();for(var i=0;i<format.length;i++){c=format.charAt(i);switch(c){case"\\":r=null;i++;break;case"y":r="[0-9]{2}";break;case"Y":r="[0-9]{4}";break;case"m":r="0[1-9]|1[012]";break;case"n":r="[1-9]|1[012]";break;case"M":r="[A-Za-z]{"+this.options.monthShort+"}";break;case"F":r="[A-Za-z]+";break;case"d":r="0[1-9]|[12][0-9]|3[01]";break;case"j":r="[1-9]|[12][0-9]|3[01]";break;case"D":r="[A-Za-z]{"+this.options.dayShort+"}";break;case"l":r="[A-Za-z]+";break;case"G":case"H":case"g":case"h":r="[0-9]{1,2}";break;case"a":r="(am|pm)";break;case"A":r="(AM|PM)";break;case"i":case"s":r="[012345][0-9]";break;case"U":r="-?[0-9]+$";break;default:r=null}if($chk(r)){m=t.match("^"+r);if($chk(m)){a[c]=m[0];t=t.substring(a[c].length)}else{if(this.options.debug){alert("Fatal Error in DatePicker\n\nUnexpected format at: '"+t+"' expected format character '"+c+"' (pattern '"+r+"')")}return d}}else{t=t.substring(1)}}for(c in a){var v=a[c];switch(c){case"y":d.setFullYear(v<30?2000+v.toInt():1900+v.toInt());break;case"Y":d.setFullYear(v);break;case"m":case"n":d.setMonth(v-1);break;case"M":v=this.options.months.filter(function(item,index){return item.substring(0,this.options.monthShort)==v}.bind(this))[0];case"F":d.setMonth(this.options.months.indexOf(v));break;case"d":case"j":d.setDate(v);break;case"G":case"H":d.setHours(v);break;case"g":case"h":if(a.a=="pm"||a.A=="PM"){d.setHours(v==12?0:v.toInt()+12)}else{d.setHours(v)}break;case"i":d.setMinutes(v);break;case"s":d.setSeconds(v);break;case"U":d=new Date(v.toInt()*1000)}}return d}});var MultipleFields=new Class({version:0.1,options:{spliter:";"},initialize:function(_object,_options){if(!_object){return}if(_object.get("data-spliter")){this.options.spliter=_object.get("data-spliter")}this.inputFields=_object;this.inputFields.each(function(elem){var template=elem.clone().erase("name").erase("id").erase("data-spliter").erase("value").addClass("template");elem.set("type","hidden");new Element("span.add_field",{text:"+"}).inject(elem,"after").addEvent("click",function(e){this.addField(elem,template)}.bind(this));elem.get("value").toString().split(this.options.spliter).each(function(data){this.addField(elem,template,data)}.bind(this))}.bind(this))},addField:function(elem,template,data){template.clone().set("value",data).addEvent("change",function(e){var values=[];e.target.getParent(".input").getElements(".template").each(function(template){if(template.value.trim()){values.push(template.value.trim())}});elem.set("value",values.join(this.options.spliter))}.bind(this)).inject(elem.getParent(".input").getElement(".add_field"),"before")}});window.addEvent("domready",function(){var ajaxNote=new Ajaxify();var lang=document.html.get("lang");if(lang==="en"){lang="en-US"}else{lang=lang+"-"+lang.toUpperCase()}Locale.use(lang);var wysiwyg=[];var setupJsForm=function(scope){scope.getElements(".wysiwyg").each(function(elem){wysiwyg.push(elem.mooEditable())});new MultipleFields(scope.getElements(".multiple_fields"));var dateFormat=Locale.get("Date.shortDate").replace(/%/g,"");var timeFormat="H:i";var dateMonths=Locale.get("Date.months");var dateDays=Locale.get("Date.days");new DatePicker(scope.getElements(".picker.datetime, .picker.timestamp"),{allowEmpty:true,inputOutputFormat:"Y-m-d H:i",months:dateMonths,days:dateDays,timePicker:true,format:dateFormat+" "+timeFormat});new DatePicker(scope.getElements(".picker.date"),{allowEmpty:true,inputOutputFormat:"Y-m-d H:i",months:dateMonths,days:dateDays,format:dateFormat});new DatePicker(scope.getElements(".picker.time"),{allowEmpty:true,inputOutputFormat:"Y-m-d H:i",months:dateMonths,days:dateDays,timePickerOnly:true,format:timeFormat})};var quickEdit=new AjaxEdit({holderParent:$("content"),onStartRequest:function(form){ajaxNote.loading()},onFormInjected:function(form){setupJsForm(form);ajaxNote.success()},onSave:function(form){ajaxNote.success()},onBeforeSubmit:function(){ajaxNote.loading();wysiwyg.each(function(elem){elem.saveContent()})}});var platforms=document.body.getElements(".platform");var main_form=document.id("main_form");if(platforms.length){var setupSortables=function(scope){new Sortables(scope.getElements(".sortable"),{handle:".handle",onStart:function(element,clone){element.addClass("dragged")},onComplete:function(element){element.removeClass("dragged");new Request({method:"get",url:this.element.getParent("tbody").get("data-sort-url")}).send({data:{order:this.serialize()}})}})};var updatePlatform=function(href,platform,callback){ajaxNote.loading();new Request.HTML({method:"get",url:href,onSuccess:function(a,b,html){platform.innerHTML=html;if(callback){callback.call()}setupSortables(platform);ajaxNote.success()}}).send()};platforms.addEvents({"click:relay(.pagination a, thead a)":function(e){e.preventDefault();updatePlatform(this.get("href"),this.getParent(".platform"))},"submit:relay(.search)":function(e){ajaxNote.loading();e.preventDefault();var parent=this.getParent(".platform");new Request.HTML({method:"get",url:this.get("action"),onSuccess:function(a,b,html){parent.innerHTML=html;setupSortables(parent);ajaxNote.success()}}).send({data:this})},"click:relay(.quick_edit)":function(e){e.preventDefault();quickEdit.startEdit(this,this.getParent("tr"))},"click:relay(.action a)":function(e){e.target.addClass("clicked")},"ajax:complete:relay(a[data-method=delete][data-remote])":function(e){e.preventDefault();this.getParent("tr").dispose()}});quickEdit.addEvents({successAndChange:function(json){var tr=this.wrapElement;tr.getElements("td").each(function(td){var name=td.get("data-column-name");if(!name){return}var a=td.getElement("a");(a?a:td).innerHTML=json[name]||""})},successAndNext:function(json){var tr=this.wrapElement;var nextTr=tr.getNext("tr");if(nextTr){quickEdit.startEdit(nextTr.getElement("a"),nextTr)}else{var platform=tr.getParent(".platform");var loadMore=platform.getElement(".load_more");if(loadMore){trIndex=tr.getParent("tbody").getElements("tr").indexOf(tr);updatePlatform(loadMore.get("href"),platform,function(){platform.getElements("tbody tr").each(function(newTr,index){if(trIndex===index){nextTr=newTr.getNext("tr");quickEdit.startEdit(nextTr.getElement("a"),nextTr)}})})}else{nextTr=platform.getElements("tbody tr")[0];quickEdit.startEdit(nextTr.getElement("a"),nextTr)}}}});setupSortables(document.body)}else{if(main_form){setupJsForm(main_form);main_form.addEvents({"click:relay(.quick_edit)":function(e){e.preventDefault();quickEdit.startEdit(this)}});quickEdit.addEvents({successAndChange:function(json){this.wrapElement.set("text",json.to_bhf_s||"")},successAndNext:function(json){var a=this.wrapElement;var li=a.getParent("li");if(!li){this.close();return}var holder=li.getNext("li");if(!holder){holder=li.getParent("ul")}quickEdit.startEdit(holder.getElement("a"))}})}}var dbch=document.body.clientHeight;window.onresize=function(e){dbch=document.body.clientHeight};window.onscroll=function(e){var innerForm=quickEdit.holder.getElement("form");if(!innerForm){return}var scroll=document.body.scrollTop-70;if(scroll<10){scroll=10}if(scroll+innerForm.getSize().y>dbch){return}quickEdit.holder.setStyle("padding-top",scroll)};var fm=$("flash_massages");if(fm){fm.addClass("show").removeClass.delay(4000,fm,"show")}new BrowserUpdate({vs:{i:8,f:3,o:10.01,s:2,n:9}})});
@@ -0,0 +1,1330 @@
1
+ //
2
+ // showdown.js -- A javascript port of Markdown.
3
+ //
4
+ // Copyright (c) 2007 John Fraser.
5
+ //
6
+ // Original Markdown Copyright (c) 2004-2005 John Gruber
7
+ // <http://daringfireball.net/projects/markdown/>
8
+ //
9
+ // The full source distribution is at:
10
+ //
11
+ // A A L
12
+ // T C A
13
+ // T K B
14
+ //
15
+ // <http://www.attacklab.net/>
16
+ //
17
+
18
+ //
19
+ // Wherever possible, Showdown is a straight, line-by-line port
20
+ // of the Perl version of Markdown.
21
+ //
22
+ // This is not a normal parser design; it's basically just a
23
+ // series of string substitutions. It's hard to read and
24
+ // maintain this way, but keeping Showdown close to the original
25
+ // design makes it easier to port new features.
26
+ //
27
+ // More importantly, Showdown behaves like markdown.pl in most
28
+ // edge cases. So web applications can do client-side preview
29
+ // in Javascript, and then build identical HTML on the server.
30
+ //
31
+ // This port needs the new RegExp functionality of ECMA 262,
32
+ // 3rd Edition (i.e. Javascript 1.5). Most modern web browsers
33
+ // should do fine. Even with the new regular expression features,
34
+ // We do a lot of work to emulate Perl's regex functionality.
35
+ // The tricky changes in this file mostly have the "attacklab:"
36
+ // label. Major or self-explanatory changes don't.
37
+ //
38
+ // Smart diff tools like Araxis Merge will be able to match up
39
+ // this file with markdown.pl in a useful way. A little tweaking
40
+ // helps: in a copy of markdown.pl, replace "#" with "//" and
41
+ // replace "$text" with "text". Be sure to ignore whitespace
42
+ // and line endings.
43
+ //
44
+
45
+
46
+ //
47
+ // Showdown usage:
48
+ //
49
+ // var text = "Markdown *rocks*.";
50
+ //
51
+ // var converter = new Attacklab.showdown.converter();
52
+ // var html = converter.makeHtml(text);
53
+ //
54
+ // alert(html);
55
+ //
56
+ // Note: move the sample code to the bottom of this
57
+ // file before uncommenting it.
58
+ //
59
+
60
+
61
+ //
62
+ // Attacklab namespace
63
+ //
64
+ var Attacklab = Attacklab || {}
65
+
66
+ //
67
+ // Showdown namespace
68
+ //
69
+ Attacklab.showdown = Attacklab.showdown || {}
70
+
71
+ //
72
+ // converter
73
+ //
74
+ // Wraps all "globals" so that the only thing
75
+ // exposed is makeHtml().
76
+ //
77
+ Attacklab.showdown.converter = function() {
78
+
79
+
80
+ // g_urls and g_titles allow arbitrary user-entered strings as keys. This
81
+ // caused an exception (and hence stopped the rendering) when the user entered
82
+ // e.g. [push] or [__proto__]. Adding a prefix to the actual key prevents this
83
+ // (since no builtin property starts with "s_"). See
84
+ // http://meta.stackoverflow.com/questions/64655/strange-wmd-bug
85
+ // (granted, switching from Array() to Object() alone would have left only __proto__
86
+ // to be a problem)
87
+ var SaveHash = function () {
88
+ this.set = function (key, value) {
89
+ this["s_" + key] = value;
90
+ }
91
+ this.get = function (key) {
92
+ return this["s_" + key];
93
+ }
94
+ }
95
+
96
+ //
97
+ // Globals:
98
+ //
99
+
100
+ // Global hashes, used by various utility routines
101
+ var g_urls;
102
+ var g_titles;
103
+ var g_html_blocks;
104
+
105
+ // Used to track when we're inside an ordered or unordered list
106
+ // (see _ProcessListItems() for details):
107
+ var g_list_level = 0;
108
+
109
+
110
+ this.makeHtml = function(text) {
111
+ //
112
+ // Main function. The order in which other subs are called here is
113
+ // essential. Link and image substitutions need to happen before
114
+ // _EscapeSpecialCharsWithinTagAttributes(), so that any *'s or _'s in the <a>
115
+ // and <img> tags get encoded.
116
+ //
117
+
118
+ // Clear the global hashes. If we don't clear these, you get conflicts
119
+ // from other articles when generating a page which contains more than
120
+ // one article (e.g. an index page that shows the N most recent
121
+ // articles):
122
+ g_urls = new SaveHash();
123
+ g_titles = new SaveHash();
124
+ g_html_blocks = new Array();
125
+
126
+ // attacklab: Replace ~ with ~T
127
+ // This lets us use tilde as an escape char to avoid md5 hashes
128
+ // The choice of character is arbitray; anything that isn't
129
+ // magic in Markdown will work.
130
+ text = text.replace(/~/g,"~T");
131
+
132
+ // attacklab: Replace $ with ~D
133
+ // RegExp interprets $ as a special character
134
+ // when it's in a replacement string
135
+ text = text.replace(/\$/g,"~D");
136
+
137
+ // Standardize line endings
138
+ text = text.replace(/\r\n/g,"\n"); // DOS to Unix
139
+ text = text.replace(/\r/g,"\n"); // Mac to Unix
140
+
141
+ // Make sure text begins and ends with a couple of newlines:
142
+ text = "\n\n" + text + "\n\n";
143
+
144
+ // Convert all tabs to spaces.
145
+ text = _Detab(text);
146
+
147
+ // Strip any lines consisting only of spaces and tabs.
148
+ // This makes subsequent regexen easier to write, because we can
149
+ // match consecutive blank lines with /\n+/ instead of something
150
+ // contorted like /[ \t]*\n+/ .
151
+ text = text.replace(/^[ \t]+$/mg,"");
152
+
153
+ // Turn block-level HTML blocks into hash entries
154
+ text = _HashHTMLBlocks(text);
155
+
156
+ // Strip link definitions, store in hashes.
157
+ text = _StripLinkDefinitions(text);
158
+
159
+ text = _RunBlockGamut(text);
160
+
161
+ text = _UnescapeSpecialChars(text);
162
+
163
+ // attacklab: Restore dollar signs
164
+ text = text.replace(/~D/g,"$$");
165
+
166
+ // attacklab: Restore tildes
167
+ text = text.replace(/~T/g,"~");
168
+
169
+ return text;
170
+ }
171
+
172
+ var _StripLinkDefinitions = function(text) {
173
+ //
174
+ // Strips link definitions from text, stores the URLs and titles in
175
+ // hash references.
176
+ //
177
+
178
+ // Link defs are in the form: ^[id]: url "optional title"
179
+
180
+ /*
181
+ var text = text.replace(/
182
+ ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1
183
+ [ \t]*
184
+ \n? // maybe *one* newline
185
+ [ \t]*
186
+ <?(\S+?)>? // url = $2
187
+ (?=\s|$) // lookahead for whitespace instead of the lookbehind removed below
188
+ [ \t]*
189
+ \n? // maybe one newline
190
+ [ \t]*
191
+ ( // (potential) title = $3
192
+ (\n*) // any lines skipped = $4 attacklab: lookbehind removed
193
+ [ \t]+
194
+ ["(]
195
+ (.+?) // title = $5
196
+ [")]
197
+ [ \t]*
198
+ )? // title is optional
199
+ (?:\n+|$)
200
+ /gm,
201
+ function(){...});
202
+ */
203
+ var text = text.replace(/^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?(?=\s|$)[ \t]*\n?[ \t]*((\n*)["(](.+?)[")][ \t]*)?(?:\n+)/gm,
204
+ function (wholeMatch,m1,m2,m3,m4,m5) {
205
+ m1 = m1.toLowerCase();
206
+ g_urls.set(m1, _EncodeAmpsAndAngles(m2)); // Link IDs are case-insensitive
207
+ if (m4) {
208
+ // Oops, found blank lines, so it's not a title.
209
+ // Put back the parenthetical statement we stole.
210
+ return m3;
211
+ } else if (m5) {
212
+ g_titles.set(m1, m5.replace(/"/g,"&quot;"));
213
+ }
214
+
215
+ // Completely remove the definition from the text
216
+ return "";
217
+ }
218
+ );
219
+
220
+ return text;
221
+ }
222
+
223
+ var _HashHTMLBlocks = function(text) {
224
+
225
+ // Hashify HTML blocks:
226
+ // We only want to do this for block-level HTML tags, such as headers,
227
+ // lists, and tables. That's because we still want to wrap <p>s around
228
+ // "paragraphs" that are wrapped in non-block-level tags, such as anchors,
229
+ // phrase emphasis, and spans. The list of tags we're looking for is
230
+ // hard-coded:
231
+ var block_tags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del"
232
+ var block_tags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math"
233
+
234
+ // First, look for nested blocks, e.g.:
235
+ // <div>
236
+ // <div>
237
+ // tags for inner block must be indented.
238
+ // </div>
239
+ // </div>
240
+ //
241
+ // The outermost tags must start at the left margin for this to match, and
242
+ // the inner nested divs must be indented.
243
+ // We need to do this before the next, more liberal match, because the next
244
+ // match will start at the first `<div>` and stop at the first `</div>`.
245
+
246
+ // attacklab: This regex can be expensive when it fails.
247
+ /*
248
+ var text = text.replace(/
249
+ ( // save in $1
250
+ ^ // start of line (with /m)
251
+ <($block_tags_a) // start tag = $2
252
+ \b // word break
253
+ // attacklab: hack around khtml/pcre bug...
254
+ [^\r]*?\n // any number of lines, minimally matching
255
+ </\2> // the matching end tag
256
+ [ \t]* // trailing spaces/tabs
257
+ (?=\n+) // followed by a newline
258
+ ) // attacklab: there are sentinel newlines at end of document
259
+ /gm,function(){...}};
260
+ */
261
+ text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del)\b[^\r]*?\n<\/\2>[ \t]*(?=\n+))/gm,hashElement);
262
+
263
+ //
264
+ // Now match more liberally, simply from `\n<tag>` to `</tag>\n`
265
+ //
266
+
267
+ /*
268
+ var text = text.replace(/
269
+ ( // save in $1
270
+ ^ // start of line (with /m)
271
+ <($block_tags_b) // start tag = $2
272
+ \b // word break
273
+ // attacklab: hack around khtml/pcre bug...
274
+ [^\r]*? // any number of lines, minimally matching
275
+ .*</\2> // the matching end tag
276
+ [ \t]* // trailing spaces/tabs
277
+ (?=\n+) // followed by a newline
278
+ ) // attacklab: there are sentinel newlines at end of document
279
+ /gm,function(){...}};
280
+ */
281
+ text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math)\b[^\r]*?.*<\/\2>[ \t]*(?=\n+)\n)/gm,hashElement);
282
+
283
+ // Special case just for <hr />. It was easier to make a special case than
284
+ // to make the other regex more complicated.
285
+
286
+ /*
287
+ text = text.replace(/
288
+ \n // Starting after a blank line
289
+ [ ]{0,3}
290
+ ( // save in $1
291
+ (<(hr) // start tag = $2
292
+ \b // word break
293
+ ([^<>])*? //
294
+ \/?>) // the matching end tag
295
+ [ \t]*
296
+ (?=\n{2,}) // followed by a blank line
297
+ )
298
+ /g,hashElement);
299
+ */
300
+ text = text.replace(/\n[ ]{0,3}((<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,hashElement);
301
+
302
+ // Special case for standalone HTML comments:
303
+
304
+ /*
305
+ text = text.replace(/
306
+ \n\n // Starting after a blank line
307
+ [ ]{0,3} // attacklab: g_tab_width - 1
308
+ ( // save in $1
309
+ <!
310
+ (--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--) // see http://www.w3.org/TR/html-markup/syntax.html#comments
311
+ >
312
+ [ \t]*
313
+ (?=\n{2,}) // followed by a blank line
314
+ )
315
+ /g,hashElement);
316
+ */
317
+ text = text.replace(/\n\n[ ]{0,3}(<!(--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--)>[ \t]*(?=\n{2,}))/g, hashElement);
318
+
319
+ // PHP and ASP-style processor instructions (<?...?> and <%...%>)
320
+
321
+ /*
322
+ text = text.replace(/
323
+ (?:
324
+ \n\n // Starting after a blank line
325
+ )
326
+ ( // save in $1
327
+ [ ]{0,3} // attacklab: g_tab_width - 1
328
+ (?:
329
+ <([?%]) // $2
330
+ [^\r]*?
331
+ \2>
332
+ )
333
+ [ \t]*
334
+ (?=\n{2,}) // followed by a blank line
335
+ )
336
+ /g,hashElement);
337
+ */
338
+ text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,hashElement);
339
+
340
+ return text;
341
+ }
342
+
343
+ var hashElement = function(wholeMatch,m1) {
344
+ var blockText = m1;
345
+
346
+ // Undo double lines
347
+ blockText = blockText.replace(/^\n+/,"");
348
+
349
+ // strip trailing blank lines
350
+ blockText = blockText.replace(/\n+$/g,"");
351
+
352
+ // Replace the element text with a marker ("~KxK" where x is its key)
353
+ blockText = "\n\n~K" + (g_html_blocks.push(blockText)-1) + "K\n\n";
354
+
355
+ return blockText;
356
+ };
357
+
358
+ var _RunBlockGamut = function(text, doNotUnhash) {
359
+ //
360
+ // These are all the transformations that form block-level
361
+ // tags like paragraphs, headers, and list items.
362
+ //
363
+ text = _DoHeaders(text);
364
+
365
+ // Do Horizontal Rules:
366
+ var key = hashBlock("<hr />");
367
+ text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm,key);
368
+ text = text.replace(/^[ ]{0,2}([ ]?-[ ]?){3,}[ \t]*$/gm,key);
369
+ text = text.replace(/^[ ]{0,2}([ ]?_[ ]?){3,}[ \t]*$/gm,key);
370
+
371
+ text = _DoLists(text);
372
+ text = _DoCodeBlocks(text);
373
+ text = _DoBlockQuotes(text);
374
+
375
+ // We already ran _HashHTMLBlocks() before, in Markdown(), but that
376
+ // was to escape raw HTML in the original Markdown source. This time,
377
+ // we're escaping the markup we've just created, so that we don't wrap
378
+ // <p> tags around block-level tags.
379
+ text = _HashHTMLBlocks(text);
380
+ text = _FormParagraphs(text, doNotUnhash);
381
+
382
+ return text;
383
+ }
384
+
385
+
386
+ var _RunSpanGamut = function(text) {
387
+ //
388
+ // These are all the transformations that occur *within* block-level
389
+ // tags like paragraphs, headers, and list items.
390
+ //
391
+
392
+ text = _DoCodeSpans(text);
393
+ text = _EscapeSpecialCharsWithinTagAttributes(text);
394
+ text = _EncodeBackslashEscapes(text);
395
+
396
+ // Process anchor and image tags. Images must come first,
397
+ // because ![foo][f] looks like an anchor.
398
+ text = _DoImages(text);
399
+ text = _DoAnchors(text);
400
+
401
+ // Make links out of things like `<http://example.com/>`
402
+ // Must come after _DoAnchors(), because you can use < and >
403
+ // delimiters in inline links like [this](<url>).
404
+ text = _DoAutoLinks(text);
405
+ text = _EncodeAmpsAndAngles(text);
406
+ text = _DoItalicsAndBold(text);
407
+
408
+ // Do hard breaks:
409
+ text = text.replace(/ +\n/g," <br />\n");
410
+
411
+ return text;
412
+ }
413
+
414
+ var _EscapeSpecialCharsWithinTagAttributes = function(text) {
415
+ //
416
+ // Within tags -- meaning between < and > -- encode [\ ` * _] so they
417
+ // don't conflict with their use in Markdown for code, italics and strong.
418
+ //
419
+
420
+ // Build a regex to find HTML tags and comments. See Friedl's
421
+ // "Mastering Regular Expressions", 2nd Ed., pp. 200-201.
422
+
423
+ // SE: changed the comment part of the regex
424
+
425
+ var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--)>)/gi;
426
+
427
+ text = text.replace(regex, function(wholeMatch) {
428
+ var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g,"$1`");
429
+ tag = escapeCharacters(tag,"\\`*_");
430
+ return tag;
431
+ });
432
+
433
+ return text;
434
+ }
435
+
436
+ var _DoAnchors = function(text) {
437
+ //
438
+ // Turn Markdown link shortcuts into XHTML <a> tags.
439
+ //
440
+ //
441
+ // First, handle reference-style links: [link text] [id]
442
+ //
443
+
444
+ /*
445
+ text = text.replace(/
446
+ ( // wrap whole match in $1
447
+ \[
448
+ (
449
+ (?:
450
+ \[[^\]]*\] // allow brackets nested one level
451
+ |
452
+ [^\[] // or anything else
453
+ )*
454
+ )
455
+ \]
456
+
457
+ [ ]? // one optional space
458
+ (?:\n[ ]*)? // one optional newline followed by spaces
459
+
460
+ \[
461
+ (.*?) // id = $3
462
+ \]
463
+ )()()()() // pad remaining backreferences
464
+ /g,_DoAnchors_callback);
465
+ */
466
+ text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeAnchorTag);
467
+
468
+ //
469
+ // Next, inline-style links: [link text](url "optional title")
470
+ //
471
+
472
+ /*
473
+ text = text.replace(/
474
+ ( // wrap whole match in $1
475
+ \[
476
+ (
477
+ (?:
478
+ \[[^\]]*\] // allow brackets nested one level
479
+ |
480
+ [^\[\]] // or anything else
481
+ )*
482
+ )
483
+ \]
484
+ \( // literal paren
485
+ [ \t]*
486
+ () // no id, so leave $3 empty
487
+ <?( // href = $4
488
+ (?:
489
+ \([^)]*\) // allow one level of (correctly nested) parens (think MSDN)
490
+ |
491
+ [^()]
492
+ )*?
493
+ )>?
494
+ [ \t]*
495
+ ( // $5
496
+ (['"]) // quote char = $6
497
+ (.*?) // Title = $7
498
+ \6 // matching quote
499
+ [ \t]* // ignore any spaces/tabs between closing quote and )
500
+ )? // title is optional
501
+ \)
502
+ )
503
+ /g,writeAnchorTag);
504
+ */
505
+
506
+ text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()<?((?:\([^)]*\)|[^()])*?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeAnchorTag);
507
+
508
+ //
509
+ // Last, handle reference-style shortcuts: [link text]
510
+ // These must come last in case you've also got [link test][1]
511
+ // or [link test](/foo)
512
+ //
513
+
514
+ /*
515
+ text = text.replace(/
516
+ ( // wrap whole match in $1
517
+ \[
518
+ ([^\[\]]+) // link text = $2; can't contain '[' or ']'
519
+ \]
520
+ )()()()()() // pad rest of backreferences
521
+ /g, writeAnchorTag);
522
+ */
523
+ text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag);
524
+
525
+ return text;
526
+ }
527
+
528
+ var writeAnchorTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
529
+ if (m7 == undefined) m7 = "";
530
+ var whole_match = m1;
531
+ var link_text = m2;
532
+ var link_id = m3.toLowerCase();
533
+ var url = m4;
534
+ var title = m7;
535
+
536
+ if (url == "") {
537
+ if (link_id == "") {
538
+ // lower-case and turn embedded newlines into spaces
539
+ link_id = link_text.toLowerCase().replace(/ ?\n/g," ");
540
+ }
541
+ url = "#"+link_id;
542
+
543
+ if (g_urls.get(link_id) != undefined) {
544
+ url = g_urls.get(link_id);
545
+ if (g_titles.get(link_id) != undefined) {
546
+ title = g_titles.get(link_id);
547
+ }
548
+ }
549
+ else {
550
+ if (whole_match.search(/\(\s*\)$/m)>-1) {
551
+ // Special case for explicit empty url
552
+ url = "";
553
+ } else {
554
+ return whole_match;
555
+ }
556
+ }
557
+ }
558
+
559
+ url = escapeCharacters(url,"*_");
560
+ var result = "<a href=\"" + url + "\"";
561
+
562
+ if (title != "") {
563
+ title = title.replace(/"/g,"&quot;");
564
+ title = escapeCharacters(title,"*_");
565
+ result += " title=\"" + title + "\"";
566
+ }
567
+
568
+ result += ">" + link_text + "</a>";
569
+
570
+ return result;
571
+ }
572
+
573
+
574
+ var _DoImages = function(text) {
575
+ //
576
+ // Turn Markdown image shortcuts into <img> tags.
577
+ //
578
+
579
+ //
580
+ // First, handle reference-style labeled images: ![alt text][id]
581
+ //
582
+
583
+ /*
584
+ text = text.replace(/
585
+ ( // wrap whole match in $1
586
+ !\[
587
+ (.*?) // alt text = $2
588
+ \]
589
+
590
+ [ ]? // one optional space
591
+ (?:\n[ ]*)? // one optional newline followed by spaces
592
+
593
+ \[
594
+ (.*?) // id = $3
595
+ \]
596
+ )()()()() // pad rest of backreferences
597
+ /g,writeImageTag);
598
+ */
599
+ text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeImageTag);
600
+
601
+ //
602
+ // Next, handle inline images: ![alt text](url "optional title")
603
+ // Don't forget: encode * and _
604
+
605
+ /*
606
+ text = text.replace(/
607
+ ( // wrap whole match in $1
608
+ !\[
609
+ (.*?) // alt text = $2
610
+ \]
611
+ \s? // One optional whitespace character
612
+ \( // literal paren
613
+ [ \t]*
614
+ () // no id, so leave $3 empty
615
+ <?(\S+?)>? // src url = $4
616
+ [ \t]*
617
+ ( // $5
618
+ (['"]) // quote char = $6
619
+ (.*?) // title = $7
620
+ \6 // matching quote
621
+ [ \t]*
622
+ )? // title is optional
623
+ \)
624
+ )
625
+ /g,writeImageTag);
626
+ */
627
+ text = text.replace(/(!\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeImageTag);
628
+
629
+ return text;
630
+ }
631
+
632
+ var writeImageTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
633
+ var whole_match = m1;
634
+ var alt_text = m2;
635
+ var link_id = m3.toLowerCase();
636
+ var url = m4;
637
+ var title = m7;
638
+
639
+ if (!title) title = "";
640
+
641
+ if (url == "") {
642
+ if (link_id == "") {
643
+ // lower-case and turn embedded newlines into spaces
644
+ link_id = alt_text.toLowerCase().replace(/ ?\n/g," ");
645
+ }
646
+ url = "#"+link_id;
647
+
648
+ if (g_urls.get(link_id) != undefined) {
649
+ url = g_urls.get(link_id);
650
+ if (g_titles.get(link_id) != undefined) {
651
+ title = g_titles.get(link_id);
652
+ }
653
+ }
654
+ else {
655
+ return whole_match;
656
+ }
657
+ }
658
+
659
+ alt_text = alt_text.replace(/"/g,"&quot;");
660
+ url = escapeCharacters(url,"*_");
661
+ var result = "<img src=\"" + url + "\" alt=\"" + alt_text + "\"";
662
+
663
+ // attacklab: Markdown.pl adds empty title attributes to images.
664
+ // Replicate this bug.
665
+
666
+ //if (title != "") {
667
+ title = title.replace(/"/g,"&quot;");
668
+ title = escapeCharacters(title,"*_");
669
+ result += " title=\"" + title + "\"";
670
+ //}
671
+
672
+ result += " />";
673
+
674
+ return result;
675
+ }
676
+
677
+
678
+ var _DoHeaders = function(text) {
679
+
680
+ // Setext-style headers:
681
+ // Header 1
682
+ // ========
683
+ //
684
+ // Header 2
685
+ // --------
686
+ //
687
+ text = text.replace(/^(.+)[ \t]*\n=+[ \t]*\n+/gm,
688
+ function(wholeMatch,m1){return "<h1>" + _RunSpanGamut(m1) + "</h1>\n\n";});
689
+
690
+ text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm,
691
+ function(matchFound,m1){return "<h2>" + _RunSpanGamut(m1) + "</h2>\n\n";});
692
+
693
+ // atx-style headers:
694
+ // # Header 1
695
+ // ## Header 2
696
+ // ## Header 2 with closing hashes ##
697
+ // ...
698
+ // ###### Header 6
699
+ //
700
+
701
+ /*
702
+ text = text.replace(/
703
+ ^(\#{1,6}) // $1 = string of #'s
704
+ [ \t]*
705
+ (.+?) // $2 = Header text
706
+ [ \t]*
707
+ \#* // optional closing #'s (not counted)
708
+ \n+
709
+ /gm, function() {...});
710
+ */
711
+
712
+ text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm,
713
+ function(wholeMatch,m1,m2) {
714
+ var h_level = m1.length;
715
+ return "<h" + h_level + ">" + _RunSpanGamut(m2) + "</h" + h_level + ">\n\n";
716
+ });
717
+
718
+ return text;
719
+ }
720
+
721
+ // This declaration keeps Dojo compressor from outputting garbage:
722
+ var _ProcessListItems;
723
+
724
+ var _DoLists = function(text) {
725
+ //
726
+ // Form HTML ordered (numbered) and unordered (bulleted) lists.
727
+ //
728
+
729
+ // attacklab: add sentinel to hack around khtml/safari bug:
730
+ // http://bugs.webkit.org/show_bug.cgi?id=11231
731
+ text += "~0";
732
+
733
+ // Re-usable pattern to match any entirel ul or ol list:
734
+
735
+ /*
736
+ var whole_list = /
737
+ ( // $1 = whole list
738
+ ( // $2
739
+ [ ]{0,3} // attacklab: g_tab_width - 1
740
+ ([*+-]|\d+[.]) // $3 = first list item marker
741
+ [ \t]+
742
+ )
743
+ [^\r]+?
744
+ ( // $4
745
+ ~0 // sentinel for workaround; should be $
746
+ |
747
+ \n{2,}
748
+ (?=\S)
749
+ (?! // Negative lookahead for another list item marker
750
+ [ \t]*
751
+ (?:[*+-]|\d+[.])[ \t]+
752
+ )
753
+ )
754
+ )/g
755
+ */
756
+ var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
757
+
758
+ if (g_list_level) {
759
+ text = text.replace(whole_list,function(wholeMatch,m1,m2) {
760
+ var list = m1;
761
+ var list_type = (m2.search(/[*+-]/g)>-1) ? "ul" : "ol";
762
+
763
+ var result = _ProcessListItems(list, list_type);
764
+
765
+ // Trim any trailing whitespace, to put the closing `</$list_type>`
766
+ // up on the preceding line, to get it past the current stupid
767
+ // HTML block parser. This is a hack to work around the terrible
768
+ // hack that is the HTML block parser.
769
+ result = result.replace(/\s+$/,"");
770
+ result = "<"+list_type+">" + result + "</"+list_type+">\n";
771
+ return result;
772
+ });
773
+ } else {
774
+ whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g;
775
+ text = text.replace(whole_list,function(wholeMatch,m1,m2,m3) {
776
+ var runup = m1;
777
+ var list = m2;
778
+
779
+ var list_type = (m3.search(/[*+-]/g)>-1) ? "ul" : "ol";
780
+ var result = _ProcessListItems(list, list_type);
781
+ result = runup + "<"+list_type+">\n" + result + "</"+list_type+">\n";
782
+ return result;
783
+ });
784
+ }
785
+
786
+ // attacklab: strip sentinel
787
+ text = text.replace(/~0/,"");
788
+
789
+ return text;
790
+ }
791
+
792
+ var _listItemMarkers = { ol: "\\d+[.]", ul: "[*+-]" };
793
+
794
+ _ProcessListItems = function(list_str, list_type) {
795
+ //
796
+ // Process the contents of a single ordered or unordered list, splitting it
797
+ // into individual list items.
798
+ //
799
+ // list_type is either "ul" or "ol".
800
+
801
+ // The $g_list_level global keeps track of when we're inside a list.
802
+ // Each time we enter a list, we increment it; when we leave a list,
803
+ // we decrement. If it's zero, we're not in a list anymore.
804
+ //
805
+ // We do this because when we're not inside a list, we want to treat
806
+ // something like this:
807
+ //
808
+ // I recommend upgrading to version
809
+ // 8. Oops, now this line is treated
810
+ // as a sub-list.
811
+ //
812
+ // As a single paragraph, despite the fact that the second line starts
813
+ // with a digit-period-space sequence.
814
+ //
815
+ // Whereas when we're inside a list (or sub-list), that line will be
816
+ // treated as the start of a sub-list. What a kludge, huh? This is
817
+ // an aspect of Markdown's syntax that's hard to parse perfectly
818
+ // without resorting to mind-reading. Perhaps the solution is to
819
+ // change the syntax rules such that sub-lists must start with a
820
+ // starting cardinal number; e.g. "1." or "a.".
821
+
822
+ g_list_level++;
823
+
824
+ // trim trailing blank lines:
825
+ list_str = list_str.replace(/\n{2,}$/,"\n");
826
+
827
+ // attacklab: add sentinel to emulate \z
828
+ list_str += "~0";
829
+
830
+ // In the original attacklab WMD, list_type was not given to this function, and anything
831
+ // that matched /[*+-]|\d+[.]/ would just create the next <li>, causing this mismatch:
832
+ //
833
+ // Markdown rendered by WMD rendered by MarkdownSharp
834
+ // ------------------------------------------------------------------
835
+ // 1. first 1. first 1. first
836
+ // 2. second 2. second 2. second
837
+ // - third 3. third * third
838
+ //
839
+ // We changed this to behave identical to MarkdownSharp. This is the constructed RegEx,
840
+ // with {MARKER} being one of \d+[.] or [*+-], depending on list_type:
841
+ /*
842
+ list_str = list_str.replace(/
843
+ (^[ \t]*) // leading whitespace = $1
844
+ ({MARKER}) [ \t]+ // list marker = $2
845
+ ([^\r]+? // list item text = $3
846
+ (\n+))
847
+ (?= (~0 | \2 ({MARKER}) [ \t]+))
848
+ /gm, function(){...});
849
+ */
850
+
851
+ var marker = _listItemMarkers[list_type];
852
+ var re = new RegExp("(^[ \\t]*)(" + marker + ")[ \\t]+([^\\r]+?(\\n+))(?=(~0|\\1(" + marker + ")[ \\t]+))", "gm");
853
+ var last_item_had_a_double_newline = false;
854
+ list_str = list_str.replace(re,
855
+ function(wholeMatch,m1,m2,m3){
856
+ var item = m3;
857
+ var leading_space = m1;
858
+ var ends_with_double_newline = /\n\n$/.test(item);
859
+ var contains_double_newline = ends_with_double_newline || item.search(/\n{2,}/)>-1;
860
+
861
+ if (contains_double_newline || last_item_had_a_double_newline) {
862
+ item = _RunBlockGamut(_Outdent(item), /* doNotUnhash = */ true);
863
+ }
864
+ else {
865
+ // Recursion for sub-lists:
866
+ item = _DoLists(_Outdent(item));
867
+ item = item.replace(/\n$/,""); // chomp(item)
868
+ item = _RunSpanGamut(item);
869
+ }
870
+ last_item_had_a_double_newline = ends_with_double_newline;
871
+ return "<li>" + item + "</li>\n";
872
+ }
873
+ );
874
+
875
+ // attacklab: strip sentinel
876
+ list_str = list_str.replace(/~0/g,"");
877
+
878
+ g_list_level--;
879
+ return list_str;
880
+ }
881
+
882
+
883
+ var _DoCodeBlocks = function(text) {
884
+ //
885
+ // Process Markdown `<pre><code>` blocks.
886
+ //
887
+
888
+ /*
889
+ text = text.replace(text,
890
+ /(?:\n\n|^)
891
+ ( // $1 = the code block -- one or more lines, starting with a space/tab
892
+ (?:
893
+ (?:[ ]{4}|\t) // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
894
+ .*\n+
895
+ )+
896
+ )
897
+ (\n*[ ]{0,3}[^ \t\n]|(?=~0)) // attacklab: g_tab_width
898
+ /g,function(){...});
899
+ */
900
+
901
+ // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
902
+ text += "~0";
903
+
904
+ text = text.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g,
905
+ function(wholeMatch,m1,m2) {
906
+ var codeblock = m1;
907
+ var nextChar = m2;
908
+
909
+ codeblock = _EncodeCode( _Outdent(codeblock));
910
+ codeblock = _Detab(codeblock);
911
+ codeblock = codeblock.replace(/^\n+/g,""); // trim leading newlines
912
+ codeblock = codeblock.replace(/\n+$/g,""); // trim trailing whitespace
913
+
914
+ codeblock = "<pre><code>" + codeblock + "\n</code></pre>";
915
+
916
+ return "\n\n" + codeblock + "\n\n" + nextChar;
917
+ }
918
+ );
919
+
920
+ // attacklab: strip sentinel
921
+ text = text.replace(/~0/,"");
922
+
923
+ return text;
924
+ }
925
+
926
+ var hashBlock = function(text) {
927
+ text = text.replace(/(^\n+|\n+$)/g,"");
928
+ return "\n\n~K" + (g_html_blocks.push(text)-1) + "K\n\n";
929
+ }
930
+
931
+
932
+ var _DoCodeSpans = function(text) {
933
+ //
934
+ // * Backtick quotes are used for <code></code> spans.
935
+ //
936
+ // * You can use multiple backticks as the delimiters if you want to
937
+ // include literal backticks in the code span. So, this input:
938
+ //
939
+ // Just type ``foo `bar` baz`` at the prompt.
940
+ //
941
+ // Will translate to:
942
+ //
943
+ // <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
944
+ //
945
+ // There's no arbitrary limit to the number of backticks you
946
+ // can use as delimters. If you need three consecutive backticks
947
+ // in your code, use four for delimiters, etc.
948
+ //
949
+ // * You can use spaces to get literal backticks at the edges:
950
+ //
951
+ // ... type `` `bar` `` ...
952
+ //
953
+ // Turns to:
954
+ //
955
+ // ... type <code>`bar`</code> ...
956
+ //
957
+
958
+ /*
959
+ text = text.replace(/
960
+ (^|[^\\]) // Character before opening ` can't be a backslash
961
+ (`+) // $2 = Opening run of `
962
+ ( // $3 = The code block
963
+ [^\r]*?
964
+ [^`] // attacklab: work around lack of lookbehind
965
+ )
966
+ \2 // Matching closer
967
+ (?!`)
968
+ /gm, function(){...});
969
+ */
970
+
971
+ text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
972
+ function(wholeMatch,m1,m2,m3,m4) {
973
+ var c = m3;
974
+ c = c.replace(/^([ \t]*)/g,""); // leading whitespace
975
+ c = c.replace(/[ \t]*$/g,""); // trailing whitespace
976
+ c = _EncodeCode(c);
977
+ return m1+"<code>"+c+"</code>";
978
+ });
979
+
980
+ return text;
981
+ }
982
+
983
+
984
+ var _EncodeCode = function(text) {
985
+ //
986
+ // Encode/escape certain characters inside Markdown code runs.
987
+ // The point is that in code, these characters are literals,
988
+ // and lose their special Markdown meanings.
989
+ //
990
+ // Encode all ampersands; HTML entities are not
991
+ // entities within a Markdown code span.
992
+ text = text.replace(/&/g,"&amp;");
993
+
994
+ // Do the angle bracket song and dance:
995
+ text = text.replace(/</g,"&lt;");
996
+ text = text.replace(/>/g,"&gt;");
997
+
998
+ // Now, escape characters that are magic in Markdown:
999
+ text = escapeCharacters(text,"\*_{}[]\\",false);
1000
+
1001
+ // jj the line above breaks this:
1002
+ //---
1003
+
1004
+ //* Item
1005
+
1006
+ // 1. Subitem
1007
+
1008
+ // special char: *
1009
+ //---
1010
+
1011
+ return text;
1012
+ }
1013
+
1014
+
1015
+ var _DoItalicsAndBold = function(text) {
1016
+
1017
+ // <strong> must go first:
1018
+ text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[\*_]*)\1/g,
1019
+ "<strong>$2</strong>");
1020
+
1021
+ text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g,
1022
+ "<em>$2</em>");
1023
+
1024
+ return text;
1025
+ }
1026
+
1027
+
1028
+ var _DoBlockQuotes = function(text) {
1029
+
1030
+ /*
1031
+ text = text.replace(/
1032
+ ( // Wrap whole match in $1
1033
+ (
1034
+ ^[ \t]*>[ \t]? // '>' at the start of a line
1035
+ .+\n // rest of the first line
1036
+ (.+\n)* // subsequent consecutive lines
1037
+ \n* // blanks
1038
+ )+
1039
+ )
1040
+ /gm, function(){...});
1041
+ */
1042
+
1043
+ text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm,
1044
+ function(wholeMatch,m1) {
1045
+ var bq = m1;
1046
+
1047
+ // attacklab: hack around Konqueror 3.5.4 bug:
1048
+ // "----------bug".replace(/^-/g,"") == "bug"
1049
+
1050
+ bq = bq.replace(/^[ \t]*>[ \t]?/gm,"~0"); // trim one level of quoting
1051
+
1052
+ // attacklab: clean up hack
1053
+ bq = bq.replace(/~0/g,"");
1054
+
1055
+ bq = bq.replace(/^[ \t]+$/gm,""); // trim whitespace-only lines
1056
+ bq = _RunBlockGamut(bq); // recurse
1057
+
1058
+ bq = bq.replace(/(^|\n)/g,"$1 ");
1059
+ // These leading spaces screw with <pre> content, so we need to fix that:
1060
+ bq = bq.replace(
1061
+ /(\s*<pre>[^\r]+?<\/pre>)/gm,
1062
+ function(wholeMatch,m1) {
1063
+ var pre = m1;
1064
+ // attacklab: hack around Konqueror 3.5.4 bug:
1065
+ pre = pre.replace(/^ /mg,"~0");
1066
+ pre = pre.replace(/~0/g,"");
1067
+ return pre;
1068
+ });
1069
+
1070
+ return hashBlock("<blockquote>\n" + bq + "\n</blockquote>");
1071
+ });
1072
+ return text;
1073
+ }
1074
+
1075
+
1076
+ var _FormParagraphs = function(text, doNotUnhash) {
1077
+ //
1078
+ // Params:
1079
+ // $text - string to process with html <p> tags
1080
+ //
1081
+
1082
+ // Strip leading and trailing lines:
1083
+ text = text.replace(/^\n+/g,"");
1084
+ text = text.replace(/\n+$/g,"");
1085
+
1086
+ var grafs = text.split(/\n{2,}/g);
1087
+ var grafsOut = new Array();
1088
+
1089
+ //
1090
+ // Wrap <p> tags.
1091
+ //
1092
+ var end = grafs.length;
1093
+ for (var i=0; i<end; i++) {
1094
+ var str = grafs[i];
1095
+
1096
+ // if this is an HTML marker, copy it
1097
+ if (str.search(/~K(\d+)K/g) >= 0) {
1098
+ grafsOut.push(str);
1099
+ }
1100
+ else if (str.search(/\S/) >= 0) {
1101
+ str = _RunSpanGamut(str);
1102
+ str = str.replace(/^([ \t]*)/g,"<p>");
1103
+ str += "</p>"
1104
+ grafsOut.push(str);
1105
+ }
1106
+
1107
+ }
1108
+ //
1109
+ // Unhashify HTML blocks
1110
+ //
1111
+ if (!doNotUnhash) {
1112
+ end = grafsOut.length;
1113
+ for (var i=0; i<end; i++) {
1114
+ // if this is a marker for an html block...
1115
+ while (grafsOut[i].search(/~K(\d+)K/) >= 0) {
1116
+ var blockText = g_html_blocks[RegExp.$1];
1117
+ blockText = blockText.replace(/\$/g,"$$$$"); // Escape any dollar signs
1118
+ grafsOut[i] = grafsOut[i].replace(/~K\d+K/,blockText);
1119
+ }
1120
+ }
1121
+ }
1122
+ return grafsOut.join("\n\n");
1123
+ }
1124
+
1125
+
1126
+ var _EncodeAmpsAndAngles = function(text) {
1127
+ // Smart processing for ampersands and angle brackets that need to be encoded.
1128
+
1129
+ // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
1130
+ // http://bumppo.net/projects/amputator/
1131
+ text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g,"&amp;");
1132
+
1133
+ // Encode naked <'s
1134
+ text = text.replace(/<(?![a-z\/?\$!])/gi,"&lt;");
1135
+
1136
+ return text;
1137
+ }
1138
+
1139
+
1140
+ var _EncodeBackslashEscapes = function(text) {
1141
+ //
1142
+ // Parameter: String.
1143
+ // Returns: The string, with after processing the following backslash
1144
+ // escape sequences.
1145
+ //
1146
+
1147
+ // attacklab: The polite way to do this is with the new
1148
+ // escapeCharacters() function:
1149
+ //
1150
+ // text = escapeCharacters(text,"\\",true);
1151
+ // text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
1152
+ //
1153
+ // ...but we're sidestepping its use of the (slow) RegExp constructor
1154
+ // as an optimization for Firefox. This function gets called a LOT.
1155
+
1156
+ text = text.replace(/\\(\\)/g,escapeCharacters_callback);
1157
+ text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g,escapeCharacters_callback);
1158
+ return text;
1159
+ }
1160
+
1161
+
1162
+ var _DoAutoLinks = function(text) {
1163
+
1164
+ text = text.replace(/<((https?|ftp|dict):[^'">\s]+)>/gi,"<a href=\"$1\">$1</a>");
1165
+
1166
+ // Email addresses: <address@domain.foo>
1167
+
1168
+ /*
1169
+ text = text.replace(/
1170
+ <
1171
+ (?:mailto:)?
1172
+ (
1173
+ [-.\w]+
1174
+ \@
1175
+ [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+
1176
+ )
1177
+ >
1178
+ /gi, _DoAutoLinks_callback());
1179
+ */
1180
+ text = text.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,
1181
+ function(wholeMatch,m1) {
1182
+ return _EncodeEmailAddress( _UnescapeSpecialChars(m1) );
1183
+ }
1184
+ );
1185
+
1186
+ return text;
1187
+ }
1188
+
1189
+
1190
+ var _EncodeEmailAddress = function(addr) {
1191
+ //
1192
+ // Input: an email address, e.g. "foo@example.com"
1193
+ //
1194
+ // Output: the email address as a mailto link, with each character
1195
+ // of the address encoded as either a decimal or hex entity, in
1196
+ // the hopes of foiling most address harvesting spam bots. E.g.:
1197
+ //
1198
+ // <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101;
1199
+ // x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111;
1200
+ // &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a>
1201
+ //
1202
+ // Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
1203
+ // mailing list: <http://tinyurl.com/yu7ue>
1204
+ //
1205
+
1206
+ // attacklab: why can't javascript speak hex?
1207
+ function char2hex(ch) {
1208
+ var hexDigits = '0123456789ABCDEF';
1209
+ var dec = ch.charCodeAt(0);
1210
+ return(hexDigits.charAt(dec>>4) + hexDigits.charAt(dec&15));
1211
+ }
1212
+
1213
+ var encode = [
1214
+ function(ch){return "&#"+ch.charCodeAt(0)+";";},
1215
+ function(ch){return "&#x"+char2hex(ch)+";";},
1216
+ function(ch){return ch;}
1217
+ ];
1218
+
1219
+ addr = "mailto:" + addr;
1220
+
1221
+ addr = addr.replace(/./g, function(ch) {
1222
+ if (ch == "@") {
1223
+ // this *must* be encoded. I insist.
1224
+ ch = encode[Math.floor(Math.random()*2)](ch);
1225
+ } else if (ch !=":") {
1226
+ // leave ':' alone (to spot mailto: later)
1227
+ var r = Math.random();
1228
+ // roughly 10% raw, 45% hex, 45% dec
1229
+ ch = (
1230
+ r > .9 ? encode[2](ch) :
1231
+ r > .45 ? encode[1](ch) :
1232
+ encode[0](ch)
1233
+ );
1234
+ }
1235
+ return ch;
1236
+ });
1237
+
1238
+ addr = "<a href=\"" + addr + "\">" + addr + "</a>";
1239
+ addr = addr.replace(/">.+:/g,"\">"); // strip the mailto: from the visible part
1240
+
1241
+ return addr;
1242
+ }
1243
+
1244
+
1245
+ var _UnescapeSpecialChars = function(text) {
1246
+ //
1247
+ // Swap back in all the special characters we've hidden.
1248
+ //
1249
+ text = text.replace(/~E(\d+)E/g,
1250
+ function(wholeMatch,m1) {
1251
+ var charCodeToReplace = parseInt(m1);
1252
+ return String.fromCharCode(charCodeToReplace);
1253
+ }
1254
+ );
1255
+ return text;
1256
+ }
1257
+
1258
+
1259
+ var _Outdent = function(text) {
1260
+ //
1261
+ // Remove one level of line-leading tabs or spaces
1262
+ //
1263
+
1264
+ // attacklab: hack around Konqueror 3.5.4 bug:
1265
+ // "----------bug".replace(/^-/g,"") == "bug"
1266
+
1267
+ text = text.replace(/^(\t|[ ]{1,4})/gm,"~0"); // attacklab: g_tab_width
1268
+
1269
+ // attacklab: clean up hack
1270
+ text = text.replace(/~0/g,"")
1271
+
1272
+ return text;
1273
+ }
1274
+
1275
+ var _Detab = function (text) {
1276
+ if (!/\t/.test(text))
1277
+ return text;
1278
+
1279
+ var spaces = [" ", " ", " ", " "],
1280
+ skew = 0,
1281
+ v;
1282
+
1283
+ return text.replace(/[\n\t]/g, function (match, offset) {
1284
+ if (match === "\n") {
1285
+ skew = offset + 1;
1286
+ return match;
1287
+ }
1288
+ v = (offset - skew) % 4;
1289
+ skew = offset + 1;
1290
+ return spaces[v];
1291
+ });
1292
+ }
1293
+
1294
+ //
1295
+ // attacklab: Utility functions
1296
+ //
1297
+
1298
+
1299
+ var escapeCharacters = function(text, charsToEscape, afterBackslash) {
1300
+ // First we have to escape the escape characters so that
1301
+ // we can build a character class out of them
1302
+ var regexString = "([" + charsToEscape.replace(/([\[\]\\])/g,"\\$1") + "])";
1303
+
1304
+ if (afterBackslash) {
1305
+ regexString = "\\\\" + regexString;
1306
+ }
1307
+
1308
+ var regex = new RegExp(regexString,"g");
1309
+ text = text.replace(regex,escapeCharacters_callback);
1310
+
1311
+ return text;
1312
+ }
1313
+
1314
+
1315
+ var escapeCharacters_callback = function(wholeMatch,m1) {
1316
+ var charCodeToEscape = m1.charCodeAt(0);
1317
+ return "~E"+charCodeToEscape+"E";
1318
+ }
1319
+
1320
+ } // end of Attacklab.showdown.converter
1321
+
1322
+
1323
+ // Version 0.9 used the Showdown namespace instead of Attacklab.showdown
1324
+ // The old namespace is deprecated, but we'll support it for now:
1325
+ var Showdown = Attacklab.showdown;
1326
+
1327
+ // If anyone's interested, tell the world that this file's been loaded
1328
+ if (Attacklab.fileLoaded) {
1329
+ Attacklab.fileLoaded("showdown.js");
1330
+ }