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