// form.js - utilities for message creation and editing forms FIRSTCLASS.util.Form = { validateName: function(baseURL, string, fieldId, index, callback, options, allowgroups, params, ignorelast) { if (this._lastNameValidated == string && !ignorelast) return; this._lastNameValidated = string; var requestUrl = FIRSTCLASS.lang.ensureSlashUrl(baseURL) + FIRSTCLASS.opCodes.Lookup+"?Templates=JS&JSON=2&Operation=InsertMulti&FieldID="+fieldId+"&charset=UTF-8&Srch="+FIRSTCLASS.lang.uesc(string); if (params) { requestUrl = requestUrl + "&"+ params; } if (typeof options == "undefined" || !options) { options = 4; } requestUrl += "&Options=" + options; var connManagerRequest = FIRSTCLASS.util.net.asyncRequest("GET", requestUrl, { success:function(response) { var newdata = []; try { newdata = YAHOO.lang.JSON.parse(response.responseText); } catch(x){ //YAHOO.log("JSON Parse Failed", "error", "Form.js"); callback.onFailure({"response":response}); return; } if (!allowgroups) { var data = []; for (var i in newdata.records) { if (newdata.records[i].nmattrs1.mailable == 1) { data.push(newdata.records[i]); } } newdata.records = data; } if (newdata.records && newdata.records.length == 1) { callback.onComplete({ "match":"single", "item":newdata.records[0], "pattern":string }); } else if (newdata.records && newdata.records.length > 1) { callback.onComplete({ "match":"multi", "dataSource":new FIRSTCLASS.util.DataSource({baseUrl:requestUrl, prePopulateData:newdata, name:'ValidateName (' + string + ")"}), "pattern":string }); } else { callback.onComplete({ "match":"none", "pattern":string }); } }, failure:function(response) { callback.onFailure({"response":response}); } }); }, deleteName: function(baseURL, fieldId, index, cid, callback) { var param = "&Index="+index; if (typeof cid == "number") { param = "&ClientID="+cid; } var requestUrl = FIRSTCLASS.lang.ensureSlashUrl(baseURL) + FIRSTCLASS.opCodes.Lookup+"?Templates=JS&JSON=2&Operation=Delete&FieldID="+fieldId+param; var connManagerRequest = FIRSTCLASS.util.net.asyncRequest("GET", requestUrl, { success:function(response) { if (callback && callback.onComplete) { callback.onComplete(response); } }, failure:function(response) { if (callback && callback.onFailure) { callback.onFailure({"response":response}); } } }); }, add: function(baseURL, string, fieldId, index, callback, params, suppresslookup, close) { if (!params) { params = ""; } var lookup = FIRSTCLASS.opCodes.Lookup; if (suppresslookup) { lookup = ""; } var requestUrl = FIRSTCLASS.lang.ensureSlashUrl(baseURL) + lookup + "?Templates=JS&JSON=2&Operation=Add&FieldID="+fieldId + params; if (FIRSTCLASS.lang.isEmailAddress(string)) { requestUrl+="&Name=" + FIRSTCLASS.lang.uesc(string); } else { requestUrl+="&Name="+string; } if (close) { requestUrl += "&Close=0"; } var connManagerRequest = FIRSTCLASS.util.net.asyncRequest("GET", requestUrl, { success:function(response) { callback.onComplete(response); }, failure:function(response) { callback.onFailure({"response":response}); } }); }, nameValCompare: function(key, string) { var keys = key.split(" "); var strings = string.split("%20"); var lastindexfound = -1; var keyindex = 0; for (var i = 0; i < strings.length; i++) { if (strings[i] === "") { lastindexfound = i; continue; } while (keyindex < keys.length) { if (keys[keyindex++].indexOf(strings[i]) >= 0) { lastindexfound = i; break; } } } return (lastindexfound == strings.length-1); } }; // Configuration variables for the message editor: // baseURL - the container for a new item or the item itself // op - operation to be performed - "Create" or "Edit" or FIRSTCLASS.opCodes.Reply or whatever // params - url param string to add to the edit request (no question mark) // element - element to contain the editor // objType - from FIRSTCLASS.objTypes // formID - the FirstClass form ID to be edited // formElId - the id of the
element in the template // bodytype - "plain" or "HTML" // quoteText - text to quote for replies // quoteAuth - him what said it // sendTo - default addressee // callback - callback object with the functions: // onLoaded - prepare calling object when editor is about to open // onFail - object failed to open // onDisplay - the editor content is in the DOM // validate - validate the forms data before submitting (return false to abort submitting) // onCancel - cancel button pressed // onSave - submit transaction completed // onCommand - user issued a command to the editor // onTyping - user typed in the editor // initHeight - initial height of editor // initWidth - initial width of editor // showAddr - show the address block // tbType - canned toolbar type - "message", "reply", "wiki", "blog" // toolbar - YUI toolbar config object if you want a custom toolbar // dataSource - data source for object's container // row - item's data source row if existing // upload - pass in YUI XHR upload param // autoHeight - true if you want editor to grow with the content // maxImage - (number) maximum pixel dimension of uploaded images; larger images will be thumbnailed // overrideForms - url param to override forms path FIRSTCLASS.util.Message = function(config) { // capture config this.configure(config); this._editor = null; // form the URL var url = []; var that = this; url.push(FIRSTCLASS.lang.ensureSlashUrl(this._config.baseURL)); url.push(this._config.op); url.push("?FormID=" + this._config.formID); if (this._urlParams) { url.push("&" + this._urlParams); } url[0] = url.join(""); // member init this._dialog = null; this._embedIdx = -1; this._embedContents = []; this._touches = []; this._editForm = null; this._nameTable = null; this._nameContainer = null; this._validatedNames = null; this._currentlySubmitting = false; this._bodyElID = 'BODY'; if (config.bodyElID) { this._bodyElID = config.bodyElID; } // set up validation key for uploads this._stockVKey = false; this.getVKey(); // stop propagating key events YAHOO.util.Event.addListener(this._config.element, "keyup", FIRSTCLASS.util.Message.eatKeys); YAHOO.util.Event.addListener(this._config.element, "keydown", FIRSTCLASS.util.Message.eatKeys); // set up callbacks var callback = { success: function(o) { that.onOpen(o.responseText); }, failure: function(o) { window.clearInterval(this._touchTimer); this._touchTimer = null; if (that._config.callback.onFail) { var obj = {}; if (o && o.responseText) { try { obj = FIRSTCLASS.lang.JSON.parse(o.responseText); } catch (e) { } } that._config.callback.onFail(obj); } else { alert(FIRSTCLASS.locale.editor.misc.cantopen); } } }; // open the item FIRSTCLASS.util.net.asyncRequest("GET", url[0], callback); }; FIRSTCLASS.util.Message.prototype.getVKey = function() { var that = this; var rc = this._stockVKey; if (FIRSTCLASS.session.server.requiresvkeys) { var vkeycb = function(key) { that._stockVKey = key; }; FIRSTCLASS.util.net.getVKey(vkeycb); } this._stockVKey = false; return rc; }; FIRSTCLASS.util.Message.prototype._onOpenFunctionFactory = function(config) { var that = config.that; var nm = config.name; var f = function() { that.deleteName(that._nameContainer, that.getIndexForRow(that._validatedNames, nm)); }; return f; }; // handle response to object edit/create FIRSTCLASS.util.Message.prototype.onOpen = function(messageText) { var that = this; // check if content is editable var success = (messageText.indexOf("= 0) ? true : false; if (this._config.callback.onLoaded) { this._config.callback.onLoaded(success); } if (success) { // hide edit element FIRSTCLASS.ui.Dom.setInnerHTML(this._config.element, this.prepareContent(messageText)); if (this._config.bodyType == "HTML") { var domEl = FIRSTCLASS.ui.Dom.getChildByIdName(this._bodyElID, this._config.element); if (!domEl) { domEl = this._bodyElID; } this.openEditor(domEl); } var cancelBtn = FIRSTCLASS.ui.Dom.getChildByIdName("fcDocFormCancel", this._config.element); var saveBtn = FIRSTCLASS.ui.Dom.getChildByIdName("fcDocFormSave", this._config.element); var tags = FIRSTCLASS.ui.Dom.getChildByIdName("fcTagContainer", this._config.element); var oldtags = ""; if (this._config.row) { oldtags = this._config.row.tags; } else { var tagEl = FIRSTCLASS.ui.Dom.getChildByIdName("fcTags", this._config.element); if (tagEl) { oldTags = tagEl.value; } } if (tags && FIRSTCLASS.apps.Workflows && FIRSTCLASS.apps.Workflows.Tags) { window.setTimeout(function() { tags.innerHTML = "
"; that.tagconfig = { domElement:tags.firstChild, item: FIRSTCLASS.ui.parseServerTags(oldtags), hidesuggestions:true, destField: tags.lastChild, showonconfig:true }; FIRSTCLASS.apps.Workflows.Tags.reconfigure(that.tagconfig); }, 10); } // set up form event hooks this._editForm = FIRSTCLASS.ui.Dom.getChildByIdName(this._config.formElId, this._config.element); if (this._editForm) { var newUrl = this._editForm.getAttribute("fcurl"); if (newUrl) { this._config.baseURL = newUrl; } if (saveBtn) { YAHOO.util.Event.addListener(saveBtn, "click", function(evt) { if (!that._currentlySubmitting) { that._currentlySubmitting = true; that.onSubmit(); } }); } this._editForm.onsubmit = function() { return false; }; if (cancelBtn) { YAHOO.util.Event.addListener(cancelBtn,"click",function() { that.onCancel(that); }); } // addressing if (this._config.objType == FIRSTCLASS.objTypes.message) { var validatedNames = YAHOO.util.Dom.getElementsByClassName('fcValidatedName', "", this._editForm); this._nameContainer = FIRSTCLASS.ui.Dom.getChildByClassName('fcValidatedNamesTo', this._editForm); if (this._nameContainer) { this._nameTable = this._nameContainer.firstChild; if (!this._config.showAddr) { YAHOO.util.Dom.setStyle(this._nameContainer, 'display', 'none'); YAHOO.util.Dom.setStyle(this._nameContainer.previousSibling, 'display', 'none'); } } if (this._config.showAddr) { this._validatedNames = validatedNames; for (var i in validatedNames) { var nm = validatedNames[i]; var cont = document.createElement("div"); var button = new YAHOO.widget.Button({label:FIRSTCLASS.locale.workflows.sendto.email.remove, container:cont}); button.addListener("click", this._onOpenFunctionFactory({that:that, name:nm})); nm.lastChild.appendChild(cont); } var inputRow = FIRSTCLASS.ui.Dom.getChildByClassName("fcNameValInput", this._editForm); var addButton = new YAHOO.widget.Button(inputRow.lastChild.firstChild); this._inputRow = inputRow.cloneNode(true); var nameButtons = YAHOO.util.Dom.getElementsByClassName('fcNameAddButton', "", this._editForm); var nameInputs = YAHOO.util.Dom.getElementsByClassName('fcNameValTo', "", this._editForm); this.inputs = { "to": nameInputs[0] }; addButton.addListener("click", function(evt) { that.addName(that._nameContainer, nameInputs[0].value,true); }); YAHOO.util.Event.addListener(nameInputs[0], "keyup", function(evt) { if (evt.keyCode == 13 || (nameInputs[0].value.indexOf(that._autoCompleteLastSearch) != 0 || nameInputs[0].value.length < that._autoCompleteLastSearch.length)) { that.addName(that._nameContainer, nameInputs[0].value,false); } }); YAHOO.util.Event.addListener(nameInputs[0], "blur", function(evt) { if (nameInputs[0].value.length > 0) { that.addName(that._nameContainer, nameInputs[0].value,true); } }); } } // show it if (this._config.bodyType !== "HTML") { // post-display callback - non-styled case YAHOO.util.Dom.removeClass(this._config.element,"fcHidden"); if (this._config.callback.onDisplay) { this._config.callback.onDisplay(); } } // keep it open this._touchTimer = window.setInterval(function() { that.keepOpen(); }, 300000); } } }; // touch server object to keep it open FIRSTCLASS.util.Message.prototype.keepOpen = function() { var that = this; var callback = { success: function(o) { that._touches.push(true); }, failure: function(o) { that._touches.push(false); } }; var url = FIRSTCLASS.lang.ensureSlashUrl(this._config.baseURL) + "__Touch"; FIRSTCLASS.util.net.asyncRequest("GET",url,callback); }; // stop key events propagating up past edit frame FIRSTCLASS.util.Message.eatKeys = function(evt) { YAHOO.util.Event.stopPropagation(evt); }; // instantiate the editor FIRSTCLASS.util.Message.prototype.openEditor = function(textEl) { CKEDITOR.plugins.addExternal('bfimage', '../cke_plugins/bfimage/', 'bfimage.js'); CKEDITOR.plugins.addExternal('bflink', '../cke_plugins/bflink/', 'bflink.js'); CKEDITOR.plugins.addExternal('bfembed', '../cke_plugins/bfembed/', 'bfembed.js'); CKEDITOR.plugins.addExternal('bfinsert', '../cke_plugins/bfinsert/', 'bfinsert.js'); if (CKEDITOR.instances.BODY) { CKEDITOR.remove(CKEDITOR.instances.BODY); } this._editor = CKEDITOR.replace(textEl, this._ckConfig); this._editor.message = this; this._editor.on('instanceReady', function() { this.onEditorLoaded(); this.registerEditorEvents(); }, this); }; // close and destroy FIRSTCLASS.util.Message.prototype.closeEditor = function() { if (this._editor !== null) { this._editor.destroy(); this._editor = null; } }; // capture configuration FIRSTCLASS.util.Message.prototype.configure = function(config) { // save config object with defaults this._config = { callback : {}, objType : FIRSTCLASS.objTypes.message, nvoptions : null, bodyType : 'plain', initWidth : '99%', showAddr : true, maxImage : 0 }; FIRSTCLASS.lang.shallowCopyObjData(this._config, config); if (this._config.objType == FIRSTCLASS.objTypes.odocument) { this._config.formID = config.formID || 20501; } else { this._config.formID = config.formID || 141; } if (!this._config.initHeight && this._config.element && this._config.element.offsetHeight) { this._config.initHeight = this._config.element.offsetHeight; } // apply url options var param = this._config.baseURL.indexOf("?"); if (param != -1) { this._urlParams = this._config.baseURL.slice(param+1); this._config.baseURL = this._config.baseURL.slice(0,param); } if (this._config.params) { if (this._urlParams) { this._urlParams += "&" + config.params; } else { this._urlParams = config.params; } } if (!config.overrideForms) { if (this._urlParams) { this._urlParams += "&Templates=Forms"; } else { this._urlParams = "Templates=Forms"; } } else { if (this._urlParams) { this._urlParams += config.overrideForms; } else { this._urlParams = config.overrideForms; } } this._ckConfig = this.configEditor(); }; // configure the editor component FIRSTCLASS.util.Message.prototype.configEditor = function() { // defaults var ckc = { startupFocus: true, resize_enabled: false, dialog_backgroundCoverOpacity: 0.0, dialog_backgroundCoverColor: '#FFFFFF', colorButton_enableMore: true, skin: 'bf1_1,../cke_skins/bf1_1/', undoStackSize : 50, removePlugins: 'flash,newpage,pagebreak,save,scayt,templates,wsc,image,link', extraPlugins : 'bfimage,bflink,bfembed,bfinsert', disableNativeSpellChecker: false, entities: false }; // suppress element path for non-wiki if (this._config.tbType != 'wiki') { ckc.removePlugins += ',elementspath'; } this.configToolbar(this._config.tbType, ckc); // language ckc.language = 'en-us'; if (FIRSTCLASS.session.language) { ckc.language = FIRSTCLASS.session.language; } // styles var resetPath = FIRSTCLASS.session.templatebase + '/' + FIRSTCLASS.session.ui.yuifolder + '/build/reset-fonts-grids/reset-fonts-grids.css'; var fcPath = FIRSTCLASS.session.ui.fcbase.absolute + '/css/firstclass.pcss' var ckePath = FIRSTCLASS.session.templatebase + '/cke_skins/bf1_1/contents.css'; ckc.contentsCss = [resetPath, fcPath, ckePath]; ckc.format_tags = 'p;h1;h2;h3;h4'; // dimensions ckc.height = this._config.initHeight; ckc.width = this._config.initWidth; return ckc; }; // set up toolbar based on tbType of passed-in config FIRSTCLASS.util.Message.prototype.configToolbar = function(type, config) { var that = this; if (!type) { type = 'Full'; } config.insertmenuitems = { bfimage: { label: FIRSTCLASS.locale.editor.insertmenu.image, command: 'bfimage' }, link: { label: FIRSTCLASS.locale.editor.insertmenu.link, command: 'link' }, wikilink: { label: FIRSTCLASS.locale.editor.insertmenu.wikilink, command: 'wikilink' }, doclink: { label: FIRSTCLASS.locale.editor.insertmenu.doclink, command: 'doclink' }, threadlink: { label: FIRSTCLASS.locale.editor.insertmenu.threadlink, command: 'threadlink' }, userlink: { label: FIRSTCLASS.locale.editor.insertmenu.userlink, command: 'userlink' }, commlink: { label: FIRSTCLASS.locale.editor.insertmenu.commlink, command: 'commlink' }, bfembed: { label: FIRSTCLASS.locale.editor.insertmenu.bfembed, command: 'bfembed' }, table: { label: FIRSTCLASS.locale.editor.insertmenu.table, command: 'table' }, newwiki: { label: FIRSTCLASS.locale.editor.insertmenu.newwiki, command: 'newwiki' }, newdoc: { label: FIRSTCLASS.locale.editor.insertmenu.newdoc, command: 'newdoc' }, horizontalrule: { label: FIRSTCLASS.locale.editor.insertmenu.rule, command: 'horizontalrule' }, smiley: { label: FIRSTCLASS.locale.editor.insertmenu.smiley, command: 'smiley' }, blockquote: { label: FIRSTCLASS.locale.editor.insertmenu.quote, command: 'blockquote' }, bflinkmenu: { label: FIRSTCLASS.locale.editor.insertmenu.linkmenu, name: 'bflinkmenu', items: 'link,wikilink,doclink,threadlink,userlink,commlink' }, bfnewmenu: { label: FIRSTCLASS.locale.editor.insertmenu.newmenu, name: 'bfnewmenu', items: 'newwiki,newdoc' }, Insert: { label: FIRSTCLASS.locale.editor.insertmenu.insert, name: 'Insert' } }; switch (type) { case 'wiki': config.toolbar = 'wiki'; config.toolbar_wiki = [ ['Undo','Redo'], ['PasteText','PasteFromWord'], ['Insert','BFUnlink'], ['NumberedList','BulletedList'], ['Outdent','Indent','Blockquote'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'], ['SelectAll','RemoveFormat'], ['Print','Preview','Source','Maximize','ShowBlocks'], '/', ['Bold','Italic','Underline','Strike','Subscript','Superscript'], ['Format','Font','FontSize'], ['TextColor','BGColor'] ]; config.insertmenuitems['Insert'].items = 'bfimage,bflinkmenu,bfembed,table,newwiki,newdoc,horizontalrule,smiley'; break; case 'reply': config.toolbar = 'reply'; config.toolbar_reply = [ ['Undo','Redo'], ['PasteText','PasteFromWord'], ['Bold','Italic','Underline','Strike'], ['Font','FontSize'], ['Insert', 'BFUnlink'], ['NumberedList','BulletedList'] ]; config.insertmenuitems['Insert'].items = 'bfimage,bflinkmenu,bfembed,table,smiley'; break; case 'blog': config.toolbar = 'blog'; config.toolbar_blog = [ ['Undo','Redo'], ['PasteText','PasteFromWord'], ['Bold','Italic','Underline','Strike','Subscript','Superscript'], ['Format','Font','TextColor'], ['Insert','BFUnlink'], ['NumberedList','BulletedList'], ['SelectAll','RemoveFormat'], ['Print','Preview','Source','Maximize','ShowBlocks'] ]; config.insertmenuitems['Insert'].items = 'bfimage,bflinkmenu,bfembed,table,horizontalrule,smiley'; break; case 'sendto': config.toolbar = 'sendto'; config.toolbarStartupExpanded = false; config.toolbar_sendto = [ ['Undo','Redo'], ['Insert', 'BFUnlink'] ]; config.insertmenuitems['Insert'].items = 'bfimage,bflinkmenu'; break; default: config.toolbar = 'Full'; config.toolbar_Full = [ ['Undo','Redo'], ['PasteText','PasteFromWord'], ['Bold','Italic','Underline','Strike'], ['Font','FontSize'], ['Insert','BFUnlink'], ['NumberedList','BulletedList'] ]; config.insertmenuitems['Insert'].items = 'bfimage,bflinkmenu,bfembed,table,smiley'; } }; // external interface for closing FIRSTCLASS.util.Message.prototype.destroy = function() { if (this._editor) { this.closeEditor(); this._editor = null; } }; // prepare incoming HTML for display FIRSTCLASS.util.Message.prototype.prepareContent = function (text) { if (text.indexOf('id="BODY"') > 0) { return FIRSTCLASS.util.url.expandImageUrls(this._config.baseURL, text); } else { return text; } }; FIRSTCLASS.util.Message.prototype.saveCheckpoint = function() { this.onSubmit(true); }; FIRSTCLASS.util.Message.prototype.onSubmit = function(incremental, callback) { if (!incremental) { window.clearInterval(this._touchTimer); } if (this._editForm && this._editForm.action) { if (this._config.bodyType == "plain") { this._editForm.BODY.value = FIRSTCLASS.lang.mlesc(this._editForm.BODY.value); } var that = this; var action = this._editForm.action; var parts = action.split("?"); action = parts[0]; if (incremental) { action += "?Close=-1"; } else { if (this._config.op == FIRSTCLASS.opCodes.FormNew && this._tbType == "wiki") { action += "?Close=5&Templates=JS&JSON=2"; } else if (action.indexOf("__Attach") == -1) { action += "?Close=0&Clear=0&Templates=JS&JSON=2"; } else { action += "?Close=0&Clear=0&Templates=JS"; } } if (this._config.dontClear) { action += "&Clear=0"; } if (typeof this._config.callback.validate != "undefined") { if (this._config.callback.validate() === false) { this._currentlySubmitting = false; return; } } var saveCB = { success: function(a) { if (that._config.callback.onSave && !incremental) { that._config.callback.onSave(a); } if (callback) { callback.completed(); } YAHOO.util.Connect.resetDefaultHeaders(); }, failure: function(a) { if (that._config.callback.onFail && !incremental) { that._config.callback.onFail(a); } if (callback) { callback.completed(); } }, upload: function(eventType, args) { if (that._config.callback.onSave && !incremental) { that._config.callback.onSave(eventType); } if (callback) { callback.completed(); } YAHOO.util.Connect.resetDefaultHeaders(); } }; if (incremental) { this._editForm["FieldID:8101=LITERALSTRING"].value = "Auto-saved"; } // grab attachment list, then grab content, audit attachments, and save that.getAttachmentList(function(attachments, success) { if (success) { that._attachmentList = attachments; } else { that._attachmentList = []; } that.getContentFromForm(); if (!incremental) { that.deleteUnusedAttachments(); } FIRSTCLASS.util.submitForm(that._editForm, that._config.upload, saveCB, action); }); } return; }; // increment ref-count for attachment with passed-in name FIRSTCLASS.util.Message.prototype.addAttachRef = function(attachName) { if (this._attachmentList) { for (var idx = 0; idx < this._attachmentList.length; idx++) { var attachment = this._attachmentList[idx]; if (attachment.name.toLowerCase().localeCompare(attachName.toLowerCase()) === 0) { if (attachment.refCount) { attachment.refCount++; } else { attachment.refCount = 1; } return; } } } }; // delete all embedded attachments with zero ref-count FIRSTCLASS.util.Message.prototype.deleteUnusedAttachments = function() { var url = this._config.baseURL, deleteUrl = ""; if (url.charAt(url.length-1) != '/') { url = url.slice(0,url.lastIndexOf('/')); url = url.slice(0,url.lastIndexOf('/')+1); } if (url.indexOf(FIRSTCLASS.opCodes.FormEdit) > 0) { url = url.slice(0,url.lastIndexOf(FIRSTCLASS.opCodes.FormEdit)); } if (this._attachmentList) { for (var idx = 0; idx < this._attachmentList.length; idx++) { var attachment = this._attachmentList[idx]; if (attachment.embed && !attachment.refCount) { deleteUrl = url + attachment.name + "?Delete=1&Close=-1"; FIRSTCLASS.util.net.asyncRequest('GET',deleteUrl); } } } }; // on save, filter out various kinds of crud from the HTML stream FIRSTCLASS.util.Message.prototype.filterContent = function(html) { // allow inline styles for wikis if (this._tbType !== "wiki") { // style tags html = html.replace(/]*>[\s\S]*?<\/style[^>]*>/gi, ''); // mso classes html = html.replace(/ class="Mso[a-zA-Z]*"/gi, ''); //ms m: tags html = html.replace(/]*>[\s\S]*?<\/m:[^>]*>/gi, ''); // xml defs html = html.replace(/]*>[\s\S]*?<\/xml[^>]*>/gi, ''); // comments html = html.replace(//gi, ''); } else { // just the if's html = html.replace(//gi, ''); } // terminate wacky embed divs if (YAHOO.env.ua.webkit) { html = html.replace(/]*fcEmbed[^>]*>/gi, "$&"); } // external stylesheets html = html.replace(/]*>/gi, ''); // meta tags html = html.replace(/]*>/gi, ''); return html; }; // clear all current content from the editor FIRSTCLASS.util.Message.prototype.clearContent = function() { if (this._config.bodyType != 'HTML') { if (this._editForm.BODY) { this._editForm.BODY.value = ''; } } else { if (this._editor) { this._editor.setData(""); } } }; FIRSTCLASS.util.Message.prototype.getContentFromForm = function() { if (this._config.bodyType != 'HTML') { if (this._editForm.BODY) { var text = this._editForm.BODY.value; var lines = text.split("\n"); YAHOO.util.Dom.setStyle(this._editForm.BODY, "display", "none"); var saving = document.createElement("div"); saving.innerHTML = FIRSTCLASS.locale.editor.misc.prog; this._editForm.BODY.parentNode.appendChild(saving); this._editForm.BODY.value = this.filterContent(lines.join("
")); } } else { // get root content node and process it and its kids var baseEl = this._editor.document.getBody(); this._formUrlObj = FIRSTCLASS.util.url.decomposeUrl(this._editForm.action); this.procBodyElements(baseEl); this._editor.updateElement(); var line = this._editForm.BODY.value.split("\n"); this._editForm.BODY.value = this.filterContent(line.join(" ")); var field = {}; var fields = null; fields = this._editForm.elements; for (var i in fields) { field = fields[i]; if (field && field.id && (typeof field.id === "string")) { if (field.id.indexOf("BODY_") >= 0 || field.id.indexOf("BODYCONTAINER") >= 0) { field.value = ""; } } } } this.prepareTags(); }; FIRSTCLASS.util.Message.prototype.procBodyElements = function(inEl) { if (inEl.getName) { switch(inEl.getName()) { case 'img': this.procImageElement(inEl); break; case 'a': this.procAnchorElement(inEl); break; case 'div': this.procDivElement(inEl); break; } } // process child nodes if (inEl.getChildCount) { for (var n = 0; n < inEl.getChildCount(); n++) { if (inEl.getChild) { this.procBodyElements(inEl.getChild(n)); } } } }; FIRSTCLASS.util.Message.prototype.procImageElement = function(el) { var imgObj = FIRSTCLASS.util.url.decomposeUrl(el.getAttribute('src')); var fcattrs = el.getAttribute('fcattrs'); var fcid = el.getAttribute('fcid'); var isEmbed = ((fcid == 'fcestart') && (typeof fcattrs != 'undefined')) ? true : false; var isAttach = ((imgObj.path.length > 0) && (imgObj.path[0] == "Login")) ? true : false; if (isEmbed) { var attrs = fcattrs.split(';'); this.addAttachRef('embed' + attrs[0] + '.html'); var divEl = this._editor.document.createElement('div'); divEl.setAttribute('class', 'fcEmbed'); divEl.setAttribute('fcid', 'fcestart'); divEl.setAttribute('fcattrs', fcattrs); divEl.replace(el); el = divEl; } else if (isAttach) { el.setAttribute('_cke_saved_src', imgObj.path[imgObj.path.length - 1]); this.addAttachRef(imgObj.path[imgObj.path.length - 1]); } }; FIRSTCLASS.util.Message.prototype.procAnchorElement = function(el) { var dstObj = {}; var dstStr = el.getAttribute('_cke_saved_href'); var fcth = el.getAttribute('fcth'); if (!dstStr) { dstStr = el.getAttribute('href'); } if (dstStr) { dstObj = FIRSTCLASS.util.url.decomposeUrl(dstStr); // check for attribute on anchor if ((fcth !== null) && (typeof fcth !== 'undefined')) { el.setAttribute('_cke_saved_href', dstObj.path[dstObj.path.length - 1]); this.addAttachRef(dstObj.path[dstObj.path.length - 1]); } else { // test for local link and knock out target if so var myUrlObj = FIRSTCLASS.util.url.decomposeUrl(FIRSTCLASS.session.domain.toUpperCase()); if (dstObj.server && dstObj.server.toUpperCase() == myUrlObj.server) { el.removeAttribute('target'); } } } }; FIRSTCLASS.util.Message.prototype.procDivElement = function(el) { // convert old-style embed div-with-image to div-only if (el.hasClass('fcEmbed')) { if (el.getFirst() && el.getFirst().getName() == 'img') { this.procImageElement(el.getFirst()); } el.setHTML(''); } }; FIRSTCLASS.util.Message.prototype.prepareTags = function() { var tags = $("fcTags"); var otags = $("fcTagOriginal"); //var dtags = $("fcTagDiff"); var thetag; if (tags && otags) { var atags = tags.value.split(","); for (var i in atags) { thetag = FIRSTCLASS.lang.string.trim(atags[i]); if (thetag.charAt(0) == "\"" || thetag.charAt(0) == "\'") { thetag = thetag.substr(1); } if (thetag.charAt(thetag.length-1) == "\"" || thetag.charAt(thetag.length-1) == "\'") { thetag = thetag.substr(0, thetag.length-1); } atags[i] = thetag; } tags.value = atags.join(","); /*var adtags = []; for (var j in atags) { thetag = FIRSTCLASS.lang.string.trim(atags[j]); if (otags.value.indexOf(thetag) < 0 ) { adtags.push(thetag); } } dtags.value = adtags.join(",");*/ } }; FIRSTCLASS.util.Message.prototype.onCancel = function() { var that = this; var paramStr = "?Quit=1"; window.clearInterval(this._touchTimer); if (this._config.op == FIRSTCLASS.opCodes.MemForm) { if (that._config.callback.onCancel) { that._config.callback.onCancel(); } } else { if ((this._config.objType == FIRSTCLASS.objTypes.message) || (this._config.op == FIRSTCLASS.opCodes.FormNew) || (this._config.op == FIRSTCLASS.opCodes.MemForm)) { paramStr = "?Delete=1"; } var cancelCallback = { success: function(o) { if (that._config.callback.onCancel) { that._config.callback.onCancel(); } }, failure: function(o) { alert(FIRSTCLASS.locale.editor.misc.nocancel); if (that._config.callback.onCancel) { that._config.callback.onCancel(); } } }; if (this._editForm) { var url = this._editForm.getAttribute('fcUrl'); url = FIRSTCLASS.lang.removeSlashUrl(url) + paramStr; var request = FIRSTCLASS.util.net.asyncRequest("GET", url, cancelCallback); } } }; FIRSTCLASS.util.Message.prototype.preProcessNodes = function() { // function to walk nodes and insert embed placeholders var processNode = function(node, cfg) { if (node.tagName == "DIV" && node.className == "fcEmbed") { var image = cfg.image.cloneNode(true); image.className = node.className; image.setAttribute('fcid', node.getAttribute('fcid')); image.setAttribute('fcattrs', node.getAttribute('fcattrs')); node.parentNode.replaceChild(image, node); } for (var c = 0; c < node.childNodes.length; c++) { processNode(node.childNodes[c], cfg); } }; // find base node if (this._editor && this._editor.document) { var doc = this._editor.document; var baseEl = null; if (doc) { baseEl = doc.getBody().$; var theImage = doc.createElement('img').$; theImage.setAttribute('src', FIRSTCLASS.session.ui.fcbase.absolute + "/images/EmbedActiveContent.gif"); processNode(baseEl, { image: theImage, message: this }); } } }; FIRSTCLASS.util.Message.prototype.onEditorLoaded = function() { // notify owner if (this._config.callback.onDisplay) { this._config.callback.onDisplay(); } // insert quote if any if (this._config.quoteText) { this.insertQuote(this._config.quoteText, this._config.quoteAuth); } // prepare content this.preProcessNodes(); this.updateEmbedIndex(); // nuke bogus context menu items var listener = false, rc = false, image = this._editor.document.createElement( 'img' ); for (var i in this._editor.contextMenu._.listeners) { listener = this._editor.contextMenu._.listeners[i]; if (typeof listener == 'function') { rc = listener.call(this, image, this._editor.getSelection()); if (rc && rc.image) { this._editor.contextMenu._.listeners.splice(i,1); } rc = false; } } var that = this; window.setTimeout(function() { // set focus after decoupling delay if (that._editForm && that._config.op != FIRSTCLASS.opCodes.Reply) { var subj = that._editForm.Subject; if (subj) { subj.focus(); } else { that._editor.focus(); } } else { that._editor.focus(); } }, 500); }; FIRSTCLASS.util.Message.prototype.registerEditorEvents = function() { this._editor.on('key', function(evt) { // trap alt-arrows if (evt.data.altKey) { if ((evt.data.keyCode == 18) || (evt.data.keyCode == 39)) { evt.stop(); } } if (evt.data.metaKey) { if ((evt.data.keyCode == 37) || (evt.data.keyCode == 39)) { evt.stop(); } } // report typing to owner if (this._config.callback.onTyping) { this._config.callback.onTyping(evt); } }, this); }; // walk nodes to trap highest embed index FIRSTCLASS.util.Message.prototype.updateEmbedIndex = function() { // recursive index finder var getMaxEmbedIdx = function(node, index) { var nIdx = 0; var attrs; var attrVals = []; if (node.tagName == "IMG") { attrs = node.getAttribute('fcattrs'); if (attrs && node.getAttribute('fcid') === 'fcestart') { attrVals = attrs.split(';'); nIdx = attrVals[0] - 0; if (nIdx > index) { index = nIdx; } } } for (var c = 0; c < node.childNodes.length; c++) { index = getMaxEmbedIdx(node.childNodes[c], index); } return index; }; // find base node var baseEl = this._config.element; if (this._editor.document.getBody()) { baseEl = this._editor.document.getBody().$; } this._embedIdx = getMaxEmbedIdx(baseEl, this._embedIdx); }; // OpenDialog - open a new editor dialog // Editor dialog config: // .title - "window title" // .tbid - toolbar container id (used to set up css) // .tb - toolbar config // .body - html body for non-toolbar dialogs (must include a tb container with id = tbid if including body and toolbar) // .width - sets the width of the dialog, surprisingly // .callback: // .done() // .cancel() // FIRSTCLASS.util.Message.prototype.openDialog = function(config) { var that = this; if (this._dialog !== null) { // close current this.closeDialog(); } this._dialog = {}; this._dialog.config = {}; YAHOO.lang.augmentObject(this._dialog.config, config); // this._dialog.editEl = this._editor.currentElement[0]; this._dialog.el = document.createElement('div'); this._dialog.el.setAttribute('style','visibility:hidden'); this._dialog.el.setAttribute('id','fcEditorDialog'); var header = document.createElement('div'); var body = document.createElement('div'); // insert body if any if (this._dialog.config.body) { body.innerHTML = this._dialog.config.body; } // insert toolbar into body or selected subelement if (this._dialog.config.tb) { var tbarCont = document.createElement('div'); tbarCont.id = this._dialog.config.tbid + '_toolbar'; var ins = body; if (this._dialog.config.body) { var tbc = FIRSTCLASS.ui.Dom.getChildByIdName(this._dialog.config.tbid); if (tbc) { ins = tbc; } } ins.appendChild(tbarCont); this._dialog.tbar = new YAHOO.widget.Toolbar(tbarCont, this._dialog.config.tb); this._dialog.tbar.editor_el = this._dialog.editEl; var fm = this._dialog.tbar.getButtonByValue('fontname'); if (fm) { fm._menu.beforeShowEvent.subscribe(function() { this._menu.cfg.setProperty('zindex',3); },fm,true); } } this._config.element.appendChild(this._dialog.el); // create the dialog var buttons = []; if (typeof this._dialog.config.cancel !== 'undefined') { buttons.push( { text: FIRSTCLASS.locale.editor.textstyle.cancel, handler: function() { that[that._dialog.config.cancel](); }, isDefault:false }); } if (typeof this._dialog.config.done !== 'undefined') { buttons.push( { text:FIRSTCLASS.locale.editor.textstyle.done, handler: function() { that[that._dialog.config.done](); }, isDefault: true }); } var dlgConfig = { draggable: false, visible: false, constraintoviewport : true, postmethod : "manual", xy: [ this._config.element.offsetHeight/2 - 100, this._config.element.offsetWidth/2-200 ], iframe: (navigator.userAgent.toLowerCase().indexOf("msie") > -1), buttons : buttons }; if (this._dialog.config.width) { dlgConfig.width = this._dialog.config.width; } this._dialog.dlg = new YAHOO.widget.Dialog("fcEditorDialog", dlgConfig); if (this._dialog.config.title) { this._dialog.dlg.setHeader(this._dialog.config.title); } if (body) { this._dialog.dlg.setBody(body); } this._dialog.dlg.render(); this._dialog.dlg.show(); if (typeof this._dialog.config.cancel !== 'undefined') { this._dialog.dlg.cancelEvent.subscribe(function() { that[that._dialog.config.cancel](); }); } return; }; // quote functions FIRSTCLASS.util.Message.prototype.openQuoteDialog = function() { var dlgCfg = {}; var that = this; dlgCfg.title = FIRSTCLASS.locale.editor.quote.title; dlgCfg.cancel = 'closeDialog'; dlgCfg.done = 'quoteDone'; var html = []; html.push("
"); html.push("
"); html.push("
"); html.push("
"); dlgCfg.body = html.join(""); if (YAHOO.env.ua.ie) { dlgCfg.width = '415px'; } this.openDialog(dlgCfg); window.setTimeout( function() { var contentEl = FIRSTCLASS.ui.Dom.getChildByIdName('fcQuoteField', that._dialog.el); contentEl.focus(); }, 500); return; }; FIRSTCLASS.util.Message.prototype.quoteDone = function() { var contentEl = FIRSTCLASS.ui.Dom.getChildByIdName('fcQuoteField', this._dialog.el); if (contentEl) { this.insertQuote(contentEl.value); } this.closeDialog(); return; }; FIRSTCLASS.util.Message.prototype.insertQuote = function(text, from) { var html = ""; if (from) { html += "" + from + " writes:
"; } if (text) { html += "
“" + text + "”


"; } this._editor.insertHtml(html); }; FIRSTCLASS.util.Message.prototype.closeDialog = function() { if (this._dialog !== null) { this._dialog.dlg.destroy(); this._dialog = null; } }; // Get the current object's attachment list and return it if possible. Callback params are (attachments, success), // where attachments is the JSON array returned by IS, and success is a boolean indicating the status of the request. // On failure, attachments will be an empty array. FIRSTCLASS.util.Message.prototype.getAttachmentList = function(callback) { var attachments = []; var url = FIRSTCLASS.lang.removeSlashUrl(this._editForm.getAttribute('fcurl')); url += "?Show=2&Templates=JS&JSON=2&Close=-1&" + FIRSTCLASS.ui.Dom.getCurrTimestamp(); var req = FIRSTCLASS.util.net.asyncRequest('GET', url, { success:function (response) { // parse JSON data var msgData = []; try { msgData = YAHOO.lang.JSON.parse(response.responseText); } catch(x) { if (callback) { callback(attachments, false); } return; } if (msgData.attachments) { for (var idx = 0; idx < msgData.attachments.length; idx++) { attachments.push(msgData.attachments[idx]); } } if (callback) { callback(attachments, true); return; } }, failure:function (response) { if (callback) { callback(attachments, false); } } }); }; // test for attachment available in item FIRSTCLASS.util.Message.prototype.testForAttachment = function(name, url, callback) { var that = this; var notYets = 0; // set up timer to poll for selected attachment var pollT = window.setInterval(function() { that.getAttachmentList(function(attachments, success) { if (success) { for (var idx = 0; idx < attachments.length; idx++) { var attachment = attachments[idx]; if (attachment.name.localeCompare(name) === 0) { window.clearInterval(pollT); if (callback) { callback(url, true); } return; } } if (notYets++ > 5) { window.clearInterval(pollT); if (callback) { callback(null, false); } } } else { window.clearInterval(pollT); if (callback) { callback(null, false); } } }); },5000); }; FIRSTCLASS.util.Message.prototype.getMessageId = function() { var msgid = null; if (this._editForm) { var url = this._editForm.getAttribute('fcurl'); var start = url.indexOf("/S") + 1; if (start >= 0) { var end = url.indexOf("/",start); if (end >= 0) { msgid = url.slice(start, end); } else { msgid = url.slice(start); } } } return msgid; }; // message addressing functions FIRSTCLASS.util.Message.prototype.autoCompleteSelectHandler = function(sType, aArgs, where) { var that = this; var rowData = aArgs[2]; var addString = rowData[1].cid; var icon = rowData[1].icon; var clientid = rowData[1].cid; var online = rowData[1].online; var addname = rowData[1].name; FIRSTCLASS.util.Form.add(that._config.baseURL, addString, 4, 1000, { onComplete:function() { var myIndex = that._validatedNames.length; var tmp = that._nameTable.insertRow(myIndex); YAHOO.util.Dom.addClass(tmp, "fcValidatedName"); if (online) { YAHOO.util.Dom.addClass(tmp, "fcNameOnline"); } tmp.clientid = clientid; var tmp2 = document.createElement("td"); var tmp3 = document.createElement("td"); tmp.appendChild(tmp2); tmp.appendChild(tmp3); tmp2.innerHTML=""+addname; var cont = document.createElement("div"); var button = new YAHOO.widget.Button({label:FIRSTCLASS.locale.workflows.sendto.email.remove, container:cont}); that._validatedNames.push(tmp); button.addListener("click", function(evt) { that.deleteName(where,that.getIndexForRow(that._validatedNames, tmp)); }); tmp3.appendChild(cont); that.refreshNameInput(); if (that._config.callback.onNameValidate) { that._config.callback.onNameValidate(); } that._isNameValidating = false; }, onFailure:function(err) { that._isNameValidating = false; alert(FIRSTCLASS.locale.editor.misc.addrfail); // that._autoComplete.destroy(); } }); }; FIRSTCLASS.util.Message.prototype.addName = function(where, inputValue, showNoFindAlert) { /*if (this._isNameValidating) { return; }*/ this._isNameValidating = true; var that = this; FIRSTCLASS.util.Form.validateName(that._config.baseURL, inputValue, 4, 1000, { onComplete: function(obj) { var addString; var icon; var clientid; var online; var addname; switch(obj.match) { case "multi": var dsDef = obj.dataSource.getYAHOOWidgetDataSource('name', true, FIRSTCLASS.util.Form.nameValCompare); var ac = FIRSTCLASS.ui.Dom.getChildByClassName("fcNameValAutoComplete", that._editForm); if (!that._autoComplete) { that._autoComplete = new YAHOO.widget.AutoComplete(that.inputs.to,ac,dsDef.dataSource); that._autoCompleteDataSource = obj.dataSource; that._autoCompleteLastSearch = inputValue; //that._autoComplete.maxResultsDisplayed = 5; //that._autoComplete.typeAhead = true; //that._autoComplete.useShadow = true; that._autoComplete.formatResult = dsDef.formatResult; that._autoComplete.itemSelectEvent.subscribe(function(s,a) { that.autoCompleteSelectHandler(s,a, where); }); } else if (that._autoCompleteLastSearch != inputValue){ that._autoCompleteDataSource.loadData(obj.dataSource._data); that._autoCompleteLastSearch = inputValue; } that._autoComplete.sendQuery(obj.pattern); return; case "single": if (obj.item.nmattrs1.isperson) { addString = obj.item.cid; } else if (FIRSTCLASS.lang.isEmailAddress(obj.item.name)) { addString = obj.item.name; } else { return; } icon = obj.item.icon; clientid = obj.item.cid; online = obj.item.online; addname = obj.item.name; break; default: if (!FIRSTCLASS.lang.isEmailAddress(inputValue)) { if (showNoFindAlert) alert(FIRSTCLASS.locale.editor.dirlink.nomatch); return; } else { addString = inputValue; icon = "/Icons/9204"; clientid = "CID0"; online = false; addname = inputValue; } } FIRSTCLASS.util.Form.add(that._config.baseURL, addString, 4, 1000, { onComplete:function() { var myIndex = that._validatedNames.length; var tmp = that._nameTable.insertRow(myIndex); YAHOO.util.Dom.addClass(tmp, "fcValidatedName"); if (online) { YAHOO.util.Dom.addClass(tmp, "fcNameOnline"); } tmp.clientid = clientid; var tmp2 = document.createElement("td"); var tmp3 = document.createElement("td"); tmp.appendChild(tmp2); tmp.appendChild(tmp3); tmp2.innerHTML=""+addname; var cont = document.createElement("div"); var button = new YAHOO.widget.Button({label:FIRSTCLASS.locale.workflows.sendto.email.remove, container:cont}); that._validatedNames.push(tmp); button.addListener("click", function(evt) { that.deleteName(where,that.getIndexForRow(that._validatedNames, tmp)); }); tmp3.appendChild(cont); that.refreshNameInput(); if (that._config.callback.onNameValidate) { that._config.callback.onNameValidate(); } that._isNameValidating = false; }, onFailure:function(err) { that._isNameValidating = false; alert(FIRSTCLASS.locale.editor.misc.addrfail); } }); }, onFailure: function(obj) { } }, this._config.nvoptions); }; FIRSTCLASS.util.Message.prototype.deleteName = function(where, index) { // delete the name at index var that = this; if (index == -1) { return; } FIRSTCLASS.util.Form.deleteName(that._config.baseURL, 4, index, false, { onComplete:function(obj) { var rows = YAHOO.util.Dom.getElementsByClassName("fcValidatedName", "", where); var theRow = rows[index]; var tbody = theRow.parentNode; tbody.deleteRow(index); for (var i in that._validatedNames) { if (theRow == that._validatedNames[i]) { that._validatedNames.splice(i,1); break; } } }, onFailure:function(obj) { } }); }; FIRSTCLASS.util.Message.prototype.getIndexForRow = function(where, row) { for (var i in this._validatedNames) { if (this._validatedNames[i] == row) { return i; } } return -1; }; FIRSTCLASS.util.Message.prototype.refreshNameInput = function() { if (this._nameTable && this._inputRow) { var input = this._nameTable.lastChild.firstChild.firstChild.firstChild; input.value = ""; } }; YAHOO.register("fcFormUtils", FIRSTCLASS.util.Form, {version: "0.0.1", build: "1"});