]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Emails/javascript/Email.js
Release 6.1.5
[Github/sugarcrm.git] / modules / Emails / javascript / Email.js
1 /*********************************************************************************
2  * SugarCRM is a customer relationship management program developed by
3  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
4  * 
5  * This program is free software; you can redistribute it and/or modify it under
6  * the terms of the GNU Affero General Public License version 3 as published by the
7  * Free Software Foundation with the addition of the following permission added
8  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
10  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
11  * 
12  * This program is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
15  * details.
16  * 
17  * You should have received a copy of the GNU Affero General Public License along with
18  * this program; if not, see http://www.gnu.org/licenses or write to the Free
19  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20  * 02110-1301 USA.
21  * 
22  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
23  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
24  * 
25  * The interactive user interfaces in modified source and object code versions
26  * of this program must display Appropriate Legal Notices, as required under
27  * Section 5 of the GNU Affero General Public License version 3.
28  * 
29  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
30  * these Appropriate Legal Notices must retain the display of the "Powered by
31  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
32  * technical reasons, the Appropriate Legal Notices must display the words
33  * "Powered by SugarCRM".
34  ********************************************************************************/
35
36
37
38
39 var uploads_arr=new Array();
40 var uploads_count_map=new Object();
41 var uploads_count = -1;
42 var current_uploads_id = -1;
43 var append = false; // Ed has method InsertHTML which inserts at cursor point - plain does not
44 //following varaibles store references to input fields grouped with the clicked email selection button (select).
45 var current_contact = '';
46 var current_contact_id = '';
47 var current_contact_email = '';
48 var current_contact_name = '';
49 var uploadIndex = 0;
50 var select_image = SUGAR.language.get('app_strings', 'LBL_ONLY_IMAGE_ATTACHMENT');
51 var lbl_remove = SUGAR.language.get('app_strings', 'LBL_REMOVE');
52 var lbl_email_attachments_file = SUGAR.language.get('app_strings', 'LBL_EMAIL_ATTACHMENTS_FILE');
53 var lbl_email_attachments_document = SUGAR.language.get('app_strings', 'LBL_EMAIL_ATTACHMENTS_DOCUMENT');
54 var lbl_email_attachments_embeded = SUGAR.language.get('app_strings', 'LBL_EMAIL_ATTACHMENTS_EMBEDED');
55
56
57 function toggleRawEmail() {
58         var raw = document.getElementById('rawEmail');
59         var button = document.getElementById('rawButton');
60
61         if(raw.style.display == '') {
62                 raw.style.display = 'none';
63                 button.value = showRaw;
64         } else {
65                 raw.style.display = '';
66                 button.value = hideRaw;
67         }
68 }
69
70 ///////////////////////////////////////////////////////////////////////////////
71 ////    DOCUMENT HANDLING HELPERS
72
73 function deletePriorAttachment(id) {
74         var rem = document.getElementById('removeAttachment');
75
76         if(rem.value != '') {
77                 rem.value += "::";
78         }
79         rem.value += id;
80
81         document.getElementById('noteDiv'+id).style.display = 'none';
82 }
83
84 function setDocument(target, documentId, documentName, docRevId) {
85         if(window.opener.SUGAR.email2) {
86                 var idx = window.opener.SUGAR.email2.composeLayout.currentInstanceId;
87                 window.opener.SUGAR.email2.composeLayout.setDocument(idx, target, documentId, documentName, docRevId);
88         } else {
89                 var docId = window.opener.document.getElementById('documentId' + target);
90                 var docName = window.opener.document.getElementById('documentName' + target);
91                 var docRevisionId = window.opener.document.getElementById('document' + target);
92             docId.value = documentId;
93                 docName.value = documentName;
94                 docRevisionId.value = docRevId;
95         }
96         window.close();
97 }
98
99 function setDocumentToCampaignTemplate(target, documentId, documentName,docRevId, documentType) {
100 //      var docId = eval("window.opener.document.forms.EditView.documentId" + target);
101         var docId = window.opener.document.getElementById('documentId' + target);
102         //var docName = eval("window.opener.document.EditView.documentName" + target);
103         var docName = window.opener.document.getElementById('documentName' + target);
104         var docType = window.opener.document.getElementById('documentType' + target);
105
106         var docId = window.opener.document.getElementById('documentId');
107         var docName = window.opener.document.getElementById('documentName');
108         var docRevisionId = window.opener.document.getElementById('docRevId');
109         var docType = window.opener.document.getElementById('documentType');
110
111     docId.value = documentId;
112     //docId.onchange('docUpload(); form_reset_doc();');
113         docName.value = documentName;
114         docRevisionId.value = docRevId;
115         docType.value = documentType;
116         docName.onchange('docUpload(); form_reset_doc();');
117         //alert(docName.onchange);
118         window.close();
119 }
120
121 function selectDocument(target) {
122         URL="index.php?module=Emails&action=PopupDocuments&to_pdf=true&target=" + target;
123         windowName = 'selectDocument';
124         windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
125
126         win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
127         if(window.focus) {
128                 // put the focus on the popup if the browser supports the focus() method
129                 win.focus();
130         }
131 }
132
133 function addDocument() {
134         for(var i=0;i<10;i++) {
135                 var elem = document.getElementById('document'+i);
136                 if(elem.style.display == 'none') {
137                         elem.style.display='block';
138                         break;
139                 }
140         }
141 }
142
143 function deleteDocument(index) {
144         var elem = document.getElementById('document'+index);
145         document.getElementById('documentId'+index).value = "";
146         document.getElementById('documentName'+index).value = "";
147         elem.style.display='none';
148 }
149
150 // attachment functions below
151 function deleteFile(index) {
152         //get div element
153         var elem = document.getElementById('file'+index);
154         //get upload widget
155         var ea_input = document.getElementById('email_attachment'+index);
156
157         //get the parent node
158         var Parent = ea_input.parentNode;
159         //create replacement node
160         var ea = document.createElement('input');
161     ea.setAttribute('id', 'email_attachment' + index);
162     ea.setAttribute('name', 'email_attachment' + index);
163     ea.setAttribute('tabindex', '120');
164     ea.setAttribute('size', '40');
165     ea.setAttribute('type', 'file');
166
167         //replace the old node with the new one
168     Parent.replaceChild(ea, ea_input);
169
170         //hide the div element
171         elem.style.display='none';
172
173 }
174
175 function addFile() {
176         for(var i=0;i<10;i++) {
177                 var elem = document.getElementById('file'+i);
178                 if(elem.style.display == 'none') {
179                         elem.style.display='block';
180                         break;
181                 }
182         }
183 }
184 ////    END DOCUMENT HANDLING HELPERS
185 ///////////////////////////////////////////////////////////////////////////////
186
187 ///// New file upload code
188
189 function multiFiles( list_target){
190         // Where to write the list
191         this.list_target = list_target;
192         //this.list_target = document.getElementById(list_target);
193         // How many elements?
194         this.count = 0;
195         this.id = 0;
196         /**
197          * Add a new file input element
198          */
199         this.addElement = function( element ){
200                 // Make sure it's a file input element
201                 if( element.tagName == 'INPUT' && element.type == 'file' ){
202                     var currCount =this.id++;
203                         element.name = 'email_attachment' + currCount;
204                         element.id   = 'email_attachment' + currCount;
205
206                         // Add reference to this object
207                         element.multi_selector = this;
208                         // What to do when a file is selected
209             element.onchange = function(){
210
211                 //AJAX call begins
212                 var callback = {
213                             upload:function(r) {
214                         var rets = JSON.parse(r.responseText);
215                             }
216                 }
217
218                 var url ='index.php?to_pdf=1&module=EmailTemplates&action=AttachFiles';
219                     YAHOO.util.Connect.setForm(document.getElementById("upload_form"), true,true);
220             YAHOO.util.Connect.asyncRequest('POST', url, callback,null);
221             //AJAX call ends
222
223                //var theForm = document.getElementById('upload_form');
224                  var theForm = document.getElementById('EditView');
225
226
227                                 // New file input
228                                 var new_element = document.createElement( 'input' );
229                                 new_element.type = 'file';
230                            // new_element.name = 'email_attachment' +up++;
231
232                                 // Add new element
233                                 this.parentNode.insertBefore( new_element, this );
234                                 // Apply 'update' to element
235                                 this.multi_selector.addElement( new_element );
236                                 // Update list
237                                 this.multi_selector.addListRow( this );
238                                 // Hide this: we can't use display:none because Safari doesn't like it
239                  //this.style.display='none';
240                 //display none works fine for FF and IE
241                 this.style.display = 'none';
242                 //later for Safari add following
243                                 //this.style.position = 'absolute';
244                                 //this.style.left = '-5000px';
245                 };
246                         // File element counter
247                         this.count++;
248                         // Most recent element
249                         this.current_element = element;
250
251                 } else {
252                         // This can only be applied to file input elements!
253                         alert( 'Error: not a file input element' );
254                 };
255         };
256
257         /**
258          * Add a new row to the list of files
259          */
260         this.addListRow = function( element ){
261                 // Row div
262                 var new_row = document.createElement( 'div' );
263
264                 // Delete button
265                 var new_row_button_remove = document.createElement( 'input' );
266         new_row_button_remove.type = 'button';
267         new_row_button_remove.value = lbl_remove;
268
269                 var new_row_file_name = document.createElement( 'input' );
270                 new_row_file_name.type = 'text';
271                 new_row_file_name.size = '40';
272                 new_row_file_name.disabled=true;
273
274                 var new_row_chk_box = document.createElement( 'input' );
275                 new_row_chk_box.setAttribute('id','checkBoxFile[]');
276                 new_row_chk_box.setAttribute('name','checkBoxFile[]');
277                 new_row_chk_box.type = 'checkbox';
278                 new_row_chk_box.checked =false;
279                 new_row_chk_box.disabled =true;
280
281            var new_row_attach_file = document.createElement( 'input' );
282            new_row_attach_file.type = 'image';
283        new_row_attach_file.value ='/index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=company_logo.png';
284        new_row_attach_file.disabled ='true';
285
286     var imgElement = document.createElement("img");
287         imgElement.setAttribute("src", "index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=Accounts.gif");
288         imgElement.setAttribute("align","absmiddle");
289         imgElement.setAttribute("alt",lbl_email_attachments_file);
290         imgElement.setAttribute("border","0");
291         imgElement.setAttribute("height","16");
292         imgElement.setAttribute("width","16");
293
294         var new_row_button_embed = document.createElement("img");
295         new_row_button_embed.setAttribute("src", "index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif");
296         new_row_button_embed.setAttribute("align","absmiddle");
297         new_row_button_embed.setAttribute("alt",lbl_email_attachments_embeded);
298         new_row_button_embed.setAttribute("border","0");
299         new_row_button_embed.setAttribute("height","16");
300         new_row_button_embed.setAttribute("width","16");
301
302
303
304        /*
305                 var new_row_button_embed = document.createElement( 'input' );
306         new_row_button_embed.type = 'button';
307                 new_row_button_embed.value = 'Embed';
308        */
309                 // References
310                 new_row.element = element;
311         element.size='40';
312                 // Delete function
313                 new_row_button_remove.onclick= function(){
314                         // Remove element from form
315                         this.parentNode.element.parentNode.removeChild( this.parentNode.element );
316                         var filename = this.parentNode.element.value;
317                         var filename =  filename.replace(/\\/g,'/');
318                         var text = filename.split("/");
319                         nbr_elements = text.length;
320                 if(text[nbr_elements-1].indexOf('gif')>=0 || text[nbr_elements-1].indexOf('bmp') >= 0 || text[nbr_elements-1].indexOf('png') >= 0
321                    || text[nbr_elements-1].indexOf('jpg') >= 0 || text[nbr_elements-1].indexOf('GIF')>=0 || text[nbr_elements-1].indexOf('BMP') >= 0
322                    || text[nbr_elements-1].indexOf('PNG') >= 0 || text[nbr_elements-1].indexOf('JPG') >= 0)
323                    {
324                         //var imglocation = unescape(document.location.pathname.substr(1));
325                         //imglocation = imglocation.substring(0,imglocation.lastIndexOf('/')+1);
326                 var tiny = tinyMCE.getInstanceById('body_text');
327                                 var currValTiny = tiny.getContent();
328                     while(currValTiny.indexOf(unescape(text[nbr_elements-1])) != -1){
329                                    //check where the space is and keep replacing with $#32
330                                    currValTiny = currValTiny.replace(unescape(text[nbr_elements-1]),'QW%%^%%WQ');
331                    currValTiny = currValTiny.replace(/<img[^<]*QW%%\^%%WQ[^>]*>?/,'&#32');
332                                 }
333                                 tiny.setContent(currValTiny);
334                 }
335                         // Remove this row from the list
336                         this.parentNode.parentNode.removeChild( this.parentNode );
337
338                         // Decrement counter
339                         this.parentNode.element.multi_selector.count--;
340                         // Re-enable input element (if it's disabled)
341                         this.parentNode.element.multi_selector.current_element.disabled = false;
342
343                         // Appease Safari
344                         // without it Safari wants to reload the browser window
345                         // which nixes your already queued uploads
346
347                         return false;
348                 };
349
350                 new_row_button_embed.onclick= function(){
351
352                 var filename =  element.value.replace(/\\/g,'/')
353                         var text = filename.split("/");
354                         nbr_elements = text.length;
355
356                         //check if the file name has a space
357                 text[nbr_elements-1]=text[nbr_elements-1].replace(/ /g,'&#32');
358
359                         if(text[nbr_elements-1].indexOf('gif')>=0 || text[nbr_elements-1].indexOf('bmp') >= 0 || text[nbr_elements-1].indexOf('png') >= 0
360                    || text[nbr_elements-1].indexOf('jpg') >= 0 || text[nbr_elements-1].indexOf('GIF')>=0 || text[nbr_elements-1].indexOf('BMP') >= 0
361                    || text[nbr_elements-1].indexOf('PNG') >= 0 || text[nbr_elements-1].indexOf('JPG') >= 0)
362                {
363                                  cid='cid:'+text[nbr_elements-1];
364                                  /*
365                      var imglocation = unescape(document.location.pathname.substr(1));
366                      imglocation = imglocation.substring(0,imglocation.lastIndexOf('/')+1);
367                      imglocation='/'+imglocation+sugar_cache_dir+'images/';
368                      */
369                      var imglocation = sugar_cache_dir+'images/';
370                      embedImage="<img src="+imglocation+unescape(text[nbr_elements-1])+'>';
371                      //var tiny = tinyMCE.getInstanceById('body_text');
372                      embedImage = embedImage;
373                      embedImage1="<img src=cid:"+text[nbr_elements-1]+' width="1" height="1" >';
374                      //insert_variable(embedImage1);
375                      insert_variable(embedImage);
376
377                          this.parentNode.childNodes[2].checked='true';
378                }
379               else{
380                  alert(select_image);
381               }
382
383                 };
384
385                 // Set row value
386         /*
387                 var oas = new ActiveXObject("Scripting.FileSystemObject");
388         var d = document.a.b.value;
389         var e = oas.getFile(d);
390         var f = e.size;
391         alert(f + " bytes");
392                 alert(element);
393                 */
394         //new_row_file_name.value =element.value;
395         new_row_file_name_tab = element.value.split("\\");
396         //alert(new_row_file_name_tab);
397         nbr_elements = new_row_file_name_tab.length;
398         new_row_file_name.value = new_row_file_name_tab[nbr_elements-1];
399
400                 //new_row.innerHTML = element.value;
401         //add all the elements
402         //new_row.appendChild(new_row_attach_file);
403         new_row.appendChild(imgElement);
404         new_row.appendChild(new_row_button_embed);
405         new_row.appendChild(new_row_chk_box);
406                 new_row.appendChild( new_row_file_name);
407                 // Add button
408                 new_row.appendChild( new_row_button_remove);
409                 // Add it to the list
410                 this.list_target.appendChild( new_row );
411                 //document.getElementById(list_target).appendChild(new_row);
412         };
413 };
414
415
416 function docUpload() {
417
418         //var theForm = document.getElementById('EditView');
419         //var theForm = document.getElementById('upload_form');
420     //AJAX call begins
421     var rets ='';
422         var callback = {
423             upload: function(r) {
424            rets = JSON.parse(r.responseText);
425            }
426     }
427
428         var url ='index.php?module=EmailTemplates&action=AttachDocuments';
429         YAHOO.util.Connect.asyncRequest('POST', url, callback,null);
430     //AJAX call ends
431
432         var element = document.getElementById('documentName');
433         var element1 = document.getElementById('documentId');
434     var element2 = document.getElementById('docRevId');
435     var element3 = document.getElementById('documentType');
436         var elm = document.createElement('div');
437         elm.setAttribute('id','file'+uploadIndex);
438
439         var sugarDoc = document.createElement('input');
440     sugarDoc.setAttribute('type', 'label');
441     sugarDoc.setAttribute('disabled', 'true');
442     sugarDoc.setAttribute('font', 'bold');
443     sugarDoc.setAttribute('value',"Sugar Document");
444
445
446     var new_row_button_embed_doc = document.createElement( 'input' );
447     new_row_button_embed_doc.type = 'button';
448     new_row_button_embed_doc.value = 'Embed';
449
450     var new_row_chk_box = document.createElement( 'input' );
451     new_row_chk_box.setAttribute('id','checkBoxDoc'+uploadIndex);
452     new_row_chk_box.setAttribute('name','checkBoxDoc'+uploadIndex);
453         new_row_chk_box.type = 'checkbox';
454         new_row_chk_box.checked =false;
455     new_row_chk_box.disabled='true';
456
457
458         var eah = document.createElement('input');
459     eah.setAttribute('id', 'documentId'+uploadIndex);
460     eah.setAttribute('name', 'documentId'+uploadIndex);
461     eah.setAttribute('tabindex', '120');
462     eah.setAttribute('type', 'hidden');
463     eah.setAttribute('value',element1.value);
464
465
466         var attId = document.createElement('input');
467     attId.setAttribute('id', 'docRevId'+uploadIndex);
468     attId.setAttribute('name', 'docRevId'+uploadIndex);
469     attId.setAttribute('tabindex', '120');
470     attId.setAttribute('type', 'hidden');
471     attId.setAttribute('value',element2.value);
472
473
474     var attType = document.createElement('input');
475     attType.setAttribute('id', 'documentType'+uploadIndex);
476     attType.setAttribute('name', 'documentType'+uploadIndex);
477     attType.setAttribute('tabindex', '120');
478     attType.setAttribute('type', 'hidden');
479     attType.setAttribute('value',element3.value);
480
481
482         var ea = document.createElement('input');
483     ea.setAttribute('id', 'document[]');
484     ea.setAttribute('name', 'document[]');
485     ea.setAttribute('tabindex', '120');
486     ea.setAttribute('size', '40');
487     ea.setAttribute('type', 'text');
488     ea.setAttribute('disabled',true);
489     ea.setAttribute('value',element.value);
490
491     var eai = document.createElement('input');
492     eai.setAttribute('type', 'button');
493     //eai.setAttribute('onclick', 'deleteFile('+uploadIndex+');');
494     eai.setAttribute('value', lbl_remove);
495     eai.onclick=function(){
496         var filename = this.parentNode.childNodes[4].value;
497                 if(filename != null){
498                 var tiny = tinyMCE.getInstanceById('body_text');
499                                 var currValTiny = tiny.getContent();
500                     while(currValTiny.indexOf(unescape(filename)) != -1){
501                                    currValTiny = currValTiny.replace(unescape(filename),'QW%%^%%WQ');
502                                    currValTiny = currValTiny.replace(/<img[^<]*QW%%\^%%WQ[^>]*>?/,'&#32');
503                                 }
504                                 tiny.setContent(currValTiny);
505                 }
506         this.parentNode.parentNode.removeChild(this.parentNode);
507     }
508
509
510     var new_row_button_embed = document.createElement("img");
511         new_row_button_embed.setAttribute("src", "index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=attachment.gif");
512         new_row_button_embed.setAttribute("align","absmiddle");
513         new_row_button_embed.setAttribute("alt",lbl_email_attachments_embeded);
514         new_row_button_embed.setAttribute("border","0");
515         new_row_button_embed.setAttribute("height","16");
516         new_row_button_embed.setAttribute("width","16");
517         new_row_button_embed.onclick= function(){
518         //retrieve the documentid
519         this.parentNode.childNodes[2].checked='true';
520         var documentRevisionId = this.parentNode.childNodes[4].value;
521         var mime_type = this.parentNode.childNodes[5].value;
522                 if(mime_type == "image/gif" || mime_type == "image/bmp" || mime_type == "image/png" || mime_type == "image/x-png" || mime_type == "image/jpg")
523         {
524             var imglocation = unescape(document.location.pathname.substr(1));
525             imglocation = imglocation.substring(0,imglocation.lastIndexOf('/')+1);
526             imglocation='/'+imglocation+sugar_upload_dir;
527             embedImage='<img src='+imglocation+documentRevisionId+'>';
528             embedImage1='<img src=cid:'+documentRevisionId+' width="1" height="1" >';
529             insert_variable(embedImage);
530         }
531         else{
532             new_row_chk_box.checked =false;
533             alert(select_image);
534         }
535         };
536
537    var SugarDoc = document.createElement("img");
538    SugarDoc.setAttribute("src", "index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=sugar_document.png");
539    SugarDoc.setAttribute("align","absmiddle");
540    SugarDoc.setAttribute("alt",lbl_email_attachments_document);
541    SugarDoc.setAttribute("border","0");
542    SugarDoc.setAttribute("height","16");
543    SugarDoc.setAttribute("width","16");
544
545
546     //elm.appendChild(eah);
547     elm.appendChild(SugarDoc);
548     elm.appendChild(new_row_button_embed);
549     elm.appendChild(new_row_chk_box);
550     elm.appendChild(eah);
551     elm.appendChild(attId);
552     elm.appendChild(attType);
553     elm.appendChild(ea);
554     elm.appendChild(eai);
555     elm.style.display = 'block';
556
557      var rN= document.getElementById('attachments_div');
558      rN.appendChild(elm);
559      uploadIndex++;
560 }
561
562 function addUploadFiles(form_name) {
563             var chForm = document.getElementById('upload_div');
564                 var theForm = document.getElementById(form_name);
565                 var elems = chForm.getElementsByTagName("input");
566                 //get the count of all the email_attachment file elements
567                 var count = 0;
568                 //Use the count to add the documents
569         count=this.multi_selector.id;
570         for (var i=0; i<count-1; i++) {
571     //          find out all the email_attachments and append to the EditView form
572           var el = document.getElementsByName('email_attachment'+i);
573           if(el[0] != null){
574                theForm.appendChild(el[0]);
575           }
576        }
577        var chForm = document.getElementById("upload_form");
578        var elems = chForm.getElementsByTagName("input");
579        var num = 0;
580        for (var i=0; i<elems.length; i++) {
581         //find out all the email_attachments and append to the EditView form
582           var el = elems[i];
583           //var el = document.getElementsByName('checkBoxFile[]');
584           if(el.id == 'checkBoxFile[]'){
585                 var eah = document.createElement('input');
586             eah.setAttribute('id', 'embedded'+num);
587                 eah.setAttribute('name', 'embedded'+num);
588                     eah.setAttribute('tabindex', '120');
589                     eah.setAttribute('type', 'hidden');
590                     eah.setAttribute('value',el.checked);
591                 num++;
592                 theForm.appendChild(eah);
593           }
594        }
595         }
596
597 function addUploadDocs(form_name) {
598         var chForm = document.getElementById("upload_form");
599                 var theForm = document.getElementById(form_name);
600                 var attDiv = document.getElementById("attachments_div");
601                 var elems = chForm.getElementsByTagName("input");
602                 var elems1 = attDiv.getElementsByTagName("input");
603         for (var i=0; i<elems1.length; i++) {
604         //if (elems[i].type == "file") {
605          var el = elems1[i];
606         if(el.id=='document[]') {
607             theForm.appendChild(el);
608                  }
609         }
610         for (var i=0; i<elems.length; i++) {
611         //if (elems[i].type == "file") {
612          var el = elems[i];
613
614         if(el.id=='document[]') {
615             theForm.appendChild(el);
616                 }
617                 if(el.id.indexOf('documentId')>=0 || el.id=='document[]') {
618             theForm.appendChild(el);
619                 }
620       }
621         }
622
623 function form_reset_doc() {
624         // var theForm = document.getElementById('upload_form');
625          var theForm = document.getElementById('upload_div');
626          var elems = theForm.getElementsByTagName("input");
627          for (var i=0; i<elems.length; i++) {
628                  if (elems[i].type == "text" || "hidden" ) {
629                     var el = elems[i];
630                     if(el.id == 'documentName') {
631                         var new_el =document.createElement('input');
632                         new_el.type = 'hidden';
633                         new_el.name = el.name;
634                         new_el.id = el.id;
635                         new_el.onchange = el.onchange;
636                         //new_el.disabled=true;
637                         //new_el.style.visibility="hidden";
638                         new_el.siz=true;
639                         el.parentNode.replaceChild(new_el, el);
640                         //   el.parentNode.insertBefore(new_el, el);
641                   //        el.parentNode.removeChild(el);
642                     }
643                     if(el.id == 'documentId') {
644                          var new_el =document.createElement('input');
645                          new_el.type = 'hidden';
646                          new_el.name = el.name;
647                          new_el.id = el.id;
648                          //new_el.onchange = el.onchange;
649                          //new_el.DISABLED='true';
650                          el.parentNode.replaceChild(new_el, el);
651                         //   el.parentNode.insertBefore(new_el, el);
652                           // el.parentNode.removeChild(el);
653                      }
654                  }
655         }
656 }
657
658
659 function selectDoc() {
660         URL="index.php?module=EmailTemplates&action=PopupDocumentsCampaignTemplate&to_pdf=true&target=" ;
661         windowName = 'selectDocument';
662         windowFeatures = 'width=800' + ',height=600' + ',resizable=1,scrollbars=1';
663         win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
664         if(window.focus) {
665                 // put the focus on the popup if the browser supports the focus() method
666                 win.focus();
667         }
668 }
669 ///////////////////////////////////////////////////////////////////////////////
670 ////    HTML/PLAIN EDITOR FUNCTIONS
671 function setEditor() {
672         if(document.getElementById('setEditor').checked == true) {
673                 toggle_textonly();
674         }
675 }
676
677 // cn: bug 9690 - unchecked "Send HTML" - we hose the html_div contents
678 function prepSave() {
679         if(document.getElementById('setEditor').checked == true) {
680                 document.getElementById('html_div').innerHTML = '';
681         }
682
683 }
684
685 function toggle_textonly() {
686         var altText = document.getElementById('alt_text_div');
687         var plain = document.getElementById('text_div');
688         var html = document.getElementById('html_div');
689
690         var desc = document.getElementById('description');
691         var tiny = tinyMCE.getInstanceById('description_html');
692
693         // toggling INTO HTML editting
694         if(html.style.display == 'none') {
695                 html.style.display = 'block';
696                 if(document.getElementById('toggle_textarea_elem').checked == false) {
697                         plain.style.display = 'none';
698                 }
699                 altText.style.display = 'block';
700
701                 var plainText = new String(desc.value);
702                 plainText = plainText.replace(/\n/gi, '<br />');
703                 tiny.setContent(plainText);
704         } else {
705                 // toggling into Plain Text ONLY
706                 html.style.display = 'none';
707                 plain.style.display = 'block';
708                 altText.style.display = 'none';
709
710                 if(tiny.getContent()) {
711                         var htmlText = new String(tiny.getContent());
712                         htmlText = htmlText.replace(/<br \/>/gi, "\n");
713                         htmlText = htmlText.replace(/&gt;/gi, ">");
714                         htmlText = htmlText.replace(/&lt;/gi, "<");
715                         htmlText = htmlText.replace(/&nbsp;/gi, " ");
716                         desc.value = stripTags(htmlText);
717                 }
718         }
719 }
720
721 function stripTags(str) {
722         var theText = new String(str);
723
724         if(theText != 'undefined') {
725                 return theText.replace(/<\/?[^>]+>/gi, '');
726         }
727 }
728
729 function toggle_textarea() {
730         var checkbox = document.getElementById('toggle_textarea_elem');
731         var plain = document.getElementById('text_div');
732
733         if (checkbox.checked == false) {
734                 plain.style.display = 'none';
735         } else {
736                 plain.style.display = 'block';
737         }
738 }
739 ////    END HTML/PLAIN EDITOR FUNCTIONS
740 ///////////////////////////////////////////////////////////////////////////////
741
742
743
744
745 ///////////////////////////////////////////////////////////////////////////////
746 ////    EMAIL TEMPLATE CODE
747 function fill_email(id) {
748         var where = "parent_id='" + id + "'";
749         var order = '';
750
751         if(id == '') {
752                 // query based on template, contact_id0,related_to
753                 if(! append) {
754                         document.EditView.name.value  = '';
755                         document.EditView.description.value = '';
756                         document.EditView.description_html.value = '';
757                 }
758                 return;
759         }
760         call_json_method('EmailTemplates','retrieve','record='+id,'email_template_object', appendEmailTemplateJSON);
761         args = {"module":"Notes","where":where, "order":order};
762
763         if(typeof(global_rpcClient) == 'undefined') {
764                 global_rpcClient = new SugarRPCClient();
765         }
766
767         req_id = global_rpcClient.call_method('get_full_list', args);
768         global_request_registry[req_id] = [ejo, 'display'];
769 }
770
771 function appendEmailTemplateJSON() {
772         // query based on template, contact_id0,related_to
773         if(document.EditView.name.value == '') { // cn: bug 7743, don't stomp populated Subject Line
774                 document.EditView.name.value = decodeURI(encodeURI(json_objects['email_template_object']['fields']['subject']));
775         }
776
777         document.EditView.description.value += decodeURI(encodeURI(json_objects['email_template_object']['fields']['body'])).replace(/<BR>/ig, '\n');
778         var tiny = tinyMCE.getInstanceById("description_html");
779         var tinyHtml = tiny.getContent(true);
780
781         // cn: bug 10985 - IE6/7 will show inline image at top of screen if we set this with no valid target
782         if(document.getElementById('setEditor').checked == false) {
783                 var descHtml = decodeURI(encodeURI(json_objects['email_template_object']['fields']['body_html'])).replace(/&lt;/gi,'<').replace(/&gt;/gi,'>').replace(/<BR>/ig, '\n').replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');
784
785                 // cn: bug 13376 - leave &amp; to last to preserve certain HTML-entities for TinyMCE editor
786                 descHtml = descHtml.replace(/&amp;/gi,'&');
787
788                 tiny.setContent(tinyHtml + descHtml);
789         }
790
791         var htmlDiv = document.getElementById('html_div');
792
793         // hide the HTML editor if this is Plain-text only
794         if((tinyHtml == '' || tinyHtml == '<br>') && htmlDiv.style.display == '') {
795                 var desc = document.getElementById('description');
796                 var plainText = new String(desc.value);
797                 plainText = plainText.replace(/\n/gi, '<br />');
798                 tiny.setContent(plainText);
799
800                 // cn: bug 6212
801                 // if the template is plain-text, then uncheck "Send HTML Email"
802                 document.getElementById('setEditor').checked = true;
803                 setEditor();
804         }
805 }
806
807 if(typeof SugarClass == "object") {
808         SugarClass.inherit("EmailJsonObj","SugarClass");
809 }
810 function EmailJsonObj() {
811 }
812 EmailJsonObj.prototype.display = function(result) {
813         var bean;
814         var block = document.getElementById('template_attachments');
815         var target = block.innerHTML;
816         var full_file_path;
817
818         for(i in result) {
819                 if(typeof result[i] == 'object') {
820                         bean = result[i];
821                         full_file_path = file_path + bean['id']+bean['filename'];
822                         target += '\n<input type="hidden" name="template_attachment[]" value="' + bean['id'] + '">';
823                         target += '\n<input type="checkbox" name="temp_remove_attachment[]" value="' + bean['id'] + '"> '+ lnk_remove + '&nbsp;&nbsp;';
824                         target += '<a href="' + full_file_path + '"target="_blank">' + bean['filename'] + '</a><br>';
825                 }
826         }
827         block.innerHTML = target;
828 }
829
830 ejo = new EmailJsonObj();
831 ////    END EMAIL TEMPLATE CODE
832 ///////////////////////////////////////////////////////////////////////////////
833
834
835 function fill_form(type, error_text) {
836         if(document.getElementById('subjectfield').value == '') {
837                 var sendAnyways = confirm(lbl_send_anyways);
838                 if(sendAnyways == false) { return false; }
839         }
840
841         if(type == 'out' && document.EditView.to_addrs.value  == '' &&
842                 document.EditView.cc_addrs.value  == '' &&
843                 document.EditView.bcc_addrs.value  == '') {
844
845                 alert(error_text);
846                 return false;
847         }
848
849         var the_form = document.EditView;
850         var inputs = the_form.getElementsByTagName('input');
851
852         //  this detects if browser needs the following hack or not..
853         if(inputs.length > 0) {
854                 // no need to appendChild to EditView to get file uploads to work
855                 return check_form('EditView');
856         }
857
858         if(! check_form('EditView')) {
859                 return false;
860         }
861         return true;
862 }
863
864 function setLabels(uploads_arr) {
865 }
866
867
868
869 //this function appends the selected email address to the aggregated email address fields.
870 function set_current_parent(id,email,name,value) {
871         current_contact_id.value += id+";";
872         current_contact_email.value += email+";";
873         current_contact_name.value += name+";";
874
875         if(current_contact.value != '') {
876                 current_contact.value += "; ";
877         }
878
879         current_contact.value += name + " <" + email + ">";
880 //      current_contact.value += value;
881 }
882
883 function set_email_return(popup_reply_data) {
884         var form_name = popup_reply_data.form_name;
885         var name_to_value_array = popup_reply_data.name_to_value_array;
886         if (typeof name_to_value_array == "object" ) {
887                 update_email_addresses(form_name,name_to_value_array);
888         } else {
889                 for(var i in name_to_value_array) {
890                         update_email_addresses(form_name,name_to_value_array[i]);
891                 }
892         }
893 }
894
895 function update_email_addresses(form_name,name_to_value) {
896         for(var the_key in name_to_value) {
897                 if(the_key == 'toJSON') {
898                         /* just ignore */
899                 } else {
900                         var displayValue = name_to_value[the_key];
901                         displayValue=displayValue.replace('&#039;',"'");  //restore escaped single quote.
902                         displayValue=displayValue.replace('&amp;',"&");  //restore escaped &.
903                         displayValue=displayValue.replace('&gt;',">");  //restore escaped >.
904                         displayValue=displayValue.replace('&lt;',"<");  //restore escaped <.
905                         displayValue=displayValue.replace('&quot; ',"\"");  //restore escaped ".
906
907                         window.document.forms[form_name].elements[the_key].value += displayValue + '; ';
908                 }
909         }
910 }
911
912 //create references to input fields associated with the select email address button.
913 //Clicked button is passed as the parameter to the function.
914 function button_change_onclick(obj) {
915         var prefix = 'to_';
916         if(obj.name.match(/^cc_/i)) {
917             prefix = 'cc_';
918         } else if(obj.name.match(/^bcc_/i)) {
919                 prefix = 'bcc_';
920         }
921
922         for(var i = 0; i < obj.form.length;i++) {
923                 child = obj.form[i];
924                 if(child.name.indexOf(prefix) != 0) {
925                         continue;
926                 }
927
928                 if(child.name.match(/addrs_emails$/i)) {
929                         current_contact_email = child;
930                 } else if(child.name.match(/addrs_ids$/i)) {
931                         current_contact_id = child;
932                 } else if(child.name.match(/addrs_names$/i)) {
933                         current_contact_name = child;
934                 } else if(child.name.match(/addrs$/i)) {
935                         current_contact = child;
936                 }
937         }
938
939         var filter = '';
940         var acct_name = '';
941
942         if(document.EditView.parent_type.value  == 'Accounts' && typeof(document.EditView.parent_name.value) != 'undefined' && document.EditView.parent_name.value != '') {
943                 filter = "&form_submit=false&query=true&html=Email_picker&account_name=" + escape(document.EditView.parent_name.value);
944                 acct_name = document.EditView.parent_name.value;
945         }
946
947         var popup_request_data =
948         {
949                 "call_back_function" : "set_email_return",
950                 "form_name" : "EditView",
951                 "field_to_name_array" :
952                 {
953                         "id" : prefix + "addrs_ids",
954                         "email1" : prefix + "addrs_emails",
955                         "name" : prefix + "addrs_names",
956                         "email_and_name1" : prefix + "addrs_field"
957                 }
958         };
959
960         return open_popup("Contacts", 600, 400, filter, true, false, popup_request_data, 'MultiSelect', false, 'popupdefsEmail');
961 }
962
963 //this function clear the value stored in the aggregated email address fields(nodes).
964 //it relies on the references set by the button_change_onclick method
965 function clear_email_addresses() {
966
967         if(current_contact != '') {
968                 current_contact.value = '';
969         }
970         if(current_contact_id != '') {
971                 current_contact_id.value = '';
972         }
973         if(current_contact_email != '') {
974                 current_contact_email.value = '';
975         }
976         if(current_contact_name != '') {
977                 current_contact_name.value = '';
978         }
979 }
980
981 function quick_create_overlib(id, theme) {
982     return overlib('<a style=\'width: 150px\' class=\'menuItem\' onmouseover=\'hiliteItem(this,"yes");\' onmouseout=\'unhiliteItem(this);\' href=\'index.php?module=Cases&action=EditView&inbound_email_id=' + id + '\'>' +
983             "<img border='0' src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=Cases.gif' style='margin-right:5px'>" + SUGAR.language.get('Emails', 'LBL_LIST_CASE') + '</a>' +
984             "<a style='width: 150px' class='menuItem' onmouseover='hiliteItem(this,\"yes\");' onmouseout='unhiliteItem(this);' href='index.php?module=Leads&action=EditView&inbound_email_id=" + id + "'>" +
985                     "<img border='0' src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=Leads.gif' style='margin-right:5px'>"
986                     + SUGAR.language.get('Emails', 'LBL_LIST_LEAD') + "</a>" +
987              "<a style='width: 150px' class='menuItem' onmouseover='hiliteItem(this,\"yes\");' onmouseout='unhiliteItem(this);' href='index.php?module=Contacts&action=EditView&inbound_email_id=" + id + "'>" +
988                     "<img border='0' src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=Contacts.gif' style='margin-right:5px'>"
989                     + SUGAR.language.get('Emails', 'LBL_LIST_CONTACT') + "</a>" +
990              "<a style='width: 150px' class='menuItem' onmouseover='hiliteItem(this,\"yes\");' onmouseout='unhiliteItem(this);' href='index.php?module=Bugs&action=EditView&inbound_email_id=" + id + "'>"+
991                     "<img border='0' src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=Bugs.gif' style='margin-right:5px'>"
992                     + SUGAR.language.get('Emails', 'LBL_LIST_BUG') + "</a>" +
993              "<a style='width: 150px' class='menuItem' onmouseover='hiliteItem(this,\"yes\");' onmouseout='unhiliteItem(this);' href='index.php?module=Tasks&action=EditView&inbound_email_id=" + id + "'>" +
994                     "<img border='0' src='index.php?entryPoint=getImage&themeName="+SUGAR.themes.theme_name+"&imageName=Tasks.gif' style='margin-right:5px'>"
995                    + SUGAR.language.get('Emails', 'LBL_LIST_TASK') + "</a>"
996             , CAPTION, SUGAR.language.get('Emails', 'LBL_QUICK_CREATE')
997             , STICKY, MOUSEOFF, 3000, CLOSETEXT, '<img border=0  style="margin-left:2px; margin-right: 2px;" src="index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=close.gif">', WIDTH, 150, CLOSETITLE, SUGAR.language.get('app_strings', 'LBL_ADDITIONAL_DETAILS_CLOSE_TITLE'), CLOSECLICK, FGCLASS, 'olOptionsFgClass',
998             CGCLASS, 'olOptionsCgClass', BGCLASS, 'olBgClass', TEXTFONTCLASS, 'olFontClass', CAPTIONFONTCLASS, 'olOptionsCapFontClass', CLOSEFONTCLASS, 'olOptionsCloseFontClass');
999 }
1000
1001