]> git.openstreetmap.org Git - osqa.git/blob - forum/skins/default/media/js/wmd/wmd.js
OSQA-720, changing the WMD markdown editor, applying patches that resolve issues...
[osqa.git] / forum / skins / default / media / js / wmd / wmd.js
1 jQuery.extend({createUploadIframe:function(d,b){var a="jUploadFrame"+d;if(window.ActiveXObject){var c=document.createElement('<iframe id="'+a+'" name="'+a+'" />');if(typeof b=="boolean"){c.src="javascript:false"}else{if(typeof b=="string"){c.src=b}}}else{var c=document.createElement("iframe");c.id=a;c.name=a}c.style.position="absolute";c.style.top="-1000px";c.style.left="-1000px";document.body.appendChild(c);return c},createUploadForm:function(g,b){var e="jUploadForm"+g;var a="jUploadFile"+g;var d=$('<form  action="" method="POST" name="'+e+'" id="'+e+'" enctype="multipart/form-data"></form>');var c=$("#"+b);var f=$(c).clone();$(c).attr("id",a);$(c).before(f);$(c).appendTo(d);$(d).css("position","absolute");$(d).css("top","-1200px");$(d).css("left","-1200px");$(d).appendTo("body");return d},ajaxFileUpload:function(k){k=jQuery.extend({},jQuery.ajaxSettings,k);var a=new Date().getTime();var b=jQuery.createUploadForm(a,k.fileElementId);var i=jQuery.createUploadIframe(a,k.secureuri);var h="jUploadFrame"+a;var j="jUploadForm"+a;if(k.global&&!jQuery.active++){jQuery.event.trigger("ajaxStart")}var c=false;var f={};if(k.global){jQuery.event.trigger("ajaxSend",[f,k])}var d=function(l){var p=document.getElementById(h);try{if(p.contentWindow){f.responseText=p.contentWindow.document.body?p.contentWindow.document.body.innerText:null;f.responseXML=p.contentWindow.document.XMLDocument?p.contentWindow.document.XMLDocument:p.contentWindow.document}else{if(p.contentDocument){f.responseText=p.contentDocument.document.body?p.contentDocument.document.body.textContent||document.body.innerText:null;f.responseXML=p.contentDocument.document.XMLDocument?p.contentDocument.document.XMLDocument:p.contentDocument.document}}}catch(o){jQuery.handleError(k,f,null,o)}if(f||l=="timeout"){c=true;var m;try{m=l!="timeout"?"success":"error";if(m!="error"){var n=jQuery.uploadHttpData(f,k.dataType);if(k.success){k.success(n,m)}if(k.global){jQuery.event.trigger("ajaxSuccess",[f,k])}}else{jQuery.handleError(k,f,m)}}catch(o){m="error";jQuery.handleError(k,f,m,o)}if(k.global){jQuery.event.trigger("ajaxComplete",[f,k])}if(k.global&&!--jQuery.active){jQuery.event.trigger("ajaxStop")}if(k.complete){k.complete(f,m)}jQuery(p).unbind();setTimeout(function(){try{$(p).remove();$(b).remove()}catch(q){jQuery.handleError(k,f,null,q)}},100);f=null}};if(k.timeout>0){setTimeout(function(){if(!c){d("timeout")}},k.timeout)}try{var b=$("#"+j);$(b).attr("action",k.url);$(b).attr("method","POST");$(b).attr("target",h);if(b.encoding){b.encoding="multipart/form-data"}else{b.enctype="multipart/form-data"}$(b).submit()}catch(g){jQuery.handleError(k,f,null,g)}if(window.attachEvent){document.getElementById(h).attachEvent("onload",d)}else{document.getElementById(h).addEventListener("load",d,false)}return{abort:function(){}}},uploadHttpData:function(r,type){var data=!type;data=type=="xml"||data?r.responseXML:r.responseText;if(type=="script"){jQuery.globalEval(data)}if(type=="json"){eval("data = "+data)}if(type=="html"){jQuery("<div>").html(data).evalScripts()}return data}});
2 /*Upload call*/
3 function ajaxFileUpload(imageUrl)
4 {
5   $("#loading").ajaxStart(function(){
6       $(this).show();
7   }).ajaxComplete(function(){
8       $(this).hide();
9   });
10
11   $("#upload").ajaxStart(function(){
12           $(this).hide();
13       }).ajaxComplete(function(){
14           $(this).show();
15       });
16
17       $.ajaxFileUpload
18       (
19         {
20             url: scriptUrl+'upload/',
21               secureuri:false,
22               fileElementId:'file-upload',
23               dataType: 'xml',
24               success: function (data, status)
25               {
26                   var fileURL = $(data).find('file_url').text();
27                   var error = $(data).find('error').text();
28                   if(error != ''){
29                     alert(error);
30                   }else{
31                     imageUrl.attr('value', fileURL);
32                   }
33
34               },
35               error: function (data, status, e)
36               {
37                   alert(e);
38               }
39           }
40       );
41
42     return false;
43 }
44
45 var Attacklab = Attacklab || {};
46
47 Attacklab.wmdBase = function(){
48
49         // A few handy aliases for readability.
50         var wmd  = top.Attacklab;
51         var doc  = top.document;
52         var re   = top.RegExp;
53         var nav  = top.navigator;
54         
55         // Some namespaces.
56         wmd.Util = {};
57         wmd.Position = {};
58         wmd.Command = {};
59         wmd.Global = {};
60         
61         var util = wmd.Util;
62         var position = wmd.Position;
63         var command = wmd.Command;
64         var global = wmd.Global;
65         
66         
67         // Used to work around some browser bugs where we can't use feature testing.
68         global.isIE             = /msie/.test(nav.userAgent.toLowerCase());
69         global.isIE_5or6        = /msie 6/.test(nav.userAgent.toLowerCase()) || /msie 5/.test(nav.userAgent.toLowerCase());
70         global.isIE_7plus       = global.isIE && !global.isIE_5or6;
71         global.isOpera          = /opera/.test(nav.userAgent.toLowerCase());
72         global.isKonqueror      = /konqueror/.test(nav.userAgent.toLowerCase());
73         
74         
75         // -------------------------------------------------------------------
76         //  YOUR CHANGES GO HERE
77         //
78         // I've tried to localize the things you are likely to change to 
79         // this area.
80         // -------------------------------------------------------------------
81         
82         // The text that appears on the upper part of the dialog box when
83         // entering links.
84     var imageDialogText = "<p style='margin-top: 0px'>" + $.i18n._('enter image url') + "</p>";
85     var linkDialogText = "<p style='margin-top: 0px'>" + $.i18n._('enter url') + "</p>";
86     var uploadImageHTML ="<div>" + $.i18n._('upload image') + "</div>" +
87             "<input type=\"file\" name=\"file-upload\" id=\"file-upload\" size=\"26\" "+
88             "onchange=\"return ajaxFileUpload($('#image-url'));\"/><br>" +
89             "<img id=\"loading\" src=\"" + mediaUrl("media/images/indicator.gif") + "\" style=\"display:none;\"/>";
90
91         // The default text that appears in the dialog input box when entering
92         // links.
93         var imageDefaultText = "http://";
94         var linkDefaultText = "http://";
95         
96         // The location of your button images relative to the base directory.
97         var imageDirectory = "images/";
98         
99         // Some intervals in ms.  These can be adjusted to reduce the control's load.
100         var previewPollInterval = 500;
101         var pastePollInterval = 100;
102         
103         // The link and title for the help button
104         var helpLink = "http://wmd-editor.com/";
105         var helpHoverTitle = "WMD website";
106         var helpTarget = "_blank";
107         
108         // -------------------------------------------------------------------
109         //  END OF YOUR CHANGES
110         // -------------------------------------------------------------------
111         
112         // A collection of the important regions on the page.
113         // Cached so we don't have to keep traversing the DOM.
114         wmd.PanelCollection = function(){
115                 this.buttonBar = doc.getElementById("wmd-button-bar");
116                 this.preview = doc.getElementById("previewer");
117                 this.output = doc.getElementById("wmd-output");
118                 this.input = doc.getElementById("editor");
119         };
120         
121         // This PanelCollection object can't be filled until after the page
122         // has loaded.
123         wmd.panels = undefined;
124         
125         // Internet explorer has problems with CSS sprite buttons that use HTML
126         // lists.  When you click on the background image "button", IE will 
127         // select the non-existent link text and discard the selection in the
128         // textarea.  The solution to this is to cache the textarea selection
129         // on the button's mousedown event and set a flag.  In the part of the
130         // code where we need to grab the selection, we check for the flag
131         // and, if it's set, use the cached area instead of querying the
132         // textarea.
133         //
134         // This ONLY affects Internet Explorer (tested on versions 6, 7
135         // and 8) and ONLY on button clicks.  Keyboard shortcuts work
136         // normally since the focus never leaves the textarea.
137         wmd.ieCachedRange = null;               // cached textarea selection
138         wmd.ieRetardedClick = false;    // flag
139         
140         // Returns true if the DOM element is visible, false if it's hidden.
141         // Checks if display is anything other than none.
142         util.isVisible = function (elem) {
143         
144             if (window.getComputedStyle) {
145                 // Most browsers
146                         return window.getComputedStyle(elem, null).getPropertyValue("display") !== "none";
147                 }
148                 else if (elem.currentStyle) {
149                     // IE
150                         return elem.currentStyle["display"] !== "none";
151                 }
152         };
153         
154         
155         // Adds a listener callback to a DOM element which is fired on a specified
156         // event.
157         util.addEvent = function(elem, event, listener){
158                 if (elem.attachEvent) {
159                         // IE only.  The "on" is mandatory.
160                         elem.attachEvent("on" + event, listener);
161                 }
162                 else {
163                         // Other browsers.
164                         elem.addEventListener(event, listener, false);
165                 }
166         };
167
168         
169         // Removes a listener callback from a DOM element which is fired on a specified
170         // event.
171         util.removeEvent = function(elem, event, listener){
172                 if (elem.detachEvent) {
173                         // IE only.  The "on" is mandatory.
174                         elem.detachEvent("on" + event, listener);
175                 }
176                 else {
177                         // Other browsers.
178                         elem.removeEventListener(event, listener, false);
179                 }
180         };
181
182         // Converts \r\n and \r to \n.
183         util.fixEolChars = function(text){
184                 text = text.replace(/\r\n/g, "\n");
185                 text = text.replace(/\r/g, "\n");
186                 return text;
187         };
188
189         // Extends a regular expression.  Returns a new RegExp
190         // using pre + regex + post as the expression.
191         // Used in a few functions where we have a base
192         // expression and we want to pre- or append some
193         // conditions to it (e.g. adding "$" to the end).
194         // The flags are unchanged.
195         //
196         // regex is a RegExp, pre and post are strings.
197         util.extendRegExp = function(regex, pre, post){
198                 
199                 if (pre === null || pre === undefined)
200                 {
201                         pre = "";
202                 }
203                 if(post === null || post === undefined)
204                 {
205                         post = "";
206                 }
207                 
208                 var pattern = regex.toString();
209                 var flags = "";
210                 
211                 // Replace the flags with empty space and store them.
212                 // Technically, this can match incorrect flags like "gmm".
213                 var result = pattern.match(/\/([gim]*)$/);
214                 if (result === null) {
215                         flags = result[0];
216                 }
217                 else {
218                         flags = "";
219                 }
220                 
221                 // Remove the flags and slash delimiters from the regular expression.
222                 pattern = pattern.replace(/(^\/|\/[gim]*$)/g, "");
223                 pattern = pre + pattern + post;
224                 
225                 return new RegExp(pattern, flags);
226         }
227
228         
229         // Sets the image for a button passed to the WMD editor.
230         // Returns a new element with the image attached.
231         // Adds several style properties to the image.
232         util.createImage = function(img){
233                 
234                 var imgPath = imageDirectory + img;
235                 
236                 var elem = doc.createElement("img");
237                 elem.className = "wmd-button";
238                 elem.src = imgPath;
239
240                 return elem;
241         };
242         
243
244         // This simulates a modal dialog box and asks for the URL when you
245         // click the hyperlink or image buttons.
246         //
247         // text: The html for the input box.
248         // defaultInputText: The default value that appears in the input box.
249         // makeLinkMarkdown: The function which is executed when the prompt is dismissed, either via OK or Cancel
250         util.prompt = function(text, defaultInputText, makeLinkMarkdown){
251         
252                 // These variables need to be declared at this level since they are used
253                 // in multiple functions.
254                 var dialog;                     // The dialog box.
255                 var background;         // The background beind the dialog box.
256                 var input;                      // The text box where you enter the hyperlink.
257         var type = 0;
258         // The dialog box type(0: Link, 1: Image)
259         if(arguments.length == 4){
260             type = arguments[3];
261         }
262
263                 if (defaultInputText === undefined) {
264                         defaultInputText = "";
265                 }
266                 
267                 // Used as a keydown event handler. Esc dismisses the prompt.
268                 // Key code 27 is ESC.
269                 var checkEscape = function(key){
270                         var code = (key.charCode || key.keyCode);
271                         if (code === 27) {
272                                 close(true);
273                         }
274                 };
275                 
276                 // Dismisses the hyperlink input box.
277                 // isCancel is true if we don't care about the input text.
278                 // isCancel is false if we are going to keep the text.
279                 var close = function(isCancel){
280                         util.removeEvent(doc.body, "keydown", checkEscape);
281                         var text = input.value;
282
283                         if (isCancel){
284                                 text = null;
285                         }
286                         else{
287                                 // Fixes common pasting errors.
288                                 text = text.replace('http://http://', 'http://');
289                                 text = text.replace('http://https://', 'https://');
290                                 text = text.replace('http://ftp://', 'ftp://');
291                                 
292                                 if (text.indexOf('http://') === -1 && text.indexOf('ftp://') === -1 && text.indexOf('https://') === -1) {
293                                         text = 'http://' + text;
294                                 }
295                         }
296                         
297                         dialog.parentNode.removeChild(dialog);
298                         background.parentNode.removeChild(background);
299                         makeLinkMarkdown(text);
300                         return false;
301                 };
302                 
303                 // Creates the background behind the hyperlink text entry box.
304                 // Most of this has been moved to CSS but the div creation and
305                 // browser-specific hacks remain here.
306                 var createBackground = function(){
307                 
308                         background = doc.createElement("div");
309                         background.className = "wmd-prompt-background";
310                         style = background.style;
311                         style.position = "absolute";
312                         style.top = "0";
313                         
314                         style.zIndex = "1000";
315                         
316                         // Some versions of Konqueror don't support transparent colors
317                         // so we make the whole window transparent.
318                         //
319                         // Is this necessary on modern konqueror browsers?
320                         if (global.isKonqueror){
321                                 style.backgroundColor = "transparent";
322                         }
323                         else if (global.isIE){
324                                 style.filter = "alpha(opacity=50)";
325                         }
326                         else {
327                                 style.opacity = "0.5";
328                         }
329                         
330                         var pageSize = position.getPageSize();
331                         style.height = pageSize[1] + "px";
332                         
333                         if(global.isIE){
334                                 style.left = doc.documentElement.scrollLeft;
335                                 style.width = doc.documentElement.clientWidth;
336                         }
337                         else {
338                                 style.left = "0";
339                                 style.width = "100%";
340                         }
341                         
342                         doc.body.appendChild(background);
343                 };
344                 
345                 // Create the text input box form/window.
346                 var createDialog = function(){
347                 
348                         // The main dialog box.
349                         dialog = doc.createElement("div");
350                         dialog.className = "wmd-prompt-dialog";
351                         dialog.style.padding = "10px;";
352                         dialog.style.position = "fixed";
353                         dialog.style.width = "400px";
354                         dialog.style.zIndex = "1001";
355                         
356                         // The dialog text.
357                         var question = doc.createElement("div");
358                         question.innerHTML = text;
359                         question.style.padding = "5px";
360                         dialog.appendChild(question);
361                         
362                         // The web form container for the text box and buttons.
363                         var form = doc.createElement("form");
364                         form.onsubmit = function(){ return close(false); };
365                         style = form.style;
366                         style.padding = "0";
367                         style.margin = "0";
368                         style.cssFloat = "left";
369                         style.width = "100%";
370                         style.textAlign = "center";
371                         style.position = "relative";
372                         dialog.appendChild(form);
373                         
374                         // The input text box
375                         input = doc.createElement("input");
376                         input.type = "text";
377                         input.value = defaultInputText;
378                         style = input.style;
379                         style.display = "block";
380                         style.width = "80%";
381                         style.marginLeft = style.marginRight = "auto";
382                         form.appendChild(input);
383
384             // The upload file input
385             var upload = doc.createElement("div");
386             upload.innerHTML = uploadImageHTML;
387             upload.style.padding = "5px";
388             form.appendChild(upload);
389                         
390                         // The ok button
391                         var okButton = doc.createElement("input");
392                         okButton.type = "button";
393                         okButton.onclick = function(){ return close(false); };
394                         okButton.value = "OK";
395                         style = okButton.style;
396                         style.margin = "10px";
397                         style.display = "inline";
398                         style.width = "7em";
399
400                         
401                         // The cancel button
402                         var cancelButton = doc.createElement("input");
403                         cancelButton.type = "button";
404                         cancelButton.onclick = function(){ return close(true); };
405                         cancelButton.value = "Cancel";
406                         style = cancelButton.style;
407                         style.margin = "10px";
408                         style.display = "inline";
409                         style.width = "7em";
410
411                         // The order of these buttons is different on macs.
412                         if (/mac/.test(nav.platform.toLowerCase())) {
413                                 form.appendChild(cancelButton);
414                                 form.appendChild(okButton);
415                         }
416                         else {
417                                 form.appendChild(okButton);
418                                 form.appendChild(cancelButton);
419                         }
420
421                         util.addEvent(doc.body, "keydown", checkEscape);
422                         dialog.style.top = "50%";
423                         dialog.style.left = "50%";
424                         dialog.style.display = "block";
425                         if(global.isIE_5or6){
426                                 dialog.style.position = "absolute";
427                                 dialog.style.top = doc.documentElement.scrollTop + 200 + "px";
428                                 dialog.style.left = "50%";
429                         }
430                         doc.body.appendChild(dialog);
431                         
432                         // This has to be done AFTER adding the dialog to the form if you
433                         // want it to be centered.
434                         dialog.style.marginTop = -(position.getHeight(dialog) / 2) + "px";
435                         dialog.style.marginLeft = -(position.getWidth(dialog) / 2) + "px";
436                         
437                 };
438                 
439                 createBackground();
440                 
441                 // Why is this in a zero-length timeout?
442                 // Is it working around a browser bug?
443                 top.setTimeout(function(){
444                 
445                         createDialog();
446
447                         var defTextLen = defaultInputText.length;
448                         if (input.selectionStart !== undefined) {
449                                 input.selectionStart = 0;
450                                 input.selectionEnd = defTextLen;
451                         }
452                         else if (input.createTextRange) {
453                                 var range = input.createTextRange();
454                                 range.collapse(false);
455                                 range.moveStart("character", -defTextLen);
456                                 range.moveEnd("character", defTextLen);
457                                 range.select();
458                         }
459                         
460                         input.focus();
461                 }, 0);
462         };
463         
464         
465         // UNFINISHED
466         // The assignment in the while loop makes jslint cranky.
467         // I'll change it to a better loop later.
468         position.getTop = function(elem, isInner){
469                 var result = elem.offsetTop;
470                 if (!isInner) {
471                         while (elem = elem.offsetParent) {
472                                 result += elem.offsetTop;
473                         }
474                 }
475                 return result;
476         };
477         
478         position.getHeight = function (elem) {
479                 return elem.offsetHeight || elem.scrollHeight;
480         };
481
482         position.getWidth = function (elem) {
483                 return elem.offsetWidth || elem.scrollWidth;
484         };
485
486         position.getPageSize = function(){
487                 
488                 var scrollWidth, scrollHeight;
489                 var innerWidth, innerHeight;
490                 
491                 // It's not very clear which blocks work with which browsers.
492                 if(self.innerHeight && self.scrollMaxY){
493                         scrollWidth = doc.body.scrollWidth;
494                         scrollHeight = self.innerHeight + self.scrollMaxY;
495                 }
496                 else if(doc.body.scrollHeight > doc.body.offsetHeight){
497                         scrollWidth = doc.body.scrollWidth;
498                         scrollHeight = doc.body.scrollHeight;
499                 }
500                 else{
501                         scrollWidth = doc.body.offsetWidth;
502                         scrollHeight = doc.body.offsetHeight;
503                 }
504                 
505                 if(self.innerHeight){
506                         // Non-IE browser
507                         innerWidth = self.innerWidth;
508                         innerHeight = self.innerHeight;
509                 }
510                 else if(doc.documentElement && doc.documentElement.clientHeight){
511                         // Some versions of IE (IE 6 w/ a DOCTYPE declaration)
512                         innerWidth = doc.documentElement.clientWidth;
513                         innerHeight = doc.documentElement.clientHeight;
514                 }
515                 else if(doc.body){
516                         // Other versions of IE
517                         innerWidth = doc.body.clientWidth;
518                         innerHeight = doc.body.clientHeight;
519                 }
520                 
521         var maxWidth = Math.max(scrollWidth, innerWidth);
522         var maxHeight = Math.max(scrollHeight, innerHeight);
523         return [maxWidth, maxHeight, innerWidth, innerHeight];
524         };
525         
526         // Watches the input textarea, polling at an interval and runs
527         // a callback function if anything has changed.
528         wmd.inputPoller = function(callback, interval){
529         
530                 var pollerObj = this;
531                 var inputArea = wmd.panels.input;
532                 
533                 // Stored start, end and text.  Used to see if there are changes to the input.
534                 var lastStart;
535                 var lastEnd;
536                 var markdown;
537                 
538                 var killHandle; // Used to cancel monitoring on destruction.
539                 // Checks to see if anything has changed in the textarea.
540                 // If so, it runs the callback.
541                 this.tick = function(){
542                 
543                         if (!util.isVisible(inputArea)) {
544                                 return;
545                         }
546                         
547                         // Update the selection start and end, text.
548                         if (inputArea.selectionStart || inputArea.selectionStart === 0) {
549                                 var start = inputArea.selectionStart;
550                                 var end = inputArea.selectionEnd;
551                                 if (start != lastStart || end != lastEnd) {
552                                         lastStart = start;
553                                         lastEnd = end;
554                                         
555                                         if (markdown != inputArea.value) {
556                                                 markdown = inputArea.value;
557                                                 return true;
558                                         }
559                                 }
560                         }
561                         return false;
562                 };
563                 
564                 
565                 var doTickCallback = function(){
566                 
567                         if (!util.isVisible(inputArea)) {
568                                 return;
569                         }
570                         
571                         // If anything has changed, call the function.
572                         if (pollerObj.tick()) {
573                                 callback();
574                         }
575                 };
576                 
577                 // Set how often we poll the textarea for changes.
578                 var assignInterval = function(){
579                         // previewPollInterval is set at the top of the namespace.
580                         killHandle = top.setInterval(doTickCallback, interval);
581                 };
582                 
583                 this.destroy = function(){
584                         top.clearInterval(killHandle);
585                 };
586                 
587                 assignInterval();
588         };
589         
590         // Handles pushing and popping TextareaStates for undo/redo commands.
591         // I should rename the stack variables to list.
592         wmd.undoManager = function(callback){
593         
594                 var undoObj = this;
595                 var undoStack = []; // A stack of undo states
596                 var stackPtr = 0; // The index of the current state
597                 var mode = "none";
598                 var lastState; // The last state
599                 var poller;
600                 var timer; // The setTimeout handle for cancelling the timer
601                 var inputStateObj;
602                 
603                 // Set the mode for later logic steps.
604                 var setMode = function(newMode, noSave){
605                 
606                         if (mode != newMode) {
607                                 mode = newMode;
608                                 if (!noSave) {
609                                         saveState();
610                                 }
611                         }
612                         
613                         if (!global.isIE || mode != "moving") {
614                                 timer = top.setTimeout(refreshState, 1);
615                         }
616                         else {
617                                 inputStateObj = null;
618                         }
619                 };
620                 
621                 var refreshState = function(){
622                         inputStateObj = new wmd.TextareaState();
623                         poller.tick();
624                         timer = undefined;
625                 };
626                 
627                 this.setCommandMode = function(){
628                         mode = "command";
629                         saveState();
630                         timer = top.setTimeout(refreshState, 0);
631                 };
632                 
633                 this.canUndo = function(){
634                         return stackPtr > 1;
635                 };
636                 
637                 this.canRedo = function(){
638                         if (undoStack[stackPtr + 1]) {
639                                 return true;
640                         }
641                         return false;
642                 };
643                 
644                 // Removes the last state and restores it.
645                 this.undo = function(){
646                 
647                         if (undoObj.canUndo()) {
648                                 if (lastState) {
649                                         // What about setting state -1 to null or checking for undefined?
650                                         lastState.restore();
651                                         lastState = null;
652                                 }
653                                 else {
654                                         undoStack[stackPtr] = new wmd.TextareaState();
655                                         undoStack[--stackPtr].restore();
656                                         
657                                         if (callback) {
658                                                 callback();
659                                         }
660                                 }
661                         }
662                         
663                         mode = "none";
664                         wmd.panels.input.focus();
665                         refreshState();
666                 };
667                 
668                 // Redo an action.
669                 this.redo = function(){
670                 
671                         if (undoObj.canRedo()) {
672                         
673                                 undoStack[++stackPtr].restore();
674                                 
675                                 if (callback) {
676                                         callback();
677                                 }
678                         }
679                         
680                         mode = "none";
681                         wmd.panels.input.focus();
682                         refreshState();
683                 };
684                 
685                 // Push the input area state to the stack.
686                 var saveState = function(){
687                 
688                         var currState = inputStateObj || new wmd.TextareaState();
689                         
690                         if (!currState) {
691                                 return false;
692                         }
693                         if (mode == "moving") {
694                                 if (!lastState) {
695                                         lastState = currState;
696                                 }
697                                 return;
698                         }
699                         if (lastState) {
700                                 if (undoStack[stackPtr - 1].text != lastState.text) {
701                                         undoStack[stackPtr++] = lastState;
702                                 }
703                                 lastState = null;
704                         }
705                         undoStack[stackPtr++] = currState;
706                         undoStack[stackPtr + 1] = null;
707                         if (callback) {
708                                 callback();
709                         }
710                 };
711                 
712                 var handleCtrlYZ = function(event){
713                 
714                         var handled = false;
715                         
716                         if (event.ctrlKey || event.metaKey) {
717                         
718                                 // IE and Opera do not support charCode.
719                                 var keyCode = event.charCode || event.keyCode;
720                                 var keyCodeChar = String.fromCharCode(keyCode);
721                                 
722                                 switch (keyCodeChar) {
723                                 
724                                         case "y":
725                                                 undoObj.redo();
726                                                 handled = true;
727                                                 break;
728                                                 
729                                         case "z":
730                                                 if (!event.shiftKey) {
731                                                         undoObj.undo();
732                                                 }
733                                                 else {
734                                                         undoObj.redo();
735                                                 }
736                                                 handled = true;
737                                                 break;
738                                 }
739                         }
740                         
741                         if (handled) {
742                                 if (event.preventDefault) {
743                                         event.preventDefault();
744                                 }
745                                 if (top.event) {
746                                         top.event.returnValue = false;
747                                 }
748                                 return;
749                         }
750                 };
751                 
752                 // Set the mode depending on what is going on in the input area.
753                 var handleModeChange = function(event){
754                 
755                         if (!event.ctrlKey && !event.metaKey) {
756                         
757                                 var keyCode = event.keyCode;
758                                 
759                                 if ((keyCode >= 33 && keyCode <= 40) || (keyCode >= 63232 && keyCode <= 63235)) {
760                                         // 33 - 40: page up/dn and arrow keys
761                                         // 63232 - 63235: page up/dn and arrow keys on safari
762                                         setMode("moving");
763                                 }
764                                 else if (keyCode == 8 || keyCode == 46 || keyCode == 127) {
765                                         // 8: backspace
766                                         // 46: delete
767                                         // 127: delete
768                                         setMode("deleting");
769                                 }
770                                 else if (keyCode == 13) {
771                                         // 13: Enter
772                                         setMode("newlines");
773                                 }
774                                 else if (keyCode == 27) {
775                                         // 27: escape
776                                         setMode("escape");
777                                 }
778                                 else if ((keyCode < 16 || keyCode > 20) && keyCode != 91) {
779                                         // 16-20 are shift, etc. 
780                                         // 91: left window key
781                                         // I think this might be a little messed up since there are
782                                         // a lot of nonprinting keys above 20.
783                                         setMode("typing");
784                                 }
785                         }
786                 };
787                 
788                 var setEventHandlers = function(){
789                 
790                         util.addEvent(wmd.panels.input, "keypress", function(event){
791                                 // keyCode 89: y
792                                 // keyCode 90: z
793                                 if ((event.ctrlKey || event.metaKey) && (event.keyCode == 89 || event.keyCode == 90)) {
794                                         event.preventDefault();
795                                 }
796                         });
797                         
798                         var handlePaste = function(){
799                                 if (global.isIE || (inputStateObj && inputStateObj.text != wmd.panels.input.value)) {
800                                         if (timer == undefined) {
801                                                 mode = "paste";
802                                                 saveState();
803                                                 refreshState();
804                                         }
805                                 }
806                         };
807                         
808                         // pastePollInterval is specified at the beginning of this namespace.
809                         poller = new wmd.inputPoller(handlePaste, pastePollInterval);
810                         
811                         util.addEvent(wmd.panels.input, "keydown", handleCtrlYZ);
812                         util.addEvent(wmd.panels.input, "keydown", handleModeChange);
813                         
814                         util.addEvent(wmd.panels.input, "mousedown", function(){
815                                 setMode("moving");
816                         });
817                         wmd.panels.input.onpaste = handlePaste;
818                         wmd.panels.input.ondrop = handlePaste;
819                 };
820                 
821                 var init = function(){
822                         setEventHandlers();
823                         refreshState();
824                         saveState();
825                 };
826                 
827                 this.destroy = function(){
828                         if (poller) {
829                                 poller.destroy();
830                         }
831                 };
832                 
833                 init();
834         };
835         
836         // I think my understanding of how the buttons and callbacks are stored in the array is incomplete.
837         wmd.editor = function(previewRefreshCallback){
838         
839                 if (!previewRefreshCallback) {
840                         previewRefreshCallback = function(){};
841                 }
842                 
843                 var inputBox = wmd.panels.input;
844                 
845                 var offsetHeight = 0;
846                 
847                 var editObj = this;
848                 
849                 var mainDiv;
850                 var mainSpan;
851                 
852                 var div; // This name is pretty ambiguous.  I should rename this.
853                 
854                 // Used to cancel recurring events from setInterval.
855                 var creationHandle;
856                 
857                 var undoMgr; // The undo manager
858                 
859                 // Perform the button's action.
860                 var doClick = function(button){
861                 
862                         inputBox.focus();
863                         
864                         if (button.textOp) {
865                                 
866                                 if (undoMgr) {
867                                         undoMgr.setCommandMode();
868                                 }
869                                 
870                                 var state = new wmd.TextareaState();
871                                 
872                                 if (!state) {
873                                         return;
874                                 }
875                                 
876                                 var chunks = state.getChunks();
877                                 
878                                 // Some commands launch a "modal" prompt dialog.  Javascript
879                                 // can't really make a modal dialog box and the WMD code
880                                 // will continue to execute while the dialog is displayed.
881                                 // This prevents the dialog pattern I'm used to and means
882                                 // I can't do something like this:
883                                 //
884                                 // var link = CreateLinkDialog();
885                                 // makeMarkdownLink(link);
886                                 // 
887                                 // Instead of this straightforward method of handling a
888                                 // dialog I have to pass any code which would execute
889                                 // after the dialog is dismissed (e.g. link creation)
890                                 // in a function parameter.
891                                 //
892                                 // Yes this is awkward and I think it sucks, but there's
893                                 // no real workaround.  Only the image and link code
894                                 // create dialogs and require the function pointers.
895                                 var fixupInputArea = function(){
896                                 
897                                         inputBox.focus();
898                                         
899                                         if (chunks) {
900                                                 state.setChunks(chunks);
901                                         }
902                                         
903                                         state.restore();
904                                         previewRefreshCallback();
905                                 };
906                                 
907                                 var useDefaultText = true;
908                                 var noCleanup = button.textOp(chunks, fixupInputArea, useDefaultText);
909                                 
910                                 if(!noCleanup) {
911                                         fixupInputArea();
912                                 }
913                                 
914                         }
915                         
916                         if (button.execute) {
917                                 button.execute(editObj);
918                         }
919                 };
920                         
921                 var setUndoRedoButtonStates = function(){
922                         if(undoMgr){
923                                 setupButton(document.getElementById("wmd-undo-button"), undoMgr.canUndo());
924                                 setupButton(document.getElementById("wmd-redo-button"), undoMgr.canRedo());
925                         }
926                 };
927                 
928                 var setupButton = function(button, isEnabled) {
929                 
930                         var normalYShift = "0px";
931                         var disabledYShift = "-20px";
932                         var highlightYShift = "-40px";
933                         
934                         if(isEnabled) {
935                                 button.style.backgroundPosition = button.XShift + " " + normalYShift;
936                                 button.onmouseover = function(){
937                                         this.style.backgroundPosition = this.XShift + " " + highlightYShift;
938                                 };
939                                                         
940                                 button.onmouseout = function(){
941                                         this.style.backgroundPosition = this.XShift + " " + normalYShift;
942                                 };
943                                 
944                                 // IE tries to select the background image "button" text (it's
945                                 // implemented in a list item) so we have to cache the selection
946                                 // on mousedown.
947                                 if(global.isIE) {
948                                         button.onmousedown =  function() { 
949                                                 wmd.ieRetardedClick = true;
950                                                 wmd.ieCachedRange = document.selection.createRange(); 
951                                         };
952                                 }
953                                 
954                                 if (!button.isHelp)
955                                 {
956                                         button.onclick = function() {
957                                                 if (this.onmouseout) {
958                                                         this.onmouseout();
959                                                 }
960                                                 doClick(this);
961                                                 return false;
962                                         }
963                                 }
964                         }
965                         else {
966                                 button.style.backgroundPosition = button.XShift + " " + disabledYShift;
967                                 button.onmouseover = button.onmouseout = button.onclick = function(){};
968                         }
969                 }
970         
971                 var makeSpritedButtonRow = function(){
972                         
973                         var buttonBar = document.getElementById("wmd-button-bar");
974         
975                         var normalYShift = "0px";
976                         var disabledYShift = "-20px";
977                         var highlightYShift = "-40px";
978                         
979                         var buttonRow = document.createElement("ul");
980                         buttonRow.id = "wmd-button-row";
981                         buttonRow = buttonBar.appendChild(buttonRow);
982
983                         
984                         var boldButton = document.createElement("li");
985                         boldButton.className = "wmd-button";
986                         boldButton.id = "wmd-bold-button";
987                         boldButton.title = "Strong <strong> Ctrl+B";
988                         boldButton.XShift = "0px";
989                         boldButton.textOp = command.doBold;
990                         setupButton(boldButton, true);
991                         buttonRow.appendChild(boldButton);
992                         
993                         var italicButton = document.createElement("li");
994                         italicButton.className = "wmd-button";
995                         italicButton.id = "wmd-italic-button";
996                         italicButton.title = "Emphasis <em> Ctrl+I";
997                         italicButton.XShift = "-20px";
998                         italicButton.textOp = command.doItalic;
999                         setupButton(italicButton, true);
1000                         buttonRow.appendChild(italicButton);
1001
1002                         var spacer1 = document.createElement("li");
1003                         spacer1.className = "wmd-spacer";
1004                         spacer1.id = "wmd-spacer1";
1005                         buttonRow.appendChild(spacer1); 
1006
1007                         var linkButton = document.createElement("li");
1008                         linkButton.className = "wmd-button";
1009                         linkButton.id = "wmd-link-button";
1010                         linkButton.title = "Hyperlink <a> Ctrl+L";
1011                         linkButton.XShift = "-40px";
1012                         linkButton.textOp = function(chunk, postProcessing, useDefaultText){
1013                                 return command.doLinkOrImage(chunk, postProcessing, false);
1014                         };
1015                         setupButton(linkButton, true);
1016                         buttonRow.appendChild(linkButton);
1017
1018                         var quoteButton = document.createElement("li");
1019                         quoteButton.className = "wmd-button";
1020                         quoteButton.id = "wmd-quote-button";
1021                         quoteButton.title = "Blockquote <blockquote> Ctrl+Q";
1022                         quoteButton.XShift = "-60px";
1023                         quoteButton.textOp = command.doBlockquote;
1024                         setupButton(quoteButton, true);
1025                         buttonRow.appendChild(quoteButton);
1026                         
1027                         var codeButton = document.createElement("li");
1028                         codeButton.className = "wmd-button";
1029                         codeButton.id = "wmd-code-button";
1030                         codeButton.title = "Code Sample <pre><code> Ctrl+K";
1031                         codeButton.XShift = "-80px";
1032                         codeButton.textOp = command.doCode;
1033                         setupButton(codeButton, true);
1034                         buttonRow.appendChild(codeButton);
1035
1036                         var imageButton = document.createElement("li");
1037                         imageButton.className = "wmd-button";
1038                         imageButton.id = "wmd-image-button";
1039                         imageButton.title = "Image <img> Ctrl+G";
1040                         imageButton.XShift = "-100px";
1041                         imageButton.textOp = function(chunk, postProcessing, useDefaultText){
1042                                 return command.doLinkOrImage(chunk, postProcessing, true);
1043                         };
1044                         setupButton(imageButton, true);
1045                         buttonRow.appendChild(imageButton);
1046
1047                         var spacer2 = document.createElement("li");
1048                         spacer2.className = "wmd-spacer";
1049                         spacer2.id = "wmd-spacer2";
1050                         buttonRow.appendChild(spacer2); 
1051
1052                         var olistButton = document.createElement("li");
1053                         olistButton.className = "wmd-button";
1054                         olistButton.id = "wmd-olist-button";
1055                         olistButton.title = "Numbered List <ol> Ctrl+O";
1056                         olistButton.XShift = "-120px";
1057                         olistButton.textOp = function(chunk, postProcessing, useDefaultText){
1058                                 command.doList(chunk, postProcessing, true, useDefaultText);
1059                         };
1060                         setupButton(olistButton, true);
1061                         buttonRow.appendChild(olistButton);
1062                         
1063                         var ulistButton = document.createElement("li");
1064                         ulistButton.className = "wmd-button";
1065                         ulistButton.id = "wmd-ulist-button";
1066                         ulistButton.title = "Bulleted List <ul> Ctrl+U";
1067                         ulistButton.XShift = "-140px";
1068                         ulistButton.textOp = function(chunk, postProcessing, useDefaultText){
1069                                 command.doList(chunk, postProcessing, false, useDefaultText);
1070                         };
1071                         setupButton(ulistButton, true);
1072                         buttonRow.appendChild(ulistButton);
1073                         
1074                         var headingButton = document.createElement("li");
1075                         headingButton.className = "wmd-button";
1076                         headingButton.id = "wmd-heading-button";
1077                         headingButton.title = "Heading <h1>/<h2> Ctrl+H";
1078                         headingButton.XShift = "-160px";
1079                         headingButton.textOp = command.doHeading;
1080                         setupButton(headingButton, true);
1081                         buttonRow.appendChild(headingButton); 
1082                         
1083                         var hrButton = document.createElement("li");
1084                         hrButton.className = "wmd-button";
1085                         hrButton.id = "wmd-hr-button";
1086                         hrButton.title = "Horizontal Rule <hr> Ctrl+R";
1087                         hrButton.XShift = "-180px";
1088                         hrButton.textOp = command.doHorizontalRule;
1089                         setupButton(hrButton, true);
1090                         buttonRow.appendChild(hrButton); 
1091                         
1092                         var spacer3 = document.createElement("li");
1093                         spacer3.className = "wmd-spacer";
1094                         spacer3.id = "wmd-spacer3";
1095                         buttonRow.appendChild(spacer3); 
1096                         
1097                         var undoButton = document.createElement("li");
1098                         undoButton.className = "wmd-button";
1099                         undoButton.id = "wmd-undo-button";
1100                         undoButton.title = "Undo - Ctrl+Z";
1101                         undoButton.XShift = "-200px";
1102                         undoButton.execute = function(manager){
1103                                 manager.undo();
1104                         };
1105                         setupButton(undoButton, true);
1106                         buttonRow.appendChild(undoButton); 
1107                         
1108                         var redoButton = document.createElement("li");
1109                         redoButton.className = "wmd-button";
1110                         redoButton.id = "wmd-redo-button";
1111                         redoButton.title = "Redo - Ctrl+Y";
1112                         if (/win/.test(nav.platform.toLowerCase())) {
1113                                 redoButton.title = "Redo - Ctrl+Y";
1114                         }
1115                         else {
1116                                 // mac and other non-Windows platforms
1117                                 redoButton.title = "Redo - Ctrl+Shift+Z";
1118                         }
1119                         redoButton.XShift = "-220px";
1120                         redoButton.execute = function(manager){
1121                                 manager.redo();
1122                         };
1123                         setupButton(redoButton, true);
1124                         buttonRow.appendChild(redoButton); 
1125                         
1126                         var helpButton = document.createElement("li");
1127                         helpButton.className = "wmd-button";
1128                         helpButton.id = "wmd-help-button";
1129                         helpButton.XShift = "-240px";
1130                         helpButton.isHelp = true;
1131                         
1132                         var helpAnchor = document.createElement("a");
1133                         helpAnchor.href = helpLink;
1134                         helpAnchor.target = helpTarget
1135                         helpAnchor.title = helpHoverTitle;
1136                         helpButton.appendChild(helpAnchor);
1137                         
1138                         setupButton(helpButton, true);
1139                         buttonRow.appendChild(helpButton);
1140                         
1141                         setUndoRedoButtonStates();
1142                 }
1143                 
1144                 var setupEditor = function(){
1145                 
1146                         if (/\?noundo/.test(doc.location.href)) {
1147                                 wmd.nativeUndo = true;
1148                         }
1149                         
1150                         if (!wmd.nativeUndo) {
1151                                 undoMgr = new wmd.undoManager(function(){
1152                                         previewRefreshCallback();
1153                                         setUndoRedoButtonStates();
1154                                 });
1155                         }
1156                         
1157                         makeSpritedButtonRow();
1158                         
1159                         
1160                         var keyEvent = "keydown";
1161                         if (global.isOpera) {
1162                                 keyEvent = "keypress";
1163                         }
1164                         
1165                         util.addEvent(inputBox, keyEvent, function(key){
1166                                 
1167                                 // Check to see if we have a button key and, if so execute the callback.
1168                                 if (key.ctrlKey || key.metaKey) {
1169                         
1170                                         var keyCode = key.charCode || key.keyCode;
1171                                         var keyCodeStr = String.fromCharCode(keyCode).toLowerCase();
1172                                         
1173                                         switch(keyCodeStr) {
1174                                                 case "b":
1175                                                         doClick(document.getElementById("wmd-bold-button"));
1176                                                         break;
1177                                                 case "i":
1178                                                         doClick(document.getElementById("wmd-italic-button"));
1179                                                         break;
1180                                                 case "l":
1181                                                         doClick(document.getElementById("wmd-link-button"));
1182                                                         break;
1183                                                 case "q":
1184                                                         doClick(document.getElementById("wmd-quote-button"));
1185                                                         break;
1186                                                 case "k":
1187                                                         doClick(document.getElementById("wmd-code-button"));
1188                                                         break;
1189                                                 case "g":
1190                                                         doClick(document.getElementById("wmd-image-button"));
1191                                                         break;
1192                                                 case "o":
1193                                                         doClick(document.getElementById("wmd-olist-button"));
1194                                                         break;
1195                                                 case "u":
1196                                                         doClick(document.getElementById("wmd-ulist-button"));
1197                                                         break;
1198                                                 case "h":
1199                                                         doClick(document.getElementById("wmd-heading-button"));
1200                                                         break;
1201                                                 case "r":
1202                                                         doClick(document.getElementById("wmd-hr-button"));
1203                                                         break;
1204                                                 case "y":
1205                                                         doClick(document.getElementById("wmd-redo-button"));
1206                                                         break;
1207                                                 case "z":
1208                                                         if(key.shiftKey) {
1209                                                                 doClick(document.getElementById("wmd-redo-button"));
1210                                                         }
1211                                                         else {
1212                                                                 doClick(document.getElementById("wmd-undo-button"));
1213                                                         }
1214                                                         break;
1215                                                 default:
1216                                                         return;
1217                                         }
1218                                         
1219
1220                                         if (key.preventDefault) {
1221                                                 key.preventDefault();
1222                                         }
1223                                         
1224                                         if (top.event) {
1225                                                 top.event.returnValue = false;
1226                                         }
1227                                 }
1228                         });
1229                         
1230                         // Auto-continue lists, code blocks and block quotes when
1231                         // the enter key is pressed.
1232                         util.addEvent(inputBox, "keyup", function(key){
1233                                 if (!key.shiftKey && !key.ctrlKey && !key.metaKey) {
1234                                         var keyCode = key.charCode || key.keyCode;
1235                                         // Key code 13 is Enter
1236                                         if (keyCode === 13) {
1237                                                 fakeButton = {};
1238                                                 fakeButton.textOp = command.doAutoindent;
1239                                                 doClick(fakeButton);
1240                                         }
1241                                 }
1242                         });
1243                         
1244                         // Disable ESC clearing the input textarea on IE
1245                         if (global.isIE) {
1246                                 util.addEvent(inputBox, "keydown", function(key){
1247                                         var code = key.keyCode;
1248                                         // Key code 27 is ESC
1249                                         if (code === 27) {
1250                                                 return false;
1251                                         }
1252                                 });
1253                         }
1254                         
1255                         if (inputBox.form) {
1256                                 var submitCallback = inputBox.form.onsubmit;
1257                                 inputBox.form.onsubmit = function(){
1258                                         convertToHtml();
1259                                         if (submitCallback) {
1260                                                 return submitCallback.apply(this, arguments);
1261                                         }
1262                                 };
1263                         }
1264                 };
1265                 
1266                 // Convert the contents of the input textarea to HTML in the output/preview panels.
1267                 var convertToHtml = function(){
1268                 
1269                         if (wmd.showdown) {
1270                                 var markdownConverter = new wmd.showdown.converter();
1271                         }
1272                         var text = inputBox.value;
1273                         
1274                         var callback = function(){
1275                                 inputBox.value = text;
1276                         };
1277                         
1278                         if (!/markdown/.test(wmd.wmd_env.output.toLowerCase())) {
1279                                 if (markdownConverter) {
1280                                         inputBox.value = markdownConverter.makeHtml(text);
1281                                         top.setTimeout(callback, 0);
1282                                 }
1283                         }
1284                         return true;
1285                 };
1286                 
1287                 
1288                 this.undo = function(){
1289                         if (undoMgr) {
1290                                 undoMgr.undo();
1291                         }
1292                 };
1293                 
1294                 this.redo = function(){
1295                         if (undoMgr) {
1296                                 undoMgr.redo();
1297                         }
1298                 };
1299                 
1300                 // This is pretty useless.  The setupEditor function contents
1301                 // should just be copied here.
1302                 var init = function(){
1303                         setupEditor();
1304                 };
1305                 
1306                 this.destroy = function(){
1307                         if (undoMgr) {
1308                                 undoMgr.destroy();
1309                         }
1310                         if (div.parentNode) {
1311                                 div.parentNode.removeChild(div);
1312                         }
1313                         if (inputBox) {
1314                                 inputBox.style.marginTop = "";
1315                         }
1316                         top.clearInterval(creationHandle);
1317                 };
1318                 
1319                 init();
1320         };
1321         
1322         // The input textarea state/contents.
1323         // This is used to implement undo/redo by the undo manager.
1324         wmd.TextareaState = function(){
1325         
1326                 // Aliases
1327                 var stateObj = this;
1328                 var inputArea = wmd.panels.input;
1329                 
1330                 this.init = function() {
1331                 
1332                         if (!util.isVisible(inputArea)) {
1333                                 return;
1334                         }
1335                                 
1336                         this.setInputAreaSelectionStartEnd();
1337                         this.scrollTop = inputArea.scrollTop;
1338                         if (!this.text && inputArea.selectionStart || inputArea.selectionStart === 0) {
1339                                 this.text = inputArea.value;
1340                         }
1341                         
1342                 }
1343                 
1344                 // Sets the selected text in the input box after we've performed an
1345                 // operation.
1346                 this.setInputAreaSelection = function(){
1347                 
1348                         if (!util.isVisible(inputArea)) {
1349                                 return;
1350                         }
1351                         
1352                         if (inputArea.selectionStart !== undefined && !global.isOpera) {
1353                         
1354                                 inputArea.focus();
1355                                 inputArea.selectionStart = stateObj.start;
1356                                 inputArea.selectionEnd = stateObj.end;
1357                                 inputArea.scrollTop = stateObj.scrollTop;
1358                         }
1359                         else if (doc.selection) {
1360                                 
1361                                 if (doc.activeElement && doc.activeElement !== inputArea) {
1362                                         return;
1363                                 }
1364                                         
1365                                 inputArea.focus();
1366                                 var range = inputArea.createTextRange();
1367                                 range.moveStart("character", -inputArea.value.length);
1368                                 range.moveEnd("character", -inputArea.value.length);
1369                                 range.moveEnd("character", stateObj.end);
1370                                 range.moveStart("character", stateObj.start);
1371                                 range.select();
1372                         }
1373                 };
1374                 
1375                 this.setInputAreaSelectionStartEnd = function(){
1376                 
1377                         if (inputArea.selectionStart || inputArea.selectionStart === 0) {
1378                         
1379                                 stateObj.start = inputArea.selectionStart;
1380                                 stateObj.end = inputArea.selectionEnd;
1381                         }
1382                         else if (doc.selection) {
1383                                 
1384                                 stateObj.text = util.fixEolChars(inputArea.value);
1385                                 
1386                                 // IE loses the selection in the textarea when buttons are
1387                                 // clicked.  On IE we cache the selection and set a flag
1388                                 // which we check for here.
1389                                 var range;
1390                                 if(wmd.ieRetardedClick && wmd.ieCachedRange) {
1391                                         range = wmd.ieCachedRange;
1392                                         wmd.ieRetardedClick = false;
1393                                 }
1394                                 else {
1395                                         range = doc.selection.createRange();
1396                                 }
1397
1398                                 var fixedRange = util.fixEolChars(range.text);
1399                                 var marker = "\x07";
1400                                 var markedRange = marker + fixedRange + marker;
1401                                 range.text = markedRange;
1402                                 var inputText = util.fixEolChars(inputArea.value);
1403                                         
1404                                 range.moveStart("character", -markedRange.length);
1405                                 range.text = fixedRange;
1406
1407                                 stateObj.start = inputText.indexOf(marker);
1408                                 stateObj.end = inputText.lastIndexOf(marker) - marker.length;
1409                                         
1410                                 var len = stateObj.text.length - util.fixEolChars(inputArea.value).length;
1411                                         
1412                                 if (len) {
1413                                         range.moveStart("character", -fixedRange.length);
1414                                         while (len--) {
1415                                                 fixedRange += "\n";
1416                                                 stateObj.end += 1;
1417                                         }
1418                                         range.text = fixedRange;
1419                                 }
1420                                         
1421                                 this.setInputAreaSelection();
1422                         }
1423                 };
1424                 
1425                 // Restore this state into the input area.
1426                 this.restore = function(){
1427                 
1428                         if (stateObj.text != undefined && stateObj.text != inputArea.value) {
1429                                 inputArea.value = stateObj.text;
1430                         }
1431                         this.setInputAreaSelection();
1432                         inputArea.scrollTop = stateObj.scrollTop;
1433                 };
1434                 
1435                 // Gets a collection of HTML chunks from the inptut textarea.
1436                 this.getChunks = function(){
1437                 
1438                         var chunk = new wmd.Chunks();
1439                         
1440                         chunk.before = util.fixEolChars(stateObj.text.substring(0, stateObj.start));
1441                         chunk.startTag = "";
1442                         chunk.selection = util.fixEolChars(stateObj.text.substring(stateObj.start, stateObj.end));
1443                         chunk.endTag = "";
1444                         chunk.after = util.fixEolChars(stateObj.text.substring(stateObj.end));
1445                         chunk.scrollTop = stateObj.scrollTop;
1446                         
1447                         return chunk;
1448                 };
1449                 
1450                 // Sets the TextareaState properties given a chunk of markdown.
1451                 this.setChunks = function(chunk){
1452                 
1453                         chunk.before = chunk.before + chunk.startTag;
1454                         chunk.after = chunk.endTag + chunk.after;
1455                         
1456                         if (global.isOpera) {
1457                                 chunk.before = chunk.before.replace(/\n/g, "\r\n");
1458                                 chunk.selection = chunk.selection.replace(/\n/g, "\r\n");
1459                                 chunk.after = chunk.after.replace(/\n/g, "\r\n");
1460                         }
1461                         
1462                         this.start = chunk.before.length;
1463                         this.end = chunk.before.length + chunk.selection.length;
1464                         this.text = chunk.before + chunk.selection + chunk.after;
1465                         this.scrollTop = chunk.scrollTop;
1466                 };
1467
1468                 this.init();
1469         };
1470         
1471         // before: contains all the text in the input box BEFORE the selection.
1472         // after: contains all the text in the input box AFTER the selection.
1473         wmd.Chunks = function(){
1474         };
1475         
1476         // startRegex: a regular expression to find the start tag
1477         // endRegex: a regular expresssion to find the end tag
1478         wmd.Chunks.prototype.findTags = function(startRegex, endRegex){
1479         
1480                 var chunkObj = this;
1481                 var regex;
1482                 
1483                 if (startRegex) {
1484                         
1485                         regex = util.extendRegExp(startRegex, "", "$");
1486                         
1487                         this.before = this.before.replace(regex, 
1488                                 function(match){
1489                                         chunkObj.startTag = chunkObj.startTag + match;
1490                                         return "";
1491                                 });
1492                         
1493                         regex = util.extendRegExp(startRegex, "^", "");
1494                         
1495                         this.selection = this.selection.replace(regex, 
1496                                 function(match){
1497                                         chunkObj.startTag = chunkObj.startTag + match;
1498                                         return "";
1499                                 });
1500                 }
1501                 
1502                 if (endRegex) {
1503                         
1504                         regex = util.extendRegExp(endRegex, "", "$");
1505                         
1506                         this.selection = this.selection.replace(regex,
1507                                 function(match){
1508                                         chunkObj.endTag = match + chunkObj.endTag;
1509                                         return "";
1510                                 });
1511
1512                         regex = util.extendRegExp(endRegex, "^", "");
1513                         
1514                         this.after = this.after.replace(regex,
1515                                 function(match){
1516                                         chunkObj.endTag = match + chunkObj.endTag;
1517                                         return "";
1518                                 });
1519                 }
1520         };
1521         
1522         // If remove is false, the whitespace is transferred
1523         // to the before/after regions.
1524         //
1525         // If remove is true, the whitespace disappears.
1526         wmd.Chunks.prototype.trimWhitespace = function(remove){
1527         
1528                 this.selection = this.selection.replace(/^(\s*)/, "");
1529                 
1530                 if (!remove) {
1531                         this.before += re.$1;
1532                 }
1533                 
1534                 this.selection = this.selection.replace(/(\s*)$/, "");
1535                 
1536                 if (!remove) {
1537                         this.after = re.$1 + this.after;
1538                 }
1539         };
1540         
1541         
1542         wmd.Chunks.prototype.addBlankLines = function(nLinesBefore, nLinesAfter, findExtraNewlines){
1543         
1544                 if (nLinesBefore === undefined) {
1545                         nLinesBefore = 1;
1546                 }
1547                 
1548                 if (nLinesAfter === undefined) {
1549                         nLinesAfter = 1;
1550                 }
1551                 
1552                 nLinesBefore++;
1553                 nLinesAfter++;
1554                 
1555                 var regexText;
1556                 var replacementText;
1557
1558         if (navigator.userAgent.match(/Chrome/)) {
1559             "X".match(/()./)
1560         }
1561                 
1562                 this.selection = this.selection.replace(/(^\n*)/, "");
1563                 this.startTag = this.startTag + re.$1;
1564                 this.selection = this.selection.replace(/(\n*$)/, "");
1565                 this.endTag = this.endTag + re.$1;
1566                 this.startTag = this.startTag.replace(/(^\n*)/, "");
1567                 this.before = this.before + re.$1;
1568                 this.endTag = this.endTag.replace(/(\n*$)/, "");
1569                 this.after = this.after + re.$1;
1570                 
1571                 if (this.before) {
1572                 
1573                         regexText = replacementText = "";
1574                         
1575                         while (nLinesBefore--) {
1576                                 regexText += "\\n?";
1577                                 replacementText += "\n";
1578                         }
1579                         
1580                         if (findExtraNewlines) {
1581                                 regexText = "\\n*";
1582                         }
1583                         this.before = this.before.replace(new re(regexText + "$", ""), replacementText);
1584                 }
1585                 
1586                 if (this.after) {
1587                 
1588                         regexText = replacementText = "";
1589                         
1590                         while (nLinesAfter--) {
1591                                 regexText += "\\n?";
1592                                 replacementText += "\n";
1593                         }
1594                         if (findExtraNewlines) {
1595                                 regexText = "\\n*";
1596                         }
1597                         
1598                         this.after = this.after.replace(new re(regexText, ""), replacementText);
1599                 }
1600         };
1601         
1602         // The markdown symbols - 4 spaces = code, > = blockquote, etc.
1603         command.prefixes = "(?:\\s{4,}|\\s*>|\\s*-\\s+|\\s*\\d+\\.|=|\\+|-|_|\\*|#|\\s*\\[[^\n]]+\\]:)";
1604         
1605         // Remove markdown symbols from the chunk selection.
1606         command.unwrap = function(chunk){
1607                 var txt = new re("([^\\n])\\n(?!(\\n|" + command.prefixes + "))", "g");
1608                 chunk.selection = chunk.selection.replace(txt, "$1 $2");
1609         };
1610         
1611         command.wrap = function(chunk, len){
1612                 command.unwrap(chunk);
1613                 var regex = new re("(.{1," + len + "})( +|$\\n?)", "gm");
1614                 
1615                 chunk.selection = chunk.selection.replace(regex, function(line, marked){
1616                         if (new re("^" + command.prefixes, "").test(line)) {
1617                                 return line;
1618                         }
1619                         return marked + "\n";
1620                 });
1621                 
1622                 chunk.selection = chunk.selection.replace(/\s+$/, "");
1623         };
1624         
1625         command.doBold = function(chunk, postProcessing, useDefaultText){
1626                 return command.doBorI(chunk, 2, "strong text");
1627         };
1628         
1629         command.doItalic = function(chunk, postProcessing, useDefaultText){
1630                 return command.doBorI(chunk, 1, "emphasized text");
1631         };
1632         
1633         // chunk: The selected region that will be enclosed with */**
1634         // nStars: 1 for italics, 2 for bold
1635         // insertText: If you just click the button without highlighting text, this gets inserted
1636         command.doBorI = function(chunk, nStars, insertText){
1637         
1638                 // Get rid of whitespace and fix up newlines.
1639                 chunk.trimWhitespace();
1640                 chunk.selection = chunk.selection.replace(/\n{2,}/g, "\n");
1641                 
1642                 // Look for stars before and after.  Is the chunk already marked up?
1643                 chunk.before.search(/(\**$)/);
1644                 var starsBefore = re.$1;
1645                 
1646                 chunk.after.search(/(^\**)/);
1647                 var starsAfter = re.$1;
1648                 
1649                 var prevStars = Math.min(starsBefore.length, starsAfter.length);
1650                 
1651                 // Remove stars if we have to since the button acts as a toggle.
1652                 if ((prevStars >= nStars) && (prevStars != 2 || nStars != 1)) {
1653                         chunk.before = chunk.before.replace(re("[*]{" + nStars + "}$", ""), "");
1654                         chunk.after = chunk.after.replace(re("^[*]{" + nStars + "}", ""), "");
1655                 }
1656                 else if (!chunk.selection && starsAfter) {
1657                         // It's not really clear why this code is necessary.  It just moves
1658                         // some arbitrary stuff around.
1659                         chunk.after = chunk.after.replace(/^([*_]*)/, "");
1660                         chunk.before = chunk.before.replace(/(\s?)$/, "");
1661                         var whitespace = re.$1;
1662                         chunk.before = chunk.before + starsAfter + whitespace;
1663                 }
1664                 else {
1665                 
1666                         // In most cases, if you don't have any selected text and click the button
1667                         // you'll get a selected, marked up region with the default text inserted.
1668                         if (!chunk.selection && !starsAfter) {
1669                                 chunk.selection = insertText;
1670                         }
1671                         
1672                         // Add the true markup.
1673                         var markup = nStars <= 1 ? "*" : "**"; // shouldn't the test be = ?
1674                         chunk.before = chunk.before + markup;
1675                         chunk.after = markup + chunk.after;
1676                 }
1677                 
1678                 return;
1679         };
1680         
1681         command.stripLinkDefs = function(text, defsToAdd){
1682         
1683                 text = text.replace(/^[ ]{0,3}\[(\d+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|$)/gm, 
1684                         function(totalMatch, id, link, newlines, title){        
1685                                 defsToAdd[id] = totalMatch.replace(/\s*$/, "");
1686                                 if (newlines) {
1687                                         // Strip the title and return that separately.
1688                                         defsToAdd[id] = totalMatch.replace(/["(](.+?)[")]$/, "");
1689                                         return newlines + title;
1690                                 }
1691                                 return "";
1692                         });
1693                 
1694                 return text;
1695         };
1696         
1697         command.addLinkDef = function(chunk, linkDef){
1698         
1699                 var refNumber = 0; // The current reference number
1700                 var defsToAdd = {}; //
1701                 // Start with a clean slate by removing all previous link definitions.
1702                 chunk.before = command.stripLinkDefs(chunk.before, defsToAdd);
1703                 chunk.selection = command.stripLinkDefs(chunk.selection, defsToAdd);
1704                 chunk.after = command.stripLinkDefs(chunk.after, defsToAdd);
1705                 
1706                 var defs = "";
1707                 var regex = /(\[)((?:\[[^\]]*\]|[^\[\]])*)(\][ ]?(?:\n[ ]*)?\[)(\d+)(\])/g;
1708         
1709         
1710                 
1711                 var addDefNumber = function(def){
1712                         refNumber++;
1713                         def = def.replace(/^[ ]{0,3}\[(\d+)\]:/, "  [" + refNumber + "]:");
1714                         defs += "\n" + def;
1715                 };
1716                 
1717         // note that
1718         // a) the recursive call to getLink cannot go infinite, because by definition
1719         //    of regex, inner is always a proper substring of wholeMatch, and
1720         // b) more than one level of nesting is neither supported by the regex
1721         //    nor making a lot of sense (the only use case for nesting is a linked image)
1722         var getLink = function (wholeMatch, before, inner, afterInner, id, end) {
1723             inner = inner.replace(regex, getLink);
1724                         if (defsToAdd[id]) {
1725                                 addDefNumber(defsToAdd[id]);
1726                 return before + inner + afterInner + refNumber + end;
1727                                 
1728                         }
1729                         return wholeMatch;
1730                 };
1731                 
1732                 chunk.before = chunk.before.replace(regex, getLink);
1733                 
1734                 if (linkDef) {
1735                         addDefNumber(linkDef);
1736                 }
1737                 else {
1738                         chunk.selection = chunk.selection.replace(regex, getLink);
1739                 }
1740                 
1741                 var refOut = refNumber;
1742                 
1743                 chunk.after = chunk.after.replace(regex, getLink);
1744                 
1745                 if (chunk.after) {
1746                         chunk.after = chunk.after.replace(/\n*$/, "");
1747                 }
1748                 if (!chunk.after) {
1749                         chunk.selection = chunk.selection.replace(/\n*$/, "");
1750                 }
1751                 
1752                 chunk.after += "\n\n" + defs;
1753                 
1754                 return refOut;
1755         };
1756         
1757         command.doLinkOrImage = function(chunk, postProcessing, isImage){
1758         
1759                 chunk.trimWhitespace();
1760                 chunk.findTags(/\s*!?\[/, /\][ ]?(?:\n[ ]*)?(\[.*?\])?/);
1761                 
1762                 if (chunk.endTag.length > 1) {
1763                 
1764                         chunk.startTag = chunk.startTag.replace(/!?\[/, "");
1765                         chunk.endTag = "";
1766                         command.addLinkDef(chunk, null);
1767                         
1768                 }
1769                 else {
1770                 
1771                         if (/\n\n/.test(chunk.selection)) {
1772                                 command.addLinkDef(chunk, null);
1773                                 return;
1774                         }
1775                         
1776                         // The function to be executed when you enter a link and press OK or Cancel.
1777                         // Marks up the link and adds the ref.
1778                         var makeLinkMarkdown = function(link){
1779                         
1780                                 if (link !== null) {
1781                                 
1782                                         chunk.startTag = chunk.endTag = "";
1783                                         var linkDef = " [999]: " + link;
1784                                         
1785                                         var num = command.addLinkDef(chunk, linkDef);
1786                                         chunk.startTag = isImage ? "![" : "[";
1787                                         chunk.endTag = "][" + num + "]";
1788                                         
1789                                         if (!chunk.selection) {
1790                                                 if (isImage) {
1791                                                         chunk.selection = "alt text";
1792                                                 }
1793                                                 else {
1794                                                         chunk.selection = "link text";
1795                                                 }
1796                                         }
1797                                 }
1798                                 postProcessing();
1799                         };
1800                         
1801                         if (isImage) {
1802                                 util.prompt(imageDialogText, imageDefaultText, makeLinkMarkdown);
1803                         }
1804                         else {
1805                                 util.prompt(linkDialogText, linkDefaultText, makeLinkMarkdown);
1806                         }
1807                         return true;
1808                 }
1809         };
1810         
1811         util.makeAPI = function(){
1812                 wmd.wmd = {};
1813                 wmd.wmd.editor = wmd.editor;
1814                 wmd.wmd.previewManager = wmd.previewManager;
1815         };
1816         
1817         util.startEditor = function(){
1818         
1819                 if (wmd.wmd_env.autostart === false) {
1820                         util.makeAPI();
1821                         return;
1822                 }
1823
1824                 var edit;               // The editor (buttons + input + outputs) - the main object.
1825                 var previewMgr; // The preview manager.
1826                 
1827                 // Fired after the page has fully loaded.
1828                 var loadListener = function(){
1829                 
1830                         wmd.panels = new wmd.PanelCollection();
1831                         
1832                         previewMgr = new wmd.previewManager();
1833                         var previewRefreshCallback = previewMgr.refresh;
1834                                                 
1835                         edit = new wmd.editor(previewRefreshCallback);
1836                         
1837                         previewMgr.refresh(true);
1838                         
1839                 };
1840                 
1841                 util.addEvent(top, "load", loadListener);
1842         };
1843         
1844         wmd.previewManager = function(){
1845                 
1846                 var managerObj = this;
1847                 var converter;
1848                 var poller;
1849                 var timeout;
1850                 var elapsedTime;
1851                 var oldInputText;
1852                 var htmlOut;
1853                 var maxDelay = 3000;
1854                 var startType = "delayed"; // The other legal value is "manual"
1855                 
1856                 // Adds event listeners to elements and creates the input poller.
1857                 var setupEvents = function(inputElem, listener){
1858                 
1859                         util.addEvent(inputElem, "input", listener);
1860                         inputElem.onpaste = listener;
1861                         inputElem.ondrop = listener;
1862                         
1863                         util.addEvent(inputElem, "keypress", listener);
1864                         util.addEvent(inputElem, "keydown", listener);
1865                         // previewPollInterval is set at the top of this file.
1866                         poller = new wmd.inputPoller(listener, previewPollInterval);
1867                 };
1868                 
1869                 var getDocScrollTop = function(){
1870                 
1871                         var result = 0;
1872                         
1873                         if (top.innerHeight) {
1874                                 result = top.pageYOffset;
1875                         }
1876                         else 
1877                                 if (doc.documentElement && doc.documentElement.scrollTop) {
1878                                         result = doc.documentElement.scrollTop;
1879                                 }
1880                                 else 
1881                                         if (doc.body) {
1882                                                 result = doc.body.scrollTop;
1883                                         }
1884                         
1885                         return result;
1886                 };
1887                 
1888                 var makePreviewHtml = function(){
1889                 
1890                         // If there are no registered preview and output panels
1891                         // there is nothing to do.
1892                         if (!wmd.panels.preview && !wmd.panels.output) {
1893                                 return;
1894                         }
1895                         
1896                         var text = wmd.panels.input.value;
1897                         if (text && text == oldInputText) {
1898                                 return; // Input text hasn't changed.
1899                         }
1900                         else {
1901                                 oldInputText = text;
1902                         }
1903                         
1904                         var prevTime = new Date().getTime();
1905                         
1906                         if (!converter && wmd.showdown) {
1907                                 converter = new wmd.showdown.converter();
1908                         }
1909                         
1910                         if (converter) {
1911                                 text = converter.makeHtml(text);
1912                         }
1913                         
1914                         // Calculate the processing time of the HTML creation.
1915                         // It's used as the delay time in the event listener.
1916                         var currTime = new Date().getTime();
1917                         elapsedTime = currTime - prevTime;
1918                         
1919                         pushPreviewHtml(text);
1920                         htmlOut = text;
1921                 };
1922                 
1923                 // setTimeout is already used.  Used as an event listener.
1924                 var applyTimeout = function(){
1925                 
1926                         if (timeout) {
1927                                 top.clearTimeout(timeout);
1928                                 timeout = undefined;
1929                         }
1930                         
1931                         if (startType !== "manual") {
1932                         
1933                                 var delay = 0;
1934                                 
1935                                 if (startType === "delayed") {
1936                                         delay = elapsedTime;
1937                                 }
1938                                 
1939                                 if (delay > maxDelay) {
1940                                         delay = maxDelay;
1941                                 }
1942                                 timeout = top.setTimeout(makePreviewHtml, delay);
1943                         }
1944                 };
1945                 
1946                 var getScaleFactor = function(panel){
1947                         if (panel.scrollHeight <= panel.clientHeight) {
1948                                 return 1;
1949                         }
1950                         return panel.scrollTop / (panel.scrollHeight - panel.clientHeight);
1951                 };
1952                 
1953                 var setPanelScrollTops = function(){
1954                 
1955                         if (wmd.panels.preview) {
1956                                 wmd.panels.preview.scrollTop = (wmd.panels.preview.scrollHeight - wmd.panels.preview.clientHeight) * getScaleFactor(wmd.panels.preview);
1957                                 ;
1958                         }
1959                         
1960                         if (wmd.panels.output) {
1961                                 wmd.panels.output.scrollTop = (wmd.panels.output.scrollHeight - wmd.panels.output.clientHeight) * getScaleFactor(wmd.panels.output);
1962                                 ;
1963                         }
1964                 };
1965                 
1966                 this.refresh = function(requiresRefresh){
1967                 
1968                         if (requiresRefresh) {
1969                                 oldInputText = "";
1970                                 makePreviewHtml();
1971                         }
1972                         else {
1973                                 applyTimeout();
1974                         }
1975                 };
1976                 
1977                 this.processingTime = function(){
1978                         return elapsedTime;
1979                 };
1980                 
1981                 // The output HTML
1982                 this.output = function(){
1983                         return htmlOut;
1984                 };
1985                 
1986                 // The mode can be "manual" or "delayed"
1987                 this.setUpdateMode = function(mode){
1988                         startType = mode;
1989                         managerObj.refresh();
1990                 };
1991                 
1992                 var isFirstTimeFilled = true;
1993                 
1994                 var pushPreviewHtml = function(text){
1995                 
1996                         var emptyTop = position.getTop(wmd.panels.input) - getDocScrollTop();
1997                         
1998                         // Send the encoded HTML to the output textarea/div.
1999                         if (wmd.panels.output) {
2000                                 // The value property is only defined if the output is a textarea.
2001                                 if (wmd.panels.output.value !== undefined) {
2002                                         wmd.panels.output.value = text;
2003                                         wmd.panels.output.readOnly = true;
2004                                 }
2005                                 // Otherwise we are just replacing the text in a div.
2006                                 // Send the HTML wrapped in <pre><code>
2007                                 else {
2008                                         var newText = text.replace(/&/g, "&amp;");
2009                                         newText = newText.replace(/</g, "&lt;");
2010                                         wmd.panels.output.innerHTML = "<pre><code>" + newText + "</code></pre>";
2011                                 }
2012                         }
2013                         
2014                         if (wmd.panels.preview) {
2015                                 wmd.panels.preview.innerHTML = text;
2016                         }
2017                         
2018                         setPanelScrollTops();
2019                         
2020                         if (isFirstTimeFilled) {
2021                                 isFirstTimeFilled = false;
2022                                 return;
2023                         }
2024                         
2025                         var fullTop = position.getTop(wmd.panels.input) - getDocScrollTop();
2026                         
2027                         if (global.isIE) {
2028                                 top.setTimeout(function(){
2029                                         top.scrollBy(0, fullTop - emptyTop);
2030                                 }, 0);
2031                         }
2032                         else {
2033                                 top.scrollBy(0, fullTop - emptyTop);
2034                         }
2035                 };
2036                 
2037                 var init = function(){
2038                 
2039                         setupEvents(wmd.panels.input, applyTimeout);
2040                         makePreviewHtml();
2041                         
2042                         if (wmd.panels.preview) {
2043                                 wmd.panels.preview.scrollTop = 0;
2044                         }
2045                         if (wmd.panels.output) {
2046                                 wmd.panels.output.scrollTop = 0;
2047                         }
2048                 };
2049                 
2050                 this.destroy = function(){
2051                         if (poller) {
2052                                 poller.destroy();
2053                         }
2054                 };
2055                 
2056                 init();
2057         };
2058
2059         // Moves the cursor to the next line and continues lists, quotes and code.
2060         command.doAutoindent = function(chunk, postProcessing, useDefaultText){
2061                 
2062                 chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]*\n$/, "\n\n");
2063                 chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}>[ \t]*\n$/, "\n\n");
2064                 chunk.before = chunk.before.replace(/(\n|^)[ \t]+\n$/, "\n\n");
2065                 
2066                 useDefaultText = false;
2067                 
2068                 if(/(\n|^)[ ]{0,3}([*+-])[ \t]+.*\n$/.test(chunk.before)){
2069                         if(command.doList){
2070                                 command.doList(chunk, postProcessing, false, true);
2071                         }
2072                 }
2073                 if(/(\n|^)[ ]{0,3}(\d+[.])[ \t]+.*\n$/.test(chunk.before)){
2074                         if(command.doList){
2075                                 command.doList(chunk, postProcessing, true, true);
2076                         }
2077                 }
2078                 if(/(\n|^)[ ]{0,3}>[ \t]+.*\n$/.test(chunk.before)){
2079                         if(command.doBlockquote){
2080                                 command.doBlockquote(chunk, postProcessing, useDefaultText);
2081                         }
2082                 }
2083                 if(/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)){
2084                         if(command.doCode){
2085                                 command.doCode(chunk, postProcessing, useDefaultText);
2086                         }
2087                 }
2088         };
2089         
2090         command.doBlockquote = function(chunk, postProcessing, useDefaultText){
2091                 
2092                 chunk.selection = chunk.selection.replace(/^(\n*)([^\r]+?)(\n*)$/,
2093                         function(totalMatch, newlinesBefore, text, newlinesAfter){
2094                                 chunk.before += newlinesBefore;
2095                                 chunk.after = newlinesAfter + chunk.after;
2096                                 return text;
2097                         });
2098                         
2099                 chunk.before = chunk.before.replace(/(>[ \t]*)$/,
2100                         function(totalMatch, blankLine){
2101                                 chunk.selection = blankLine + chunk.selection;
2102                                 return "";
2103                         });
2104                 
2105                 var defaultText = useDefaultText ? "Blockquote" : "";
2106                 chunk.selection = chunk.selection.replace(/^(\s|>)+$/ ,"");
2107                 chunk.selection = chunk.selection || defaultText;
2108                 
2109         // The original code uses a regular expression to find out how much of the
2110         // text *directly before* the selection already was a blockquote:
2111         /*
2112                 if(chunk.before){
2113                         chunk.before = chunk.before.replace(/\n?$/,"\n");
2114                 }
2115         chunk.before = chunk.before.replace(/(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*$)/,
2116                        function (totalMatch) {
2117                            chunk.startTag = totalMatch;
2118                            return "";
2119                        });
2120         */
2121         // This comes down to:
2122         // Go backwards as many lines a possible, such that each line
2123         //  a) starts with ">", or
2124         //  b) is almost empty, except for whitespace, or
2125         //  c) is preceeded by an unbroken chain of non-empty lines
2126         //     leading up to a line that starts with ">" and at least one more character
2127         // and in addition
2128         //  d) at least one line fulfills a)
2129         //
2130         // Since this is essentially a backwards-moving regex, it's susceptible to
2131         // catstrophic backtracking and can cause the browser to hang;
2132         // see e.g. http://meta.stackoverflow.com/questions/9807.
2133         //
2134         // Hence we replaced this by a simple state machine that just goes through the
2135         // lines and checks for a), b), and c).
2136
2137         var match = "";
2138         var leftOver = "";
2139         if (chunk.before) {
2140             var lines = chunk.before.replace(/\n$/, "").split("\n");
2141             var inChain = false;
2142             for (var i in lines) {
2143                 var good = false;
2144                 line = lines[i];
2145                 inChain = inChain && line.length > 0; // c) any non-empty line continues the chain
2146                 if (/^>/.test(line)) {                // a)
2147                     good = true;
2148                     if (!inChain && line.length > 1)  // c) any line that starts with ">" and has at least one more character starts the chain
2149                         inChain = true;
2150                 } else if (/^[ \t]*$/.test(line)) {   // b)
2151                     good = true;
2152                 } else {
2153                     good = inChain;                   // c) the line is not empty and does not start with ">", so it matches if and only if we're in the chain
2154                 }
2155                 if (good) {
2156                     match += line + "\n";
2157                 } else {
2158                     leftOver += match + line;
2159                     match = "\n";
2160                 }
2161             }
2162             if (!/(^|\n)>/.test(match)) {             // d)
2163                 leftOver += match;
2164                 match = "";
2165             }
2166         }
2167
2168         chunk.startTag = match;
2169         chunk.before = leftOver;
2170
2171         // end of change
2172         
2173                 if(chunk.after){
2174                         chunk.after = chunk.after.replace(/^\n?/,"\n");
2175                 }
2176                 
2177                 chunk.after = chunk.after.replace(/^(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*)/,
2178                         function(totalMatch){
2179                                 chunk.endTag = totalMatch;
2180                                 return "";
2181                         });
2182                 
2183                 var replaceBlanksInTags = function(useBracket){
2184                         
2185                         var replacement = useBracket ? "> " : "";
2186                         
2187                         if(chunk.startTag){
2188                                 chunk.startTag = chunk.startTag.replace(/\n((>|\s)*)\n$/,
2189                                         function(totalMatch, markdown){
2190                                                 return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
2191                                         });
2192                         }
2193                         if(chunk.endTag){
2194                                 chunk.endTag = chunk.endTag.replace(/^\n((>|\s)*)\n/,
2195                                         function(totalMatch, markdown){
2196                                                 return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
2197                                         });
2198                         }
2199                 };
2200                 
2201                 if(/^(?![ ]{0,3}>)/m.test(chunk.selection)){
2202                         command.wrap(chunk, wmd.wmd_env.lineLength - 2);
2203                         chunk.selection = chunk.selection.replace(/^/gm, "> ");
2204                         replaceBlanksInTags(true);
2205                         chunk.addBlankLines();
2206                 }
2207                 else{
2208                         chunk.selection = chunk.selection.replace(/^[ ]{0,3}> ?/gm, "");
2209                         command.unwrap(chunk);
2210                         replaceBlanksInTags(false);
2211                         
2212                         if(!/^(\n|^)[ ]{0,3}>/.test(chunk.selection) && chunk.startTag){
2213                                 chunk.startTag = chunk.startTag.replace(/\n{0,2}$/, "\n\n");
2214                         }
2215                         
2216                         if(!/(\n|^)[ ]{0,3}>.*$/.test(chunk.selection) && chunk.endTag){
2217                                 chunk.endTag=chunk.endTag.replace(/^\n{0,2}/, "\n\n");
2218                         }
2219                 }
2220                 
2221                 if(!/\n/.test(chunk.selection)){
2222                         chunk.selection = chunk.selection.replace(/^(> *)/,
2223                         function(wholeMatch, blanks){
2224                                 chunk.startTag += blanks;
2225                                 return "";
2226                         });
2227                 }
2228         };
2229
2230         command.doCode = function(chunk, postProcessing, useDefaultText){
2231                 
2232                 var hasTextBefore = /\S[ ]*$/.test(chunk.before);
2233                 var hasTextAfter = /^[ ]*\S/.test(chunk.after);
2234                 
2235                 // Use 'four space' markdown if the selection is on its own
2236                 // line or is multiline.
2237                 if((!hasTextAfter && !hasTextBefore) || /\n/.test(chunk.selection)){
2238                         
2239                         chunk.before = chunk.before.replace(/[ ]{4}$/,
2240                                 function(totalMatch){
2241                                         chunk.selection = totalMatch + chunk.selection;
2242                                         return "";
2243                                 });
2244                                 
2245                         var nLinesBefore = 1;
2246                         var nLinesAfter = 1;
2247                         
2248                         
2249                         if(/\n(\t|[ ]{4,}).*\n$/.test(chunk.before) || chunk.after === ""){
2250                                 nLinesBefore = 0; 
2251                         }
2252                         if(/^\n(\t|[ ]{4,})/.test(chunk.after)){
2253                                 nLinesAfter = 0; // This needs to happen on line 1
2254                         }
2255                         
2256                         chunk.addBlankLines(nLinesBefore, nLinesAfter);
2257                         
2258                         if(!chunk.selection){
2259                                 chunk.startTag = "    ";
2260                                 chunk.selection = useDefaultText ? "enter code here" : "";
2261                         }
2262                         else {
2263                                 if(/^[ ]{0,3}\S/m.test(chunk.selection)){
2264                                         chunk.selection = chunk.selection.replace(/^/gm, "    ");
2265                                 }
2266                                 else{
2267                                         chunk.selection = chunk.selection.replace(/^[ ]{4}/gm, "");
2268                                 }
2269                         }
2270                 }
2271                 else{
2272                         // Use backticks (`) to delimit the code block.
2273                         
2274                         chunk.trimWhitespace();
2275                         chunk.findTags(/`/, /`/);
2276                         
2277                         if(!chunk.startTag && !chunk.endTag){
2278                                 chunk.startTag = chunk.endTag="`";
2279                                 if(!chunk.selection){
2280                                         chunk.selection = useDefaultText ? "enter code here" : "";
2281                                 }
2282                         }
2283                         else if(chunk.endTag && !chunk.startTag){
2284                                 chunk.before += chunk.endTag;
2285                                 chunk.endTag = "";
2286                         }
2287                         else{
2288                                 chunk.startTag = chunk.endTag="";
2289                         }
2290                 }
2291         };
2292         
2293         command.doList = function(chunk, postProcessing, isNumberedList, useDefaultText){
2294                                 
2295                 // These are identical except at the very beginning and end.
2296                 // Should probably use the regex extension function to make this clearer.
2297                 var previousItemsRegex = /(\n|^)(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*$/;
2298                 var nextItemsRegex = /^\n*(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*/;
2299                 
2300                 // The default bullet is a dash but others are possible.
2301                 // This has nothing to do with the particular HTML bullet,
2302                 // it's just a markdown bullet.
2303                 var bullet = "-";
2304                 
2305                 // The number in a numbered list.
2306                 var num = 1;
2307                 
2308                 // Get the item prefix - e.g. " 1. " for a numbered list, " - " for a bulleted list.
2309                 var getItemPrefix = function(){
2310                         var prefix;
2311                         if(isNumberedList){
2312                                 prefix = " " + num + ". ";
2313                                 num++;
2314                         }
2315                         else{
2316                                 prefix = " " + bullet + " ";
2317                         }
2318                         return prefix;
2319                 };
2320                 
2321                 // Fixes the prefixes of the other list items.
2322                 var getPrefixedItem = function(itemText){
2323                 
2324                         // The numbering flag is unset when called by autoindent.
2325                         if(isNumberedList === undefined){
2326                                 isNumberedList = /^\s*\d/.test(itemText);
2327                         }
2328                         
2329                         // Renumber/bullet the list element.
2330                         itemText = itemText.replace(/^[ ]{0,3}([*+-]|\d+[.])\s/gm,
2331                                 function( _ ){
2332                                         return getItemPrefix();
2333                                 });
2334                                 
2335                         return itemText;
2336                 };
2337                 
2338                 chunk.findTags(/(\n|^)*[ ]{0,3}([*+-]|\d+[.])\s+/, null);
2339                 
2340                 if(chunk.before && !/\n$/.test(chunk.before) && !/^\n/.test(chunk.startTag)){
2341                         chunk.before += chunk.startTag;
2342                         chunk.startTag = "";
2343                 }
2344                 
2345                 if(chunk.startTag){
2346                         
2347                         var hasDigits = /\d+[.]/.test(chunk.startTag);
2348                         chunk.startTag = "";
2349                         chunk.selection = chunk.selection.replace(/\n[ ]{4}/g, "\n");
2350                         command.unwrap(chunk);
2351                         chunk.addBlankLines();
2352                         
2353                         if(hasDigits){
2354                                 // Have to renumber the bullet points if this is a numbered list.
2355                                 chunk.after = chunk.after.replace(nextItemsRegex, getPrefixedItem);
2356                         }
2357                         if(isNumberedList == hasDigits){
2358                                 return;
2359                         }
2360                 }
2361                 
2362                 var nLinesBefore = 1;
2363                 
2364                 chunk.before = chunk.before.replace(previousItemsRegex,
2365                         function(itemText){
2366                                 if(/^\s*([*+-])/.test(itemText)){
2367                                         bullet = re.$1;
2368                                 }
2369                                 nLinesBefore = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
2370                                 return getPrefixedItem(itemText);
2371                         });
2372                         
2373                 if(!chunk.selection){
2374                         chunk.selection = useDefaultText ? "List item" : " ";
2375                 }
2376                 
2377                 var prefix = getItemPrefix();
2378                 
2379                 var nLinesAfter = 1;
2380                 
2381                 chunk.after = chunk.after.replace(nextItemsRegex,
2382                         function(itemText){
2383                                 nLinesAfter = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
2384                                 return getPrefixedItem(itemText);
2385                         });
2386                         
2387                 chunk.trimWhitespace(true);
2388                 chunk.addBlankLines(nLinesBefore, nLinesAfter, true);
2389                 chunk.startTag = prefix;
2390                 var spaces = prefix.replace(/./g, " ");
2391                 command.wrap(chunk, wmd.wmd_env.lineLength - spaces.length);
2392                 chunk.selection = chunk.selection.replace(/\n/g, "\n" + spaces);
2393                 
2394         };
2395         
2396         command.doHeading = function(chunk, postProcessing, useDefaultText){
2397                 
2398                 // Remove leading/trailing whitespace and reduce internal spaces to single spaces.
2399                 chunk.selection = chunk.selection.replace(/\s+/g, " ");
2400                 chunk.selection = chunk.selection.replace(/(^\s+|\s+$)/g, "");
2401                 
2402                 // If we clicked the button with no selected text, we just
2403                 // make a level 2 hash header around some default text.
2404                 if(!chunk.selection){
2405                         chunk.startTag = "## ";
2406                         chunk.selection = "Heading";
2407                         chunk.endTag = " ##";
2408                         return;
2409                 }
2410                 
2411                 var headerLevel = 0;            // The existing header level of the selected text.
2412                 
2413                 // Remove any existing hash heading markdown and save the header level.
2414                 chunk.findTags(/#+[ ]*/, /[ ]*#+/);
2415                 if(/#+/.test(chunk.startTag)){
2416                         headerLevel = re.lastMatch.length;
2417                 }
2418                 chunk.startTag = chunk.endTag = "";
2419                 
2420                 // Try to get the current header level by looking for - and = in the line
2421                 // below the selection.
2422                 chunk.findTags(null, /\s?(-+|=+)/);
2423                 if(/=+/.test(chunk.endTag)){
2424                         headerLevel = 1;
2425                 }
2426                 if(/-+/.test(chunk.endTag)){
2427                         headerLevel = 2;
2428                 }
2429                 
2430                 // Skip to the next line so we can create the header markdown.
2431                 chunk.startTag = chunk.endTag = "";
2432                 chunk.addBlankLines(1, 1);
2433
2434                 // We make a level 2 header if there is no current header.
2435                 // If there is a header level, we substract one from the header level.
2436                 // If it's already a level 1 header, it's removed.
2437                 var headerLevelToCreate = headerLevel == 0 ? 2 : headerLevel - 1;
2438                 
2439                 if(headerLevelToCreate > 0){
2440                         
2441                         // The button only creates level 1 and 2 underline headers.
2442                         // Why not have it iterate over hash header levels?  Wouldn't that be easier and cleaner?
2443                         var headerChar = headerLevelToCreate >= 2 ? "-" : "=";
2444                         var len = chunk.selection.length;
2445                         if(len > wmd.wmd_env.lineLength){
2446                                 len = wmd.wmd_env.lineLength;
2447                         }
2448                         chunk.endTag = "\n";
2449                         while(len--){
2450                                 chunk.endTag += headerChar;
2451                         }
2452                 }
2453         };      
2454         
2455         command.doHorizontalRule = function(chunk, postProcessing, useDefaultText){
2456                 chunk.startTag = "----------\n";
2457                 chunk.selection = "";
2458                 chunk.addBlankLines(2, 1, true);
2459         }
2460 };
2461
2462
2463 Attacklab.wmd_env = {};
2464 Attacklab.account_options = {};
2465 Attacklab.wmd_defaults = {version:1, output:"HTML", lineLength:40, delayLoad:false};
2466
2467 if(!Attacklab.wmd)
2468 {
2469         Attacklab.wmd = function()
2470         {
2471                 Attacklab.loadEnv = function()
2472                 {
2473                         var mergeEnv = function(env)
2474                         {
2475                                 if(!env)
2476                                 {
2477                                         return;
2478                                 }
2479                         
2480                                 for(var key in env)
2481                                 {
2482                                         Attacklab.wmd_env[key] = env[key];
2483                                 }
2484                         };
2485                         
2486                         mergeEnv(Attacklab.wmd_defaults);
2487                         mergeEnv(Attacklab.account_options);
2488                         mergeEnv(top["wmd_options"]);
2489                         Attacklab.full = true;
2490                         
2491                         var defaultButtons = "bold italic link blockquote code image ol ul heading hr";
2492                         Attacklab.wmd_env.buttons = Attacklab.wmd_env.buttons || defaultButtons;
2493                 };
2494                 Attacklab.loadEnv();
2495
2496         };
2497         
2498         Attacklab.wmd();
2499         Attacklab.wmdBase();
2500         Attacklab.Util.startEditor();
2501 };
2502