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

Revision 5485, 13.6 KB checked in by angelo, 12 years ago (diff)

Ticket #2485 - Otimizar acao de criar nova mensagem ou encaminhar

  • 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.width = '100%';
102        parentDiv.appendChild(textArea);
103        RichTextEditor.plain[ID] = false;
104       
105        if(preferences.plain_text_editor == 1)
106                {
107                        RichTextEditor.plain[ID] = true; 
108                        RichTextEditor.editorReady = true;
109                }
110        else
111                        RichTextEditor.active(pObj);
112}
113
114cRichTextEditor.prototype.getSignaturesOptions = function() {
115       
116        if(RichTextEditor.signatures !== false)
117            return RichTextEditor.signatures;
118               
119        var signatures = this.fromJSON( preferences.signatures );
120        var signature_types = this.fromJSON( preferences.signature_types );
121
122        for( key in signatures )
123            if( !signature_types[key] )
124                signatures[key] = signatures[key].replace( /\n/g, "<br>" );
125                 
126        RichTextEditor.signatures = signatures;
127        return signatures;
128
129}
130
131cRichTextEditor.prototype.getSignatureDefault = function() {
132         
133        if(RichTextEditor.signatures === false)
134            RichTextEditor.signatures = RichTextEditor.getSignaturesOptions();
135         
136        if(!RichTextEditor.signatures || 
137           !RichTextEditor.signatures[preferences.signature_default || ""])
138        {
139          preferences.use_signature = "0"; //Desabilita o uso da assinatura
140          return '';
141        }
142       
143        return unescape(RichTextEditor.signatures[preferences.signature_default]);
144
145}
146
147cRichTextEditor.prototype.createImage = function(){
148               
149        var form = document.getElementById("attachment_window");
150       
151        if (form == null){
152                form = document.createElement("DIV");
153                form.id  = "attachment_window";
154                form.style.visibility = "hidden";
155                form.style.position = "absolute";
156                form.style.background = "#eeeeee";
157                form.style.left = "0px";
158                form.style.top  = "0px";
159                form.style.width = "0px";
160                form.style.height = "0px";
161                document.body.appendChild(form);
162        }
163                var form_upload = Element('form_upload');
164                if (form_upload == null)
165                        form_upload = document.createElement("DIV");
166                form_upload.id = "form_upload";
167                form_upload.style.position = "absolute";
168                form_upload.style.top = "5px";
169                form_upload.style.left = "5px";
170                form_upload.name = get_lang("Upload File");
171                form_upload.style.width = "450px";
172                form_upload.style.height = "75px";
173                form_upload.innerHTML = get_lang('Select the desired image file')+':<br>'+
174                '<input name="image_at" maxlength="255" size="40" id="inputFile_img" type="file"><br>' +
175                '<input title="' + get_lang('Include') + '"  value="' + get_lang('Include') + '"' +
176                'type="button" onclick="RichTextEditor.addInputFile();">&nbsp;' +
177                '<input title="' + get_lang('Close') + '"  value="' + get_lang('Close') + '"' +
178                ' type="button" onclick="win.close()">';
179                form.appendChild(form_upload);
180               
181                this.showWindow(form);
182}
183cRichTextEditor.prototype.showWindow = function (div){
184
185                if(! div) {
186                        return;
187                }
188               
189                if(! this.emwindow[div.id]) {
190                        div.style.width  =  div.firstChild.style.width;
191                        div.style.height = div.firstChild.style.height;
192                        div.style.zIndex = "10000";                     
193                        var title = div.firstChild.name;
194                        var wHeight = div.offsetHeight + "px";
195                        var wWidth =  div.offsetWidth   + "px";
196                        div.style.width = div.offsetWidth - 5;
197
198                        win = new dJSWin({
199                                id: 'win_'+div.id,
200                                content_id: div.id,
201                                width: wWidth,
202                                height: wHeight,
203                                title_color: '#3978d6',
204                                bg_color: '#eee',
205                                title: title,
206                                title_text_color: 'white',
207                                button_x_img: '../phpgwapi/images/winclose.gif',
208                                border: true});
209                       
210                        this.emwindow[div.id] = win;
211                        win.draw();
212                }
213                else
214                        win = this.emwindow[div.id];
215                win.open();     
216}
217cRichTextEditor.prototype.addInputFile = function()
218{
219        //Begin: Verify if the image extension is allowed.
220        var imgExtensions = new Array("jpeg", "jpg", "gif", "png", "bmp", "xbm", "tiff", "pcx");
221        var inputFile = document.getElementById('inputFile_img');       
222        if(!inputFile.value) return false;
223        var fileExtension = inputFile.value.split(".");
224        fileExtension = fileExtension[(fileExtension.length-1)];
225        var deniedExtension = true;
226        for(var i=0; i<imgExtensions.length; i++) {
227                if(imgExtensions[i].toUpperCase() == fileExtension.toUpperCase()) {
228                        deniedExtension = false;
229                        break;
230                }
231        }
232        if(deniedExtension) {
233                alert(get_lang('File extension forbidden or invalid file') + '.');
234                return false;
235        }
236        // End: Verify image extension.
237        var id =  currentTab;
238        divFiles = document.getElementById("divFiles_"+id);
239        var countDivFiles = divFiles.childNodes.length + 1;
240
241        var divFiles = document.getElementById('divFiles_'+id);
242        inputFile.id = 'inputFile_'+id +"_"+countDivFiles;
243        inputFile.name = 'file_'+countDivFiles;
244        divFile = document.createElement('DIV');
245        divFile.appendChild(inputFile);
246        divFiles.appendChild(divFile);
247
248        var form_upload = document.getElementById('form_upload');
249        form_upload.parentNode.removeChild(form_upload);
250        win.close();
251
252        RichTextEditor.saveFlag = 0; // See if save function finished
253        var save_link = document.getElementById("save_message_options_"+id);
254        save_link.onclick = function () {};
255        this.newImageId = new Date().getTime();
256        CKEDITOR.instances['body_'+id].insertHtml('<img id="'+this.newImageId+'" src=""/>');
257        save_msg(id,true);
258}
259
260cRichTextEditor.prototype.execPosInstance = function(inst) {
261     if(RichTextEditor.editorReady === false)
262     {
263        var editor =  CKEDITOR.instances[inst];
264        var id = inst.replace('body_','');
265        editor.document.on('keydown', function(event)
266        {
267                away = false;
268                var save_link = Element("save_message_options_"+id);
269                save_link.onclick = function onclick() {openTab.toPreserve[id] = true;save_msg(id);} ;
270                $("#save_message_options_"+id).button({ disabled: false });
271        });
272       
273       
274        // IM Module Enabled
275        if( window.parent.loadscript && loadscript.autoStatusIM )
276        {
277                CKEDITOR.instances[inst].document.on('keydown', function(event){
278                        loadscript.autoStatusIM;
279                });             
280        }
281
282        if (preferences.auto_save_draft == 1)
283        {
284            autoSaveControl.status[id] = true;
285            autoSaveControl.timer[id] = window.setInterval( "autoSave("+id+")" ,autosave_time); 
286
287            CKEDITOR.instances[inst].document.on('keydown', function(event){   
288                autoSaveControl.status[id] = false;
289            })
290        }
291       
292        $(".cke_editor").css("white-space", "normal");
293        RichTextEditor.editorReady = true;
294     } 
295}
296
297cRichTextEditor.prototype.setPlain = function (active,id){
298      RichTextEditor.plain[id] = active;
299      if(active === true)
300      {
301            CKEDITOR.instances['body_'+id].destroy();
302            var height = document.body.scrollHeight;
303            height -= 330;
304            $('#body_'+id).height(height);
305            $('#body_'+id).keydown(function(event) {
306                away = false;
307                var save_link = Element("save_message_options_"+id);
308                save_link.onclick = function onclick() {openTab.toPreserve[id] = true;save_msg(id);} ;
309                                $("#save_message_options_"+id).button({ disabled: false });
310                //save_link.className = 'message_options';
311            });
312                        $("[name=textplain_rt_checkbox_"+id+"]").button({ disabled: false });
313      }   
314      else
315          RichTextEditor.active('body_'+id, id);
316}
317
318cRichTextEditor.prototype.getData = function (inst){ 
319    var id = inst.replace('body_','');
320   
321    if(RichTextEditor.plain[id] === true)
322        return $('#'+inst).val();
323    else
324        return CKEDITOR.instances[inst].getData();
325}
326cRichTextEditor.prototype.setData = function (id,data){
327   
328     if(this.plain[id] === true)
329        $('#'+id).val(data);
330     else
331        CKEDITOR.instances[id].setData(data)
332}
333cRichTextEditor.prototype.setInitData = function (id,data,reply,recursion){
334   
335    if(recursion === undefined) recursion = 1;
336    else recursion++;   
337   
338     if(this.plain[id] === true)
339     {
340                 if($('#'+id) !== undefined){
341                        $('#'+id).val(data);
342                 if (reply === undefined)       
343                        $('#to_'+id).focus();
344         }
345         else
346                          setTimeout(function() {RichTextEditor.setInitData(id,data,reply,recursion); }, 500);
347         } 
348     else
349     {
350       if( RichTextEditor.editorReady === true && CKEDITOR.instances['body_'+id] !== undefined )   
351       {
352           var editor =   CKEDITOR.instances['body_'+id];   
353           editor.insertHtml('');
354           var selection = editor.getSelection();
355           if(selection !== undefined && selection !== null) var selectionRanges = selection.getRanges();
356
357           var fontSize = '';
358           var fontFamily = '';
359           
360           if(typeof(preferences.font_size_editor) !== 'undefined')
361               fontSize = 'font-size:' + preferences.font_size_editor;
362               
363           if(fontSize != '')
364               fontFamily = ';'
365           
366           if(typeof(preferences.font_family_editor) !== 'undefined')
367               fontFamily += 'font-family:' + preferences.font_family_editor + ';';
368           
369           var divBr = '<div style="'+fontSize+fontFamily+'"><br type="_moz"></div>';
370         
371                    if(reply === undefined){
372                                editor.on('insertHtml',function setFocus(e){
373                                                        setTimeout("$('#to_"+id+"').focus()",100);
374                                                }
375                                );
376                                editor.insertHtml(divBr+divBr+data);
377                        }
378                        else if(reply == 'edit')
379                                editor.insertHtml(data);
380                        else
381                                editor.insertHtml(divBr+data);
382           
383           if(selection !== null) selection.selectRanges(selectionRanges);
384                   
385                   //Coloca o scroll do editor no inicio
386                   if (is_webkit){
387                                $('#cke_contents_body_'+id+'>iframe').scrollTo(':first');
388                   }
389          //Caso não for uma resposta votla o foco para o input to
390          //if(reply === undefined)   
391            //      setTimeout("$('#to_"+id+"').focus()",100);
392 
393       }
394       else if(recursion < 20)
395           setTimeout(function() {RichTextEditor.setInitData(id,data,reply,recursion); }, 500);
396     }
397}
398
399cRichTextEditor.prototype.destroy = function(id)
400{
401        //Remove Instancia do editor
402        if( CKEDITOR.instances[id] !== undefined )   
403             CKEDITOR.remove(CKEDITOR.instances[id]);
404}
405cRichTextEditor.prototype.active = function(id, just_id)
406{
407   
408   //Remove Instancia do editor caso ela exista
409    if( CKEDITOR.instances[id] !== undefined )   
410         CKEDITOR.remove(CKEDITOR.instances[id]);
411     
412    var height = document.body.scrollHeight;
413     height -= 375;
414     $('#'+id).ckeditor(
415          function() {RichTextEditor.execPosInstance(id)},
416          {
417              toolbar:'mail',
418              height: height
419          });
420        $("[name=textplain_rt_checkbox_"+just_id+"]").button({ disabled: false });
421}
422cRichTextEditor.prototype.focus = function(id)
423{
424    if(RichTextEditor.plain[id]  === true)
425        $('#body_'+id).focus();
426    else
427        CKEDITOR.instances['body_'+id].focus();
428
429}
430//Função reseta o atributo contentEditable para resolver bug de cursor ao trocar abas
431cRichTextEditor.prototype.setEditable = function(id) {
432        if( CKEDITOR.instances['body_'+ id] === undefined ) return;   
433        var element = CKEDITOR.instances['body_'+ id].document.getBody();
434        element.removeAttribute('contentEditable');
435        element.setAttribute('contentEditable','true');
436}
437//Build the Object
438RichTextEditor = new cRichTextEditor();
Note: See TracBrowser for help on using the repository browser.