source: trunk/expressoMail1_2/js/rich_text_editor.js @ 5083

Revision 5083, 13.3 KB checked in by airton, 13 years ago (diff)

Ticket #2086 - Troca do atual editor de emails do expresso

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1function cRichTextEditor(){
2    this.emwindow   = new Array;
3    this.editor = "body_1";
4    this.table = "";
5    this.id = "1";
6    this.saveFlag = 0;
7    this.signatures = false;
8    this.replyController = false;
9    this.newImageId = false;
10    this.plain = new Array;
11    this.editorReady = true;
12}
13
14// This code was written by Tyler Akins and has been placed in the
15// public domain.  It would be nice if you left this header intact.
16// Base64 code from Tyler Akins -- http://rumkin.com
17
18var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
19
20var ua = navigator.userAgent.toLowerCase();
21if (ua.indexOf(" chrome/") >= 0 || ua.indexOf(" firefox/") >= 0 || ua.indexOf(' gecko/') >= 0) {
22    var StringMaker = function () {
23        this.str = "";
24        this.length = 0;
25        this.append = function (s) {
26            this.str += s;
27            this.length += s.length;
28        }
29        this.prepend = function (s) {
30            this.str = s + this.str;
31            this.length += s.length;
32        }
33        this.toString = function () {
34            return this.str;
35        }
36    }
37} else {
38    var StringMaker = function () {
39        this.parts = [];
40        this.length = 0;
41        this.append = function (s) {
42            this.parts.push(s);
43            this.length += s.length;
44        }
45        this.prepend = function (s) {
46            this.parts.unshift(s);
47            this.length += s.length;
48        }
49        this.toString = function () {
50            return this.parts.join('');
51        }
52    }
53}
54
55cRichTextEditor.prototype.fromJSON = function( value )
56{
57    return (new Function( "return " + this.decode64( value )))();
58}
59
60cRichTextEditor.prototype.decode64 = function(input) {
61        if( typeof input === "undefined" ) return '';
62
63        var output = new StringMaker();
64        var chr1, chr2, chr3;
65        var enc1, enc2, enc3, enc4;
66        var i = 0;
67
68        // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
69        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
70
71        while (i < input.length) {
72                enc1 = keyStr.indexOf(input.charAt(i++));
73                enc2 = keyStr.indexOf(input.charAt(i++));
74                enc3 = keyStr.indexOf(input.charAt(i++));
75                enc4 = keyStr.indexOf(input.charAt(i++));
76
77                chr1 = (enc1 << 2) | (enc2 >> 4);
78                chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
79                chr3 = ((enc3 & 3) << 6) | enc4;
80
81                output.append(String.fromCharCode(chr1));
82
83                if (enc3 != 64) {
84                        output.append(String.fromCharCode(chr2));
85                }
86                if (enc4 != 64) {
87                        output.append(String.fromCharCode(chr3));
88                }
89        }
90
91        return output.toString();
92}
93
94
95cRichTextEditor.prototype.loadEditor = function(ID) {
96       
97        var parentDiv = document.getElementById("body_position_" + ID);
98        var pObj = "body_" + ID;
99        var textArea = document.createElement("TEXTAREA");
100        textArea.id = pObj;
101        textArea.style.height = '500';
102        textArea.style.width = '100%';
103        parentDiv.appendChild(textArea);
104        RichTextEditor.plain[ID] = false;
105       
106        if(preferences.plain_text_editor == 1)
107          RichTextEditor.plain[ID] = true; 
108        else
109                  RichTextEditor.active(pObj);
110}
111
112cRichTextEditor.prototype.getSignaturesOptions = function() {
113       
114        if(RichTextEditor.signatures !== false)
115            return RichTextEditor.signatures;
116               
117        var signatures = this.fromJSON( preferences.signatures );
118        var signature_types = this.fromJSON( preferences.signature_types );
119
120        for( key in signatures )
121            if( !signature_types[key] )
122                signatures[key] = signatures[key].replace( /\n/g, "<br>" );
123                 
124        RichTextEditor.signatures = signatures;
125        return signatures;
126
127}
128
129cRichTextEditor.prototype.getSignatureDefault = function() {
130         
131        if(RichTextEditor.signatures === false)
132            RichTextEditor.signatures = RichTextEditor.getSignaturesOptions();
133         
134        if(!RichTextEditor.signatures || 
135           !RichTextEditor.signatures[preferences.signature_default || ""])
136        {
137          preferences.use_signature = "0"; //Desabilita o uso da assinatura
138          return '';
139        }
140       
141        return unescape(RichTextEditor.signatures[preferences.signature_default]);
142
143}
144
145cRichTextEditor.prototype.createImage = function(){
146        if (preferences.auto_save_draft == 1)
147        {
148                        autosave_time = 200000;
149                        clearTimeout(openTab.autosave_timer[currentTab]);
150        }
151               
152        var form = document.getElementById("attachment_window");
153       
154        if (form == null){
155                form = document.createElement("DIV");
156                form.id  = "attachment_window";
157                form.style.visibility = "hidden";
158                form.style.position = "absolute";
159                form.style.background = "#eeeeee";
160                form.style.left = "0px";
161                form.style.top  = "0px";
162                form.style.width = "0px";
163                form.style.height = "0px";
164                document.body.appendChild(form);
165        }
166                var form_upload = Element('form_upload');
167                if (form_upload == null)
168                        form_upload = document.createElement("DIV");
169                form_upload.id = "form_upload";
170                form_upload.style.position = "absolute";
171                form_upload.style.top = "5px";
172                form_upload.style.left = "5px";
173                form_upload.name = get_lang("Upload File");
174                form_upload.style.width = "450px";
175                form_upload.style.height = "75px";
176                form_upload.innerHTML = get_lang('Select the desired image file')+':<br>'+
177                '<input name="image_at" maxlength="255" size="40" id="inputFile_img" type="file"><br>' +
178                '<input title="' + get_lang('Include') + '"  value="' + get_lang('Include') + '"' +
179                'type="button" onclick="RichTextEditor.addInputFile();">&nbsp;' +
180                '<input title="' + get_lang('Close') + '"  value="' + get_lang('Close') + '"' +
181                ' type="button" onclick="win.close()">';
182                form.appendChild(form_upload);
183               
184                this.showWindow(form);
185}
186cRichTextEditor.prototype.showWindow = function (div){
187
188                if(! div) {
189                        return;
190                }
191               
192                if(! this.emwindow[div.id]) {
193                        div.style.width  =  div.firstChild.style.width;
194                        div.style.height = div.firstChild.style.height;
195                        div.style.zIndex = "10000";                     
196                        var title = div.firstChild.name;
197                        var wHeight = div.offsetHeight + "px";
198                        var wWidth =  div.offsetWidth   + "px";
199                        div.style.width = div.offsetWidth - 5;
200
201                        win = new dJSWin({
202                                id: 'win_'+div.id,
203                                content_id: div.id,
204                                width: wWidth,
205                                height: wHeight,
206                                title_color: '#3978d6',
207                                bg_color: '#eee',
208                                title: title,
209                                title_text_color: 'white',
210                                button_x_img: '../phpgwapi/images/winclose.gif',
211                                border: true});
212                       
213                        this.emwindow[div.id] = win;
214                        win.draw();
215                }
216                else
217                        win = this.emwindow[div.id];
218                win.open();     
219}
220cRichTextEditor.prototype.addInputFile = function()
221{
222        //Begin: Verify if the image extension is allowed.
223        var imgExtensions = new Array("jpeg", "jpg", "gif", "png", "bmp", "xbm", "tiff", "pcx");
224        var inputFile = document.getElementById('inputFile_img');       
225        if(!inputFile.value) return false;
226        var fileExtension = inputFile.value.split(".");
227        fileExtension = fileExtension[(fileExtension.length-1)];
228        var deniedExtension = true;
229        for(var i=0; i<imgExtensions.length; i++) {
230                if(imgExtensions[i].toUpperCase() == fileExtension.toUpperCase()) {
231                        deniedExtension = false;
232                        break;
233                }
234        }
235        if(deniedExtension) {
236                alert(get_lang('File extension forbidden or invalid file') + '.');
237                return false;
238        }
239        // End: Verify image extension.
240        var id =  currentTab;
241        divFiles = document.getElementById("divFiles_"+id);
242        var countDivFiles = divFiles.childNodes.length + 1;
243
244        var divFiles = document.getElementById('divFiles_'+id);
245        inputFile.id = 'inputFile_'+id +"_"+countDivFiles;
246        inputFile.name = 'file_'+countDivFiles;
247        divFile = document.createElement('DIV');
248        divFile.appendChild(inputFile);
249        divFiles.appendChild(divFile);
250
251        var form_upload = document.getElementById('form_upload');
252        form_upload.parentNode.removeChild(form_upload);
253        win.close();
254
255        RichTextEditor.saveFlag = 0; // See if save function finished
256        var save_link = document.getElementById("save_message_options_"+id);
257        save_link.onclick = function () {};
258        this.newImageId = new Date().getTime();
259        CKEDITOR.instances['body_'+id].insertHtml('<img id="'+this.newImageId+'" src=""/>');
260        save_msg(id,true);
261}
262
263cRichTextEditor.prototype.execPosInstance = function(inst) {
264         
265        var editor =  CKEDITOR.instances[inst];
266       
267       
268        var id = inst.replace('body_','');
269       
270        editor.document.on('keydown', function(event)
271        {
272            away = false;
273            var save_link = Element("save_message_options_"+id);
274            save_link.onclick = function onclick() {openTab.toPreserve[id] = true;save_msg(id);} ;
275            save_link.className = 'message_options';
276        });
277       
278        //Adicionando atalhos de preferencias 
279//TODO: Não esta pegando o numero (keycode)
280//        if (preferences.use_shortcuts == '1')
281//        {
282//            CKEDITOR.instances[inst].document.on('keyup', function(event){
283//                    if(event.keyCode == 27){                         
284//                            delete_border(id,'false');}  //Tecla delete fechar aba         
285//            });
286//        } 
287       
288        // IM Module Enabled
289        if( window.parent.loadscript && loadscript.autoStatusIM )
290        {
291            CKEDITOR.instances[inst].document.on('keydown', function(event){
292                   loadscript.autoStatusIM;
293            });                 
294        }
295       
296        if (preferences.auto_save_draft == 1)
297        {
298            openTab.autosave_timer[id] = false;
299            var save_link = document.getElementById("save_message_options"+id);
300            CKEDITOR.instances[inst].document.on('keydown', function(event){
301               if (openTab.autosave_timer[id])
302                    clearTimeout(openTab.autosave_timer[id]);
303               openTab.autosave_timer[id] = setTimeout("save_msg("+id+")", autosave_time);
304                       
305            }); 
306        }
307        /////////////////////////////////////////////////////////////////////////////////////
308       
309   
310       
311       RichTextEditor.editorReady = true;
312}
313cRichTextEditor.prototype.setPlain = function (active,id){
314      RichTextEditor.plain[id] = active;
315      if(active === true)
316      {
317            CKEDITOR.instances['body_'+id].destroy();
318            var height = document.body.scrollHeight;
319            height -= 330;
320            $('#body_'+id).height(height);
321            $('#body_'+id).keydown(function(event) {
322                away = false;
323                var save_link = Element("save_message_options_"+id);
324                save_link.onclick = function onclick() {openTab.toPreserve[id] = true;save_msg(id);} ;
325                save_link.className = 'message_options';
326            });
327
328      }   
329      else
330          RichTextEditor.active('body_'+id);
331}
332
333cRichTextEditor.prototype.getData = function (inst){ 
334    var id = inst.replace('body_','');
335   
336    if(RichTextEditor.plain[id] === true)
337        return $('#'+inst).val();
338    else
339        return CKEDITOR.instances[inst].getData();
340}
341cRichTextEditor.prototype.setData = function (id,data){
342   
343     if(this.plain[id] === true)
344        $('#'+id).val(data);
345     else
346        CKEDITOR.instances[id].setData(data)
347}
348cRichTextEditor.prototype.setInitData = function (id,data,reply,recursion){
349   
350    if(recursion === undefined) recursion = 1;
351    else recursion++;   
352   
353     if(this.plain[id] === true)
354     {
355                 if($('#'+id) !== undefined)
356                        $('#'+id).val(data);
357         else
358                          setTimeout(function() {RichTextEditor.setInitData(id,data,reply,recursion); }, 500);
359         } 
360     else
361     {
362       if( RichTextEditor.editorReady === true && CKEDITOR.instances['body_'+id] !== undefined )   
363       {
364           var editor =   CKEDITOR.instances['body_'+id];   
365           editor.insertHtml('');
366           var selection = editor.getSelection();
367           if(selection !== undefined && selection !== null) var selectionRanges = selection.getRanges();
368
369           editor.insertHtml('<div><br type="_moz"></div>'+data);
370           
371          if(selection !== null) selection.selectRanges(selectionRanges);
372         
373          editor.execCommand("autogrow"); //Atualiza tamanho do editor
374         
375          //Caso não for uma resposta votla o foco para o input to
376          if(reply === undefined)   
377                  setTimeout("$('#to_"+id+"').focus()",100);
378 
379       }
380       else if(recursion < 20)
381           setTimeout(function() {RichTextEditor.setInitData(id,data,reply,recursion); }, 500);
382     }
383}
384
385cRichTextEditor.prototype.destroy = function(id)
386{
387        //Remove Instancia do editor
388        if( CKEDITOR.instances[id] !== undefined )   
389             CKEDITOR.remove(CKEDITOR.instances[id]);
390}
391cRichTextEditor.prototype.active = function(id)
392{
393   
394   //Remove Instancia do editor caso ela exista
395    if( CKEDITOR.instances[id] !== undefined )   
396         CKEDITOR.remove(CKEDITOR.instances[id]);
397     
398     $('#'+id).ckeditor(
399          function() {RichTextEditor.execPosInstance(id)},
400          {
401              toolbar:'mail'     
402          });
403
404}
405cRichTextEditor.prototype.focus = function(id)
406{
407    if(RichTextEditor.plain[id]  === true)
408        $('#body_'+id).focus();
409    else
410        CKEDITOR.instances['body_'+id].focus();
411
412}
413//Função reseta o atributo contentEditable para resolver bug de cursor ao trocar abas
414cRichTextEditor.prototype.setEditable = function(id) {
415        if( CKEDITOR.instances['body_'+ id] === undefined ) return;   
416        var element = CKEDITOR.instances['body_'+ id].document.getBody();
417        element.removeAttribute('contentEditable');
418        element.setAttribute('contentEditable','true');
419}
420//Build the Object
421RichTextEditor = new cRichTextEditor();
Note: See TracBrowser for help on using the repository browser.