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