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