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