window.dependentscripts = []; window.parsingfinished = false; window.allscriptsloaded = false; window.bootstrapfinished = false; window.dependents = new Hash(); Igloo.loadingScripts = []; function addscript(script,scriptid){ var elem = $('asset-'+scriptid); if (window.isJSPackaged == true) { var scriptLocation = script; var external = false; if (scriptLocation.charAt(0) != '/') { scriptLocation = '/cmedia/js/packages/' + script; } else { external = true; } var attached = Igloo.attachedScripts.contains(scriptLocation); if (!attached && external) { Array.each(Igloo.attachedScripts, function(attachedScript) { if (attachedScript.ciContains(scriptLocation)) { attached = true; } }) } if (!attached) { window.dependentscripts[scriptid] = 'loading'; Igloo.attachedScripts.include(scriptLocation); Igloo.loadingScripts.include(scriptid); new Asset.javascript(scriptLocation, { id: 'asset-'+scriptid, 'onload':function(){ Igloo.loadingScripts.erase(scriptid); window.fireEvent('scriptfinishedloading',scriptid); } }); } else { window.fireEvent('scriptfinishedloading',scriptid); } } else { if (!elem && !window.dependentscripts[scriptid]) { window.dependentscripts[scriptid] = 'loading'; var scriptLocation = script; if (scriptLocation.charAt(0) != '/') { scriptLocation = '/cmedia/js/' + script; } if (!Igloo.attachedScripts.contains(scriptLocation)) { Igloo.attachedScripts.include(scriptLocation); Igloo.loadingScripts.include(scriptid); new Asset.javascript(scriptLocation, { id: 'asset-'+scriptid, 'onload':function(){ Igloo.loadingScripts.erase(scriptid); window.fireEvent('scriptfinishedloading',scriptid); } }); } else { window.fireEvent('scriptfinishedloading',scriptid); } } } } function newaddscript(scriptid,elem){ var script = Igloo.bootstrapFileObj[scriptid]; if (script){ if (typeof(script) == 'object') { Object.each(script, function(newScript,newScriptId) { if (!window.dependents.get(newScriptId)){ window.dependents[newScriptId] = []; } window.dependents[newScriptId].push(elem); addscript(newScript,newScriptId); }); } else { if (!window.dependents.get(scriptid)){ window.dependents[scriptid] = []; } window.dependents[scriptid].push(elem); addscript(script,scriptid); } }else{ alert('Missing Asset: '+scriptid+'\nBrowser Engine: '+Browser.name+'\nLocation: '+location.href); } } window.addEvent('scriptfinishedloading',function(sid){ if (sid){ window.dependentscripts[sid] = 'done'; //console.log('done "'+sid+'"'); } if(window.parsingfinished && Igloo.loadingScripts.length == 0){ // if the page isn't fully parsed, the scripts can NOT be fully loaded. Who knows if more will be added var allscriptsfinishedloading = true; for(s in window.dependentscripts){ if(window.dependentscripts[s] == 'loading'){ allscriptsfinishedloading = false; } } if(allscriptsfinishedloading){ window.fireEvent('allscriptsfinishedloading'); } // parsing is finished, and all scrips are finished loading } }); window.addEvent('allscriptsfinishedloading',function(){ //alert('all scripts finished loading'); window.allscriptsloaded = true; if(window.parsingfinished){ if(!window.bootstrapfinished){ window.bootstrapfinished = true; window.fireEvent('bootstrapfinished'); window.fireEvent('bootstrap4finished'); // new bootstrap finished event } } }); window.addEvent('parsingfinished',function(){ //alert('parsing finished'); window.parsingfinished = true; if(window.allscriptsloaded){ if(!window.bootstrapfinished){ window.bootstrapfinished = true; window.fireEvent('bootstrapfinished'); window.fireEvent('bootstrap4finished'); // new bootstrap finished event } }else{ window.fireEvent('scriptfinishedloading', null); } }); window.addEvent('bootstrapfinished',function(){ // all Assets should be wired to this event. //alert('bootstrap is finished'); // console.log('bootstrapfinished'); }); function bootstrap(bselement){ window.dependentscripts = []; window.parsingfinished = false; window.allscriptsloaded = false; window.bootstrapfinished = false; window.dependents = new Hash(); if (typeOf(bselement) == 'array') { var jselements = []; Array.each(bselement, function(bselem) { var currentjsElems = bselem.getElements('.js'); if (currentjsElems && currentjsElems.length > 0) { if (jselements.length > 0) { jselements.append(currentjsElems); } else { jselements = currentjsElems; } } if (bselem.hasClass('js')) { jselements.append($$(bselem)); } }); } else { var jselements = bselement.getElements('.js'); if (bselement.hasClass('js')) { jselements.append($$(bselement)); } if (window.tinymce && window.tinymce.plugins && window.tinymce.plugins.AutoSave && window.tinymce.plugins.AutoSave._beforeUnloadHandler) { bselement.getElements('a.js-clickAway').addEvent('click', function() { var beforeUnloader = tinymce.plugins.AutoSave._beforeUnloadHandler(); var confirmFlag = true; if (beforeUnloader) { var confirmFlag = confirm(beforeUnloader); } return(confirmFlag); }); } } jselements.each(function(elem){ if ((matches = elem.className.match(/(\{.*\})/))){ var dataobj = IglooXML.decode(matches[1]); dataobj = JSON.decode(dataobj); // do a nice combine of the dataobjs if(!elem.dataobj || typeOf(elem.dataobj)!='hash'){ elem.dataobj = new Hash(elem.dataobj || dataobj); } elem.dataobj.combine(dataobj); // grab the top level items in dataobj, these are the asset's scriptid for (var asset in dataobj){ newaddscript(asset, elem); } } }); window.fireEvent('parsingfinished'); } var AddContentHandler = new Class({ Implements: [Options, Events], options: { 'type': "", 'communityId': "", 'targetId': "", 'interstitial': false, 'urlidentifieronform': false, 'targettype': "" }, initialize: function(trigger, options) { this.setOptions(options || {}); this.trigger = $(trigger); this.setObjectAction(); this.setModalOptions(); this.attachEvents(); }, // cleans up input where we've added "Channel" to the end of the type. setObjectAction: function() { this.originalType = this.options.type; this.objectAction = this.options.type.toString().toLowerCase().replace('channel', ''); this.options.type = this.options.type.toString().replace('Channel', ''); }, // Attaches events to elements that exist upon initialization. attachEvents: function() { this.trigger.addEvent('click', function(event) { event.stop(); this.openModal(); return false; }.bind(this)); }, // Builds the Modal Options object. Used in openModal() when creating the Modalbox object setModalOptions: function() { var self = this; this.modalOptions = { 'title': window.translations('system-manage-Add_' + self.options.type), 'preventScrolling': false, 'position': { 'absolute': {} }, 'onSetContents': function() { this.adjustposition(); if ($(this.mymodalfront) && $(this.mymodalfront).isVisible()) { this.mymodalfront.addEvent('load', function() { this.adjustposition(); }); } } } }, // Deletes any left over modals, then creates the Modalbox object openModal: function() { if (this.addContentModal) { delete this.addContentModal; } this.addContentModal = new Modalbox(this.modalOptions); var paramListStr = 'objectId,type'; var paramTypesStr = 'id,string'; var modalQueryParams = {}; var modalPostData = {}; /* Setting a predefined location */ if (this.options.targetId != "") { paramListStr = paramListStr + ',targetId'; paramTypesStr = paramTypesStr + ',id'; modalPostDataAppend = { 'targetId': this.options.targetId }; Object.append(modalPostData, modalPostDataAppend); } Object.append(modalPostData, { 'objectId': this.options.communityId, 'type': this.options.type, 'componentName': 'modal_addObject' }); modalQueryParams = { 'paramList': paramListStr, 'paramTypes': paramTypesStr }; this.getModalContents(modalPostData, modalQueryParams, function() { this.displayModalContent(); }.bind(this)); }, // Uses an API call to get Modal contents. Executes any inline JS. getModalContents: function(modalPostData, modalQueryParams, continueTo) { var self = this; this.contentApi = new ApiClient({ 'apimethod': 'igloo/widgets/rendercomponent', 'postdata': modalPostData, 'queryparams': modalQueryParams, onRequest: function() { self.addContentModal.setcontents('
 
'); }, onSuccess: function(text, xml) { // convert the text to JSON var requestResponse = JSON.decode(text, true); if (!requestResponse || !requestResponse.response) { Utils.modalAlert(window.translations('media-js-error_general')); } // and get the HTML part out of it // ugh. This is terrible. self.html = requestResponse.response.items[0].value; // make sure the inline JS is executed! this.processScripts(self.html); continueTo(); }, onFailure: function(instance) { self.addContentModal.setcontents(window.translations('media-js-Error_loading_content')); } }); }, // Populates Modal with results of API call and sets up any necessary little display details. displayModalContent: function() { var self = this; // inject this in the modalbox if (this.addContentModal) { this.addContentModal.setcontents(this.html); } // bootstrap the modalbox contents window.setTimeout(function() { bootstrap(self.addContentModal.bodypart); }, 1); this.parentnodeuid = (this.trigger.get('nodeobjectid')) ? this.trigger.get('nodeobjectid') : ""; this.modalFront = this.addContentModal.mymodalfront; this.form = $(this.addContentModal.mymodalfront).getElement('form'); if (this.form == null) { return false; } if (this.form.getElement('.url_input')) { var r = new Retyper({ 'elem': this.form.getElement('.url_input'), 'allowed': '0-9a-z_' }); } if (this.options.urlidentifieronform && this.form.getElement('.js-navItem-url') && this.form.getElement('.js-help-url')) { this.setUrlIdentBehavior(); } this.addModalEvents(); }, // adds events to the new modal. addModalEvents: function() { var self = this; this.addContentModal.mymodalfront.getElement('.js-cancel_button').addEvent('click', function() { self.addContentModal.close(); delete self.addContentModal; }); this.form.addEvent('onvalidformsubmit', function() { if (this.options.targettype.ciCompare('page')) { this.changeParentType(); } else { this.prepModalForm(); } }.bind(this)); if (this.objectAction == "space" && $('templateId')) { // deal with the template id display. var tempDescElements = $('js-templateDesc').getChildren('.ig-tempDesc'); $('templateId').addEvent('change', function() { var selectedTemplate = $('templateId').getSelected(); var selectedValue = $('templateId').getSelected().getLast().value; if ($('tempDesc_' + selectedValue)) { Array.each(tempDescElements, function(desc) { $(desc).addClass('hide'); }); $('tempDesc_' + selectedValue).removeClass('hide'); self.addContentModal.adjustposition(); } }); } }, // sets up the url display, if urlidentifieronform is true setUrlIdentBehavior: function() { var urlInput = this.form.getElement('.js-navItem-url'); var igHelpURL = this.form.getElement('.js-help-url'); var igHelpURLValue = igHelpURL.get('html'); if (igHelpURLValue == "/") { urlInput.baseURL = undefined; } else { urlInput.baseURL = igHelpURLValue; } // update URL shown below input igHelpURL.addEvent('update', function(segmentElem) { var base = ''; if (segmentElem.baseURL) { base = segmentElem.baseURL; } var newURL = base + (segmentElem.value == '' ? '' : '/' + segmentElem.value); try { this.set('html', newURL == '' ? '/' : newURL); } catch (e) { } }); var r = new Retyper({ 'elem': urlInput, 'allowed': '0-9a-z_', 'lowercase': true, 'onScrub': function() { igHelpURL.fireEvent('update', urlInput); } }); }, // Creates a postdata object. For posting. Data. setPostData: function() { this.postData = {}; this.postData.showInNav = this.showInNav; if (this.objectAction === 'page') { this.apiMethod = 'pages/insert'; this.postData.templateId = (this.templateId != 0) ? this.templateId : ""; this.postData.parentId = (this.navParentId != -1) ? this.navParentId : this.navItemParentId; this.postData.navTitle = this.navTitle; this.postData.urlTitle = this.urlTitle; this.postData.childtype = this.childType; } else if (this.objectAction === 'blog') { this.apiMethod = 'blogfolders/' + this.navParentId + '/blogchannels/add'; this.postData.title = this.navTitle; this.postData.description = this.navDescription; this.postData.returnNav = "true"; } else if (this.objectAction === 'calendar') { this.apiMethod = 'calendar/create'; this.postData.parentId = this.navParentId; this.postData.title = this.navTitle; this.postData.returnNav = "true"; } else if (this.objectAction === 'folder') { this.apiMethod = 'folderchannel/create'; this.postData.parentId = this.navParentId; this.postData.title = this.navTitle; this.postData.returnNav = "true"; } else if (this.objectAction === 'forum') { this.apiMethod = 'forums/' + this.navParentId + '/forumchannels/add'; this.postData.parentId = this.navParentId; this.postData.title = this.navTitle; this.postData.returnNav = "true"; this.postData.description = this.navDescription; this.getCheckBoxGroupValues('.js-forum-topic-type'); } else if (this.objectAction === 'wiki') { this.apiMethod = 'wiki/create'; this.postData.parentId = this.navParentId; this.postData.title = this.navTitle; this.postData.returnNav = "true"; } else if (this.objectAction === 'microblog') { this.apiMethod = 'microblogfolders/' + this.navParentId + '/microblogchannels/add'; this.postData.title = this.navTitle; this.postData.description = this.navDescription; this.postData.hashName = this.hashName; this.postData.returnNav = "true"; } else if (this.objectAction === 'space') { this.apiMethod = 'spaces/insert'; this.postData.templateId = this.templateId; this.postData.navItemParentId = this.navItemParentId; this.postData.navTitle = this.navTitle; this.postData.urlTitle = this.urlTitle; this.postData.description = this.navDescription; } else if (this.objectAction === 'tasks') { this.apiMethod = 'taskchannels/create'; this.postData.parentId = this.navParentId; this.postData.title = this.navTitle; this.postData.returnNav = "true"; } }, getCheckBoxGroupValues: function(groupClass) { var inputArray = $$('input[type="checkbox"]' + groupClass); var topicBitmask = 0; Array.each(inputArray, function(inputField) { topicBitmask += (inputField.checked) ? inputField.get('value').toInt() : 0; }); this.postData.allowedTopicTypes = topicBitmask; }, changeParentType: function() { var self = this; // This is a page, we need to do a check to see if this is valid var updateChild = new ApiClient({ 'apimethod': 'pages/' + self.options.targetId + '/update_allowedchild', 'postdata': { 'childtype': self.originalType }, onFailure: function() { // could be a bad child type var returnstring = this.response.text; var returnjson = JSON.decode(returnstring, true); var errorText = window.translations('media-js-api_error'); if (returnjson.exception && returnjson.exception.type) { if (returnjson.exception.type.ciCompare("state_actiondoesnotapply")) { errorText = window.translations('media-js-error_Page_Childtype_Incorrect'); } } self.addContentModal.close(); Utils.modalAlert(errorText); }, onSuccess: function() { self.prepModalForm(); } }); }, // Builds out the modal form submission information. Calls setPostData(). Checks the URL, if required. prepModalForm: function() { if (!this.busy) { this.busy = true; // init the string values this.navParentId = this.options.communityId; this.navTitle = ""; this.navDescription = ""; this.urlTitle = ""; this.hashName = ""; this.showInNav = "true"; // yay. A bool value that has to be passed as a string. if (this.form.getElement('.name_input')) { this.navTitle = this.form.getElement('.name_input').value; } if (this.form.parent_select) { if (this.form.parent_select.value != "") { this.navParentId = this.form.parent_select.value; } else if (this.objectAction === 'page' && this.parentnodeuid != '') { this.navParentId = this.parentnodeuid; } } else if (this.form.getElement('.js-navItem-parent-guid')) { this.navParentId = this.form.getElement('.js-navItem-parent-guid').get('value'); } if (this.form.getElement('.desc_input')) { this.navDescription = this.form.getElement('.desc_input').value; } if (this.form.getElement('.url_input')) { this.editurlinput = this.form.getElement('.url_input'); this.urlTitle = this.editurlinput.value; } if (this.form.getElement('.hashName_input')) { this.hashName = this.form.getElement('.hashName_input').value; } if (this.form.getElement('.hidden_checkbox') && this.form.getElement('.hidden_checkbox').checked) { this.showInNav = "false"; } if (this.form.getElement('.js-navItem-parent')) { this.navItemParentId = this.form.getElement('.js-navItem-parent').value; } if (this.form.getElement('.template_select')) { this.templateId = this.form.getElement('.template_select').value; } if (this.form.getElementById('childtype')) { this.childType = this.form.getElementById('childtype').value; } this.setPostData(); if (this.options.urlidentifieronform && this.navItemParentId !== undefined && this.urlTitle !== undefined) { // do a check before submitting. this.checkUrl(); } else { this.submitContent(); } } }, // checks the url via API call. Not sure that this is needed anymore. checkUrl: function() { var self = this; Utils.item_url_available({ parentId: self.navItemParentId, urlTitle: self.urlTitle, onSuccess: function() { self.submitContent(); }, onUnsuccess: function() { Utils.modalAlert(window.translations('admin-nav-URL_Taken_Add')); self.editurlinput.focus(); self.editurlinput.select(); if (self.modalFront && self.modalFront.getElement('.js-loader')) { self.modalFront.getElement('.js-loader').addClass('hide'); } if (self.modalFront && self.modalFront.getElement('.js-submit_button')) { self.modalFront.getElement('.js-submit_button').setProperty('disabled', null).removeClass('ig-button_disabled'); } if (self.modalFront && self.modalFront.getElement('.js-cancel_button')) { self.modalFront.getElement('.js-cancel_button').setProperty('disabled', null).removeClass('ig-button_disabled'); } self.busy = false; }, onFailure: function() { self.editurlinput.focus(); self.editurlinput.select(); var args = $A(arguments).flatten(); var message = window.translations('media-js-api_error'); if (JSON.decode(args[0].responseText).exception.type == 'Validation_ReportInvalidInput') { message = window.translations('media-js-invalid_url_identifier'); } Utils.modalAlert(message); self.busy = false; } }); }, // sends off the content, and deals with success and failure. If this requires a follow-up modal, goes off to build that. submitContent: function() { var self = this; // make the API request var addManageSiteObject = new ApiClient({ 'apimethod': self.apiMethod, 'method': 'post', 'postdata': self.postData, onRequest: function() { if (self.modalFront && self.modalFront.getElement('.js-loader')) { self.modalFront.getElement('.js-loader').removeClass('hide'); } if (self.modalFront && self.modalFront.getElement('.js-submit_button')) { self.modalFront.getElement('.js-submit_button').setProperty('disabled', 'disabled').addClass('ig-button_disabled'); } }, onSuccess: function(text, xml) { var returnjson = JSON.decode(text, true); if (returnjson != null) { var responseItems = returnjson.response.items; var response = {}; var allowedChildResponse = null; var navTreeResponse = null; Object.each(responseItems, function(item) { if (item.name && item.name == "navTree") { // this is the response navTreeResponse = JSON.decode(item.value); } else if (item.name && item.name == "allowedChild") { // add this to the response allowedChildResponse = { property: {} }; allowedChildResponse.property.allowedChildType = item.value; } }); if (allowedChildResponse != null && navTreeResponse != null) { response = Object.merge(navTreeResponse, allowedChildResponse); } else if (navTreeResponse != null) { response = navTreeResponse; } else { Utils.modalAlert(window.translations('media-js-error_general')); } self.addContentModal.close(); delete self.addContentModal; document.fireEvent('addObjectSuccess', [response, self.navParentId]); if (self.options.interstitial) { self.buildInterstitial(response); } } }, onFailure: function() { var response = JSON.decode(arguments[0].responseText); if (response.exception.type === 'Validation_ObjectTitleDuplicate') { Utils.modalAlert(window.translations('system-page-error_Validation_Title_In_Use')); } else if (response.exception.type === "State_ActionDisabled" && self.objectAction === 'space') { Utils.modalAlert(window.translations('admin-siteManage-maximum_spaces_reached')); } else if (response.exception.type === 'Validation_ReportInvalidInput' && response.exception.errorList[0].type === "Hash_InvalidFormat") { Utils.modalAlert(window.translations('media-js-invalid_hashname')); } else { Utils.modalAlert(response.exception.message); } self.busy = false; }, onComplete: function() { self.busy = false; if (self.modalFront && self.modalFront.getElement('.js-loader')) { self.modalFront.getElement('.js-loader').addClass('hide'); } if (self.modalFront && self.modalFront.getElement('.js-submit_button')) { self.modalFront.getElement('.js-submit_button').setProperty('disabled', null).removeClass('ig-button_disabled'); } if (self.modalFront && self.modalFront.getElement('.js-cancel_button')) { self.modalFront.getElement('.js-cancel_button').setProperty('disabled', null).removeClass('ig-button_disabled'); } } }); }, // builds the HTML for the interstitial buildInterstitial: function(response) { var paramListStr = 'objectId,type,pageUrl,pageName,pageLocation,componentName'; var paramTypesStr = 'id,string,string,string,string,string'; modalQueryParams = { 'paramList': paramListStr, 'paramTypes': paramTypesStr }; var modalPostData = { 'objectId': this.options.communityId, 'type': this.options.type, 'pageUrl': response.property.url, 'pageName': response.property.name, 'pageLocation': window.location.protocol + '//' + window.location.hostname + response.property.url, 'componentName': 'modal_addObjectInterstitial' }; if (this.options.targetId != "") { paramListStr = paramListStr + ',targetId'; paramTypesStr = paramTypesStr + ',id'; modalPostDataAppend = { 'targetId': response.property.object_id }; Object.append(modalPostData, modalPostDataAppend); } if (this.addContentModal) { this.addContetModal.destroy(); delete this.addContentModal; } this.addContentModal = new Modalbox(this.modalOptions); this.addContentModal.settitle(window.translations('admin-siteManage-Space_Created')); this.getModalContents(modalPostData, modalQueryParams, function() { this.showInterstitial(); }.bind(this)); }, // displayse the interstitial after object creation showInterstitial: function() { var self = this; if (!this.smsfAdded) { this.smsfAdded = true; document.addEvent('siteManagerScrollFinished', function() { this.addContentModal.setcontents(this.html); this.addContentModal.adjustposition(); if (this.addContentModal.bodypart && $(this.addContentModal.bodypart).getElement('.js-closebtn')) { $(this.addContentModal.bodypart).getElement('.js-closebtn').addEvent('click', function(e) { e.preventDefault(); self.addContentModal.close(); }); } }.bind(this)); } if (!Igloo || !Igloo.asset_SiteMap) { document.fireEvent('siteManagerScrollFinished'); } } }); var AddPageHandler = new Class ({ Extends: AddContentHandler, // Populates Modal with results of API call and sets up any necessary little display details. // calls a function to deal with the template div displayModalContent: function() { var self = this; // inject this in the modalbox this.addContentModal.setcontents(this.html); // bootstrap the modalbox contents window.setTimeout(function(){ bootstrap(self.addContentModal.bodypart); },1); this.parentnodeuid = (this.trigger.get('nodeobjectid')) ? this.trigger.get('nodeobjectid') : ""; this.modalFront = this.addContentModal.mymodalfront; this.form = $(this.addContentModal.mymodalfront).getElement('form'); if (this.form == null) { return false; } this.addContentModal.mymodalfront.getElement('.js-cancel_button').addEvent('click', function() { self.addContentModal.close(); delete self.addContentModal; }); if (this.form.getElement('.url_input')) { var r = new Retyper({ 'elem': this.form.getElement('.url_input'), 'allowed': '0-9a-z_' }); } if (this.options.urlidentifieronform && this.form.getElement('.js-navItem-url') && this.form.getElement('.js-help-url')) { var urlInput = this.form.getElement('.js-navItem-url'); var igHelpURL = this.form.getElement('.js-help-url'); if (this.trigger.getParent('.ig-node-Page') && this.trigger.getParent('.ig-node-Page').getElement('.mif-tree-url')) { igHelpURL.set('html',this.trigger.getParent('.ig-node-Page').getElement('.mif-tree-url').get('html')); } var igHelpURLValue = igHelpURL.get('html'); if (igHelpURLValue == "/") { urlInput.baseURL = undefined; } else { urlInput.baseURL = igHelpURLValue; } if (this.trigger.getAttribute('parentid') && this.form.getElement('.js-navItem-parent')) { this.form.getElement('.js-navItem-parent').value = this.trigger.getAttribute('parentid'); } if (this.trigger.getAttribute('nodeobjectid') && this.form.getElement('.js-navItem-parent-guid')) { this.form.getElement('.js-navItem-parent-guid').value = this.trigger.getAttribute('nodeobjectid'); } // update URL shown below input igHelpURL.addEvent('update', function(segmentElem) { var base = ''; if (segmentElem.baseURL) { base = segmentElem.baseURL; } var newURL = base + (segmentElem.value == '' ? '' : '/' + segmentElem.value); try { this.set('html', newURL == '' ? '/' : newURL); } catch (e) { } }); var r = new Retyper({ 'elem': urlInput, 'allowed': '0-9a-z_', 'lowercase': true, 'onScrub': function() { igHelpURL.fireEvent('update', urlInput); } }); } if (this.form.parent_select && $(this.form.parent_select)) { $(this.form.parent_select).set('value', this.trigger.getAttribute('nodeobjectid')); } this.form.addEvent('onvalidformsubmit', function() { this.prepModalForm(); }.bind(this)); if ($$('.ig-templateoptions') && $('js-templateDesc') && $('js-templatelist')) { this.templateList = $('js-templatelist'); this.addTemplateFunctions(); } }, addTemplateFunctions: function() { var self = this; this.addContentModal.mymodalfront.getElement('.inputbox').getElement('.icon').addEvent('click', function() { // set a spinny in place of the arrow icon this.removeClass('icon-arrow').removeClass('ig-cursorpointer').addClass('icon-loading'); // get the templates self.getTemplateList(); }); }, getTemplateList: function() { var self = this; var templateListing = new ApiClient ({ 'apimethod': 'pages/view_all_templates', 'method': 'get', onRequest: function() { }, onSuccess: function(text, xml) { var returnjson = JSON.decode(text, true); if (returnjson != null) { var response = returnjson.response; self.availableTemplates = response.items; self.showTemplateList(); } }, onFailure: function() { var something = 'error'; }, onComplete: function() { var something = self.addContentModal.mymodalfront.getElement('.inputbox').getElement('.icon'); self.addContentModal.mymodalfront.getElement('.inputbox').getElement('.icon').addClass('icon-arrow').removeClass('icon-loading').addClass('ig-cursorpointer'); } }); }, showTemplateList: function() { // add to the template ul var self = this; $('js-templateoption_0').addEvent('click', function(e) { self.selectTemplate(e.target, true); }); Array.each(this.availableTemplates, function(template) { var tId = template.PageId; if (self.addContentModal.mymodalfront.getElements('.js-templateoption_'+tId).length == 0) { var tName = (template.Title) ? template.Title : window.translations('admin-siteManage-template_unnamed'); var tDesc = template.Description var templateElement = new Element('li', { 'id':"js-templateoption_"+tId, 'class':"js-templateoption js-templateoption_"+tId }).adopt( new Element('p', { 'class':'js-templatename', 'html':(tName) }), new Element('p', { 'class':'js-templatedesc meta small', 'html':(tDesc) }) ).addEvent('click', function(e) { self.selectTemplate(e.target, false); }); self.templateList.getElement('ul').adopt(templateElement); } }); if (this.templateList.getHeight > 300) { this.templateList.setStyle('height', '300px'); } var something = $('js-templateinput').getWidth() + "px" this.templateList.setStyle('width', $('js-templateinput').getWidth() + "px"); this.templateList.getElements('p').setStyle('width', $('js-templateinput').getWidth() + "px"); // make this a slide down this.templateList.removeClass('hide'); }, selectTemplate: function(targetelem, isBlank) { var nameElem = $('js-templateinput'); nameElem = nameElem.getFirst('.js-templatenameinput'); var descElem = $('js-templatedesc'); //set the input to the name, and the description to the desc. if (!targetelem.hasClass('js-templateoption')) { targetelem = targetelem.getParent('.js-templateoption'); } $('templateId').value = targetelem.id.replace('js-templateoption_',''); this.templateId = targetelem.id.replace('js-templateoption_',''); var newName = targetelem.getFirst('.js-templatename').get('html'); var newDesc = targetelem.getElements('.js-templatedesc').get('html'); nameElem.set('html', newName); descElem.set('html', newDesc); if (isBlank) { this.enableChildType(); } else { this.disableChildType(); } this.hideTemplateList(); this.addContentModal.adjustposition(); }, // disables the child type input, if it exists. This is done when the "blank" template is not chosen. disableChildType: function() { if (this.form.getElementById('childtype')) { this.form.getElementById('childtype').disabled = true; this.form.getElementById('childtype').addClass('ig-light_font'); } }, // enables the child type input, if it exists. This is done when the "blank" template is chosen. enableChildType: function() { if (this.form.getElementById('childtype')) { this.form.getElementById('childtype').disabled = false; this.form.getElementById('childtype').removeClass('ig-light_font'); } }, attachEvents: function() { this.trigger.addEvent('click',function(event){ event.stop(); this.openModal(); return false; }.bind(this)); document.addEvent('click', function(event) { if (this.templateList && event.target != this.templateList && !$(this.templateList).getElement(event.target)) { this.hideTemplateList(); } }.bind(this)); }, hideTemplateList: function() { // make this a slideup. this.templateList.addClass('hide'); } }); window.addEvent('domready', function() { if (Igloo && Igloo.asset_addObject) { Object.each(Igloo.asset_addObject, function(options, id) { if (id.toString().toLowerCase().contains("addpage")) { thisContentHandler = new AddPageHandler(id, options); } else { thisContentHandler = new AddContentHandler(id, options); } }); } }); window.addEvent('bootstrap4finished', function() { if (window.dependents['addObject']) { window.dependents['addObject'].each(function(elem) { var dataobj = elem.dataobj; if (elem.id.toString().toLowerCase().contains("addpage")) { thisContentHandler = new AddPageHandler(elem, dataobj.addObject); } else { thisContentHandler = new AddContentHandler(elem, dataobj.addObject); } }); } });function jsrecentbadge(elem, userid, badgeseturl, triggerId){ var commentaddajax = new ApiClient({ 'apimethod':'badges/by_user', 'method':'get', 'queryparams':{ 'userId': userid, 'maxcount': 3, 'startindex': 0, 'type': 2 }, onSuccess:function(){ var returnstring = this.response.text; var returnjson = JSON.decode(returnstring,true); if (returnjson != null) { var max = 3; if (returnjson['response']['items'].length0) { thetitle = thetitle + " - "+curitem['message']; } badgediv.addClass('ig-badgeicon ig-smallmarginright'); if(curitem['visibility']>0) { badgediv.addClass('fade'); } badgediv.set({ styles:{ 'background-position': xshift+'px 0px', 'background-image': 'url('+badgeseturl+')' }, title:thetitle }); elem.appendChild(badgediv); } } } }); } window.addEvent('bootstrap4finished', function(){ if (window.dependents['ajax-badgerecent']) { window.dependents['ajax-badgerecent'].each(function(elem){ if (elem.dataobj) { var dataobj = typeOf(elem.dataobj)=='string' ? JSON.decode(elem.dataobj) : elem.dataobj; jsrecentbadge(elem, elem.dataobj['ajax-badgerecent'].userid, elem.dataobj['ajax-badgerecent'].badgeseturl, elem.dataobj['ajax-badgerecent'].triggerId); } }); } }); var ajax_followersList = new Class({ Implements: [Options], options:{ 'objectId': null, 'triggerId': null, 'menuId':null, 'listId':null }, initialize: function(options){ var self = this; // set the options this.setOptions(options || {}); var followersList = $(this.options.listId); var getFollowers = true; var menu = new igDropdown(this.options.triggerId, null, {'menu':this.options.menuId, 'align':'right'}); menu.addEvent('show', function(){ if (getFollowers) { var getFollowersViaAjax = new ApiClient({ 'headers':{'Accept': 'application/xml'}, 'apimethod':'igloo/widgets/35/render', 'queryparams':{ 'paramList':'objectId', 'paramTypes':'id' }, 'postdata':{ 'objectId':self.options.objectId }, onSuccess:function(text,xml){ // extract the useful stuff from the IglooApiResponse var response = Utils.IARParse(xml); // Clean up the output area followersList.removeClass('ig-loader-medium'); // Output the response on screen followersList.set('html',response.apihtml); // No need to get the followers again getFollowers = false; } }); } }); } }); window.addEvent('domready', function() { if (Igloo && Igloo.asset_ajax_followersList) { var followers; Object.each(Igloo.asset_ajax_followersList, function(object, id) { object.triggerId = id; followers = new ajax_followersList(object); }); } });  window.addEvent('domready', function(){ var elements = []; if(Igloo && Igloo.asset_ajax_like){ Object.each(Igloo.asset_ajax_like, function(object, id){ var elem = $(id); if(!elem.dataobj || typeOf(elem.dataobj)!='hash'){ elem.dataobj = new Hash(elem.dataobj || object); } elem.dataobj.combine(object); elements.push(elem); }); elements.each(function(elem){ var dataobj = elem.dataobj; // Send like for item var likeButton = $('ig-like_' + dataobj.objId); if (likeButton) { likeButton.addEvent('click', function(event){ event.preventDefault(); updateItem(this, dataobj, 100); }); } // Send dislike for item var dislikeButton = $('ig-dislike_' + dataobj.objId); if (dislikeButton) { dislikeButton.addEvent('click', function(event){ event.preventDefault(); updateItem(this, dataobj, 0); }); } }); } }); function updateItem(button, dataobj, value) { var clear = (button.hasClass('hilite')) ? true : false; var apiMethod = (dataobj.commentType == 'comments') ? dataobj.commentType+'/'+dataobj.objId+'/rate' : dataobj.commentType+'/'+dataobj.objId+'/forumPost/rate'; var sendValue = new ApiClient({ 'apimethod':apiMethod, 'postdata':{ 'rating':value, 'clear':clear }, onRequest:function(){ //disable buttons }, onSuccess:function(text){ var returnjson = JSON.decode(text,true); if (returnjson) { // set variables for easy use var likeButton = $('ig-like_' + dataobj.objId); var dislikeButton = $('ig-dislike_' + dataobj.objId); var totalArea = $('ig-likeTotal_' + dataobj.objId); // get current values var totalLiked = likeButton.get('html'); var totalDisliked = (dislikeButton) ? dislikeButton.get('html') : 0; // get currently selected var currSelected = ''; if (likeButton.hasClass('hilite')) { currSelected = 'like'; } if (dislikeButton) { if (dislikeButton.hasClass('hilite')) { currSelected = 'dislike'; } } if (value > 0) { // LIKE if (clear) { // remove like totalLiked--; } else { // increment like totalLiked++; if (currSelected == 'dislike') { totalDisliked-- } } } else { // DISLIKE if (clear) { // remove dislike totalDisliked--; } else { // increment dislike totalDisliked++; if (currSelected == 'like') { totalLiked-- } } } // adjust hilite likeButton.removeClass('hilite'); if (dislikeButton) { dislikeButton.removeClass('hilite'); } if (!clear) { button.addClass('hilite'); } // update values likeButton.set('html', totalLiked); if (dislikeButton) { dislikeButton.set('html', totalDisliked); } var totalAreaTitle = totalLiked + ' Like'; if (dislikeButton) { totalAreaTitle += ', ' + totalDisliked + ' Dislike'; } totalArea.set({ 'title' : totalAreaTitle, 'html' : totalLiked - totalDisliked }); } }, onFailure:function(){ //shouldn't happen } }); } var AjaxLoadMore = new Class({ Implements: [Options], options: { 'seemorelinkid': 'ig-anchor-calendar-see_more', // Trigger 'componentName': "", //Component to render 'objId': '', // Page Id 'startDate': '', // The start date 'startDateRange': '', // The start date for the range 'endDateRange': '', // The end date for the range 'publishedBefore': '', 'resultsPerPage': 25, // Num of results per page 'startIndex': 0, //which page to start on 'mcselections': '', 'typeFilter': '', 'statusFilter': '', 'sortBy': '', 'sortOrder': '', 'uniqueId': 0, 'layout': 1, 'optProfilePic': false, 'optCreatedBy': true, 'optCreatedDate': true, 'optChannel': true, 'optSummary': true, 'optBody': true, 'optViews': true, 'optLocked': true, 'optType': true, 'optResolution': true, 'optReplies': true, 'optRating': false, 'optLikes': false, 'optActionsButton': false, 'enableFilterBox': false, 'enablePersonalFilter': false }, initialize: function(options) { // set the options this.setOptions(options || {}); this.objectId = this.options.objId; // Decode selections this.mcselections = IglooXML.decode(this.options.mcselections); this.resultsPerPage = parseInt(this.options.resultsPerPage); this.seeMoreTrigger = $(this.options.seemorelinkid); this.startDate = this.options.startDate; this.futureDate = this.options.futureDate; this.startDateRange = this.options.startDateRange; this.endDateRange = this.options.endDateRange; this.componentName = this.options.componentName; this.startIndex = parseInt(this.options.startIndex); this.uniqueId = parseInt(this.options.uniqueId); this.instanceId = this.uniqueId + "_" + this.objectId; //Get the start date and future date values this.startDateValue = ''; this.futureDateValue = ''; if (this.startDate) { this.startDateValue = this.startDate; var sDate = new Date(this.startDate); this.futureDateValue = new Date(new Date(sDate).setMonth(sDate.getMonth()+6)); this.futureDateValue = _formatDate(this.futureDateValue); } this.setWindowFlags(); this.setupAPI(); this.addEventHandlers(); }, setWindowFlags: function() { if (!Igloo.loadMore) { Igloo.loadMore = {}; } if (!Igloo.loadMore[this.instanceId]) { Igloo.loadMore[this.instanceId] = { 'requiresNewDate':false, 'startDate':this.startDateValue, 'nextDate':this.futureDateValue, 'attempts':0, 'isDateRangeEvent':false } } // Is this a date range? if (this.options.startDateRange && this.options.endDateRange) { Igloo.loadMore[this.instanceId].isDateRangeEvent = true; } }, addEventHandlers: function() { var self = this; this.seeMoreTrigger.addEvent('click', function(event) { event.preventDefault(); self.callAPI(); }); }, setupAPI: function() { var initParams = new Hash({ 'mcselections': this.mcselections, 'startDateValue': this.startDate, 'startDateRange': this.startDateRange, 'endDateRange': this.endDateRange, 'uniqueId': this.uniqueId, 'startIndex': this.startIndex, 'resultsPerPage': this.resultsPerPage, 'componentName': this.componentName, 'objectId': this.objectId, 'instanceId': this.instanceId }); if (this.componentName.ciCompare('ajaxcalendarevent')) { this.componentSetup = new AjaxCalendarEventLoadMore(this.options, initParams); } else if (this.componentName.ciCompare('ajaxwidgetcalendar')) { this.componentSetup = new AjaxCalendarWidgetLoadMore(this.options, initParams); } else if (this.componentName.ciCompare('ajaxblogarticles')) { this.componentSetup = new AjaxBlogArticlesLoadMore(this.options, initParams); } else if (this.componentName.ciCompare('ajaxforumtopics')) { this.componentSetup = new AjaxForumTopicsLoadMore(this.options, initParams); } else { return false; } }, callAPI: function() { var self = this; var msgElem = $("js-calendar-loadmore-msg_" + self.options.uniqueId); var getViaAjax = new ApiClient({ 'headers': {'Accept':'application/xml'}, 'method': 'post', 'apimethod': 'igloo/widgets/rendercomponent', 'postdata': self.componentSetup.getPostData(), 'queryparams': self.componentSetup.queryParams, onRequest: function() { // Add loader to trigger if (msgElem) { msgElem.toggleClass('icon icon-loading icon-notext'); } else { self.seeMoreTrigger.addClass('icon icon-loading icon-notext'); } }, onSuccess: function(text, xml) { var noData = new Element ('div', { 'html': self.componentSetup.noDataMessage, 'class':'ig-alert' }); // Extract the useful data from response var response = Utils.IARParse(xml); if (response.apihtml.contains('ig-alert') || response.apihtml == "") { // Is this a calendar event we are checking? if (Igloo.loadMore[self.instanceId].startDate) { // We have no events loaded so we will require a new date to query Igloo.loadMore[self.instanceId].requiresNewDate = true; Igloo.loadMore[self.instanceId].attempts += 1; // Temp start date vars var sDate = new Date(Igloo.loadMore[self.instanceId].startDate); var sNewDate = new Date(new Date(sDate).setMonth(sDate.getMonth()+6)); sNewDate = _formatDate(sNewDate); // Temp next date vars var nDate = new Date(Igloo.loadMore[self.instanceId].nextDate); var nNewDate = new Date(new Date(nDate).setMonth(nDate.getMonth()+6)); nNewDate = _formatDate(nNewDate); // Update the startDate and nextDate Window vars if (Igloo.loadMore[self.instanceId].startDate != Igloo.loadMore[self.instanceId].nextDate) { Igloo.loadMore[self.instanceId].startDate = sNewDate; Igloo.loadMore[self.instanceId].nextDate = nNewDate; } // If this is a date range search... then we should NEVER load more events if (Igloo.loadMore[self.instanceId].isDateRangeEvent == true) { noData.inject(self.seeMoreTrigger, 'before'); self.seeMoreTrigger.destroy(); } else { // Update the calendar msg if (msgElem) { var msgCount = $$("#js-calendar-loadmore-msg_" + self.options.uniqueId + " .js-stat").length; if (msgCount > 0) { msgNumElem = $$("#js-calendar-loadmore-msg_" + self.options.uniqueId + " .js-stat")[msgCount-1]; if (msgNumElem) { var msgNum = 6 * Igloo.loadMore[self.instanceId].attempts; msg = Utils.sprintf(window.translations('apps-calendar-no_events-upcoming-months'), [msgNum.toString()]) msgNumElem.set("html", msg); } } } } } else { noData.inject(self.seeMoreTrigger, 'before'); self.seeMoreTrigger.destroy(); } } else { // Inject response var nextList = new Element ('div', { 'html': response.apihtml }); // Is this a calendar event we are checking? if (Igloo.loadMore[self.instanceId].startDate) { // We have found events so we will reset the attempt counter Igloo.loadMore[self.instanceId].attempts = 0; var childElements = nextList.getChildren(); if (childElements && childElements.length > 0){ Array.each(childElements,function(childEl){ childEl.inject(self.seeMoreTrigger, 'before'); bootstrap(childEl); }); } // Since each load more request adds a msg container we need to remove the last id so duplication does not occur msgElem.removeProperty('id'); // we have a list but are not bound to checking dates, inject the new list } else { var childElements = nextList.getChildren(); if (childElements && childElements.length > 0){ Array.each(childElements,function(childEl){ childEl.inject(self.seeMoreTrigger, 'before'); bootstrap(childEl); }); // Hide the load more link if there are less records returned then what was requested if (childElements.length < this.options.postdata.itemsPerPage) { noData.inject(self.seeMoreTrigger, 'before'); self.seeMoreTrigger.destroy(); } } } } }, onFailure: function() { // Error Message var errormsg = new Modalbox({ 'title':window.translations('media-js-Error'), 'width':400, 'shadowcolor':'#ff0000', 'zindex':1000 }).setcontents( new Element('div', { 'class':'ig-modal-pad', 'html':window.translations('media-js-Error_loading_content-refresh') }) ); }, onComplete: function () { // Remove loader class on trigger if (msgElem) { msgElem.toggleClass('icon icon-loading icon-notext'); } else { self.seeMoreTrigger.removeClass('icon icon-loading icon-notext'); } } }); } }); var AjaxCalendarEventLoadMore = new Class({ Implements: [Options], initialize: function(options, initParams) { this.setOptions(options || {}); this.initParams = initParams; this.startIndex = this.initParams.startIndex; this.setupAPI(); }, setupAPI: function() { this.queryParams = { 'paramList': 'mcselections,objectId,startDateValue,startIndex,publishedBefore,resultsPerPage,uniqueId,colLikes', 'paramTypes': 'string,id,string,int,string,int,int,bool' }; this.postData = { 'mcselections': this.initParams.mcselections, 'objectId': this.initParams.objectId, 'startDateValue': this.initParams.startDateValue, 'startIndex': this.startIndex, 'publishedBefore': this.options.publishedBefore, 'resultsPerPage': this.initParams.resultsPerPage, 'uniqueId': this.initParams.uniqueId, 'componentName': this.initParams.componentName, 'colLikes': this.options.optLikes }; this.noDataMessage = window.translations('apps-calendar-no_events-upcoming'); }, getStartIndex: function() { this.startIndex = this.startIndex + this.initParams.resultsPerPage; if (Igloo.loadMore[this.initParams.instanceId].requiresNewDate == true) { this.startIndex = 0; } return this.startIndex; }, getPostData: function() { this.postData.startIndex = this.getStartIndex(); this.postData.startDateValue = Igloo.loadMore[this.initParams.instanceId].startDate; if (Igloo.loadMore[this.initParams.instanceId].requiresNewDate == true) { Igloo.loadMore[this.initParams.instanceId].requiresNewDate = false; } return this.postData; } }); var AjaxCalendarWidgetLoadMore = new Class({ Implements: [Options], initialize: function(options, initParams) { this.setOptions(options || {}); this.initParams = initParams; this.startIndex = this.initParams.startIndex; this.setupAPI(); }, setupAPI: function() { this.queryParams = { 'paramList': 'mcselections,startDateValue,startDateRange,endDateRange,startIndex,publishedBefore,resultsPerPage,uniqueId,layout,personalFilter,colLikes,opt_channel', 'paramTypes': 'string,string,string,string,int,string,int,int,int,bool,bool,bool' }; this.postData = { 'mcselections': this.initParams.mcselections, 'startDateValue': this.initParams.startDateValue, 'startDateRange': this.options.startDateRange, 'endDateRange': this.options.endDateRange, 'startIndex': this.startIndex, 'publishedBefore': this.options.publishedBefore, 'resultsPerPage': this.initParams.resultsPerPage, 'uniqueId': this.initParams.uniqueId, 'layout': this.options.layout, 'componentName': this.initParams.componentName, 'personalFilter': this.options.enablePersonalFilter, 'opt_channel': this.options.optChannel, 'colLikes': this.options.optLikes }; this.noDataMessage = window.translations('apps-calendar-no_events-upcoming'); }, getStartIndex: function() { this.startIndex = this.startIndex + this.initParams.resultsPerPage; if (Igloo.loadMore[this.initParams.instanceId].requiresNewDate == true) { this.startIndex = 0; } return this.startIndex; }, getPostData: function() { this.postData.startIndex = this.getStartIndex(); this.postData.startDateValue = Igloo.loadMore[this.initParams.instanceId].startDate; if (Igloo.loadMore[this.initParams.instanceId].requiresNewDate == true) { Igloo.loadMore[this.initParams.instanceId].requiresNewDate = false; } return this.postData; } }); var AjaxBlogArticlesLoadMore = new Class({ Implements: [Options], initialize: function(options, initParams) { this.setOptions(options || {}); this.initParams = initParams; this.startIndex = this.initParams.startIndex; this.setupAPI(); }, setupAPI: function() { this.queryParams = { 'paramList': 'objectId,mcselections,startIndex,publishedBefore,itemsPerPage,opt_profilepic,opt_CreatedBy,opt_CreatedDate,' + 'opt_channel,opt_summary,opt_body,opt_views,opt_rating,colLikes,opt_comments,opt_actionsbutton,layout', 'paramTypes': 'id,string,int,string,int,bool,bool,bool,bool,bool,bool,bool,bool,bool,bool,bool,int' }; this.postData = { 'objectId': this.initParams.objectId, 'mcselections': this.initParams.mcselections, 'startIndex': this.startIndex, 'publishedBefore': this.options.publishedBefore, 'itemsPerPage': this.initParams.resultsPerPage, 'componentName': this.initParams.componentName, 'opt_profilepic': this.options.optProfilePic, 'opt_CreatedBy': this.options.optCreatedBy, 'opt_CreatedDate': this.options.optCreatedDate, 'opt_channel': this.options.optChannel, 'opt_summary': this.options.optSummary, 'opt_body': this.options.optBody, 'opt_views': this.options.optViews, 'opt_rating': this.options.optRating, 'colLikes': this.options.optLikes, 'opt_comments': this.options.optReplies, 'opt_actionsbutton': this.options.optActionsButton, 'layout': this.options.layout }; this.noDataMessage = window.translations('apps-blogs-no_more_articles'); }, getStartIndex: function() { this.startIndex = this.startIndex + this.initParams.resultsPerPage; return this.startIndex; }, getPostData: function() { this.postData.startIndex = this.getStartIndex(); return this.postData; } }); var AjaxForumTopicsLoadMore = new Class({ Implements: [Options], initialize: function(options, initParams) { this.setOptions(options || {}); this.initParams = initParams; this.startIndex = this.initParams.startIndex; this.setupAPI(); }, setupAPI: function() { this.queryParams = { 'paramList': 'objectId,mcselections,startIndex,publishedBefore,itemsPerPage,typeFilter,statusFilter,sortBy,sortOrder,' + 'colProfilePic,colCreatedBy,colCreatedDate,colLocked,colType,colResolution,colReplies,colRating,colLikes,enableFilterBox,layout,opt_channel', 'paramTypes': 'id,string,int,string,int,string,string,string,string,bool,bool,bool,bool,bool,bool,bool,bool,bool,bool,int,bool' }; this.postData = { 'objectId': this.initParams.objectId, 'mcselections': this.initParams.mcselections, 'startIndex': this.startIndex, 'publishedBefore': this.options.publishedBefore, 'itemsPerPage': this.initParams.resultsPerPage, 'typeFilter': this.options.typeFilter, 'statusFilter': this.options.statusFilter, 'sortBy': this.options.sortBy, 'sortOrder': this.options.sortOrder, 'componentName': this.initParams.componentName, 'colProfilePic': this.options.optProfilePic, 'colCreatedBy': this.options.optCreatedBy, 'colCreatedDate': this.options.optCreatedDate, 'colLocked': this.options.optLocked, 'colType': this.options.optType, 'colResolution': this.options.optResolution, 'colReplies': this.options.optReplies, 'colRating': this.options.optRating, 'colLikes': this.options.optLikes, 'enableFilterBox': this.options.enableFilterBox, 'layout': this.options.layout, 'opt_channel': this.options.optChannel }; this.noDataMessage = window.translations('apps-forums-no_more_topics'); }, getStartIndex: function() { this.startIndex = this.startIndex + this.initParams.resultsPerPage; return this.startIndex; }, getPostData: function() { this.postData.startIndex = this.getStartIndex(); return this.postData; } }); function _formatDate(date) { var day = date.getDate(); var month = date.getMonth() + 1; var y = date.getYear(); var year = (y < 1000) ? y + 1900 : y; var h = date.getHours(); var hours = (h > 12) ? h - 12 : h; var tt = (h > 12) ? "PM" : "AM"; var m = date.getMinutes(); var minutes = (m < 10) ? '0' + m : m; var s = date.getSeconds(); var seconds = (s < 10) ? '0' + s : s; var dateTemplate = '[1]/[2]/[3] [4]:[5]:[6] [7]'; dateTemplate = dateTemplate.replace("[1]", month).replace("[2]", day).replace("[3]", year).replace("[4]", hours).replace("[5]", minutes).replace("[6]", seconds).replace("[7]", tt); return dateTemplate; } window.addEvent('domready', function() { if (Igloo && Igloo.asset_ajax_loadMore) { var instances; Object.each(Igloo.asset_ajax_loadMore, function(object, id) { object.triggerId = id; instances = new AjaxLoadMore(object); }); } });  var ajaxRating = new Class({ initialize: function(){}, // when the user clicks on a star to rate this object setRating: function(elem, percent){ var self = this; var apimethod = (elem.dataobj.isComment == 'true') ? 'comments/' : 'objects/'; apimethod += elem.dataobj.objId+'/rate'; var setRatingRequest = new ApiClient({ 'apimethod':apimethod, 'postdata':{ 'rating':percent }, onSuccess:function(text){ var returnjson = JSON.decode(text,true); if (returnjson) { self.updateMyRating(elem, percent); self.updateAverageRating(elem, returnjson); } } }); }, // does the visual magic to set the right number of stars for my rating updateMyRating: function(elem, percent){ var resp = percent / 100; var dividend = 5; var myprevstars = Math.round(resp * (dividend-1)) + 1 ; var myratingstars = elem; myratingstars.set('class', myratingstars.get('class').replace(/stars-[0-9]+/i,'') ); myratingstars.addClass('stars-'+ (myprevstars*10)); }, // does the visual magic to set the right number of stars for the average rating updateAverageRating: function(elem, apiResponse){ // Magic Box: first person to rate item, then need to make average rating visible if (elem.dataobj.isComment == 'false') { var firstElems = $$('dt.first').append($$('dd.first')); firstElems.each(function(elem){ if (elem.hasClass('js-rating')) { elem.removeClass('hide'); } else { elem.removeClass('first'); } }); } // update the voting count var voters = apiResponse.response.votes; var ratingaverage = apiResponse.response.average || 0; var dividend = 5; var granularity = 0.5; var averagestarsnum = Math.round( ratingaverage/100 * (dividend-1) * (1/granularity)) * granularity + 1; var averagestarclassname = 'stars-' + averagestarsnum*10; // this moves the decimal point over one var avgratingstars = $('js-rating-average_' + elem.dataobj.objId); avgratingstars.set('class', avgratingstars.get('class').replace(/stars-[0-9]+/i,'') ); avgratingstars.addClass(averagestarclassname); var voterTranslation = window.translations(voters == 1 ? 'macro-rating-vote' : 'macro-rating-votes'); avgratingstars.set('title', averagestarsnum+' '+window.translations('macro-rating-out_of')+' '+dividend+' ('+voters+' '+voterTranslation+')' ); } }); var igRating = new ajaxRating(); window.addEvent('domready', function(){ if (Igloo && Igloo.asset_ajaxRating) { Object.each(Igloo.asset_ajaxRating, function(object, id){ var elem = $(id); if (elem) { elem.dataobj = object; // allow me to rate this elem.getElements('li a').addEvent('click', function(event){ event.stop(); // get the inner html of this anchor as an Integer var percent = event.target.get('html').toInt(); // set the rating I've chosen igRating.setRating(elem, percent); }); } }); } }); var Heartbeat = new Class({ Implements: [Options], options: { lifespan: (3 * 60 * 60 * 1000), // milliseconds until you get a warning = 3 hours heartrate: (5 * 60 * 1000), // milliseconds between palpitations = 5 minutes sessiontimeout: (20 * 60 * 1000), // milliseconds until session times out on the platform = 20 minutes (IglooConstants.HEARTBEAT_EXPIRY_DURATION) apimethod: 'igloo/heartbeat', objectId: null, context: null, onSuccess: $empty }, initialize: function(options){ // set the options this.setOptions(options || {}); this.heartstoppedtime = null; this.sessionisalive = true; this.beatimmediately = false; // listen to these events and take note of when the last activity/event happened. this.boundNoteActivity = this.noteActivity.bind(this); window.addEvents({ 'mouseup': this.boundNoteActivity, 'focus': this.boundNoteActivity, 'scroll': this.boundNoteActivity, 'keyup': this.boundNoteActivity }); // begin the palpitations! this.startHeartbeat(); }, // noteActivity is called when a listener notices the user has done some work. noteActivity: function(e){ this.lastActivity = (new Date).getTime(); }, startHeartbeat:function(){ if(this.sessionisalive){ // if the session is dead, there's no bringing it back if(this.heartbeat){ this.endHeartbeat(); } if(this.beatimmediately){ this.palpitate(); this.beatimmediately = false; } this.heartbeat = this.palpitate.periodical(this.options.heartrate, this); document.fireEvent('heartbeat_start'); } }, endHeartbeat:function(){ this.heartbeat = clearInterval(this.heartbeat); document.fireEvent('heartbeat_end'); }, // palpitate is the one that's poking the api at a set interval. // it also looks at when the last activity occured and after 3 hours go by it shows the lastRites modal. palpitate: function(){ var timeNow = (new Date).getTime(); this.lastActivity = this.lastActivity || timeNow; // this eliminates NaN if the user has never done any activity on the page.. a pretty rare edge case var timeSinceLastActivity = timeNow - this.lastActivity; if( timeSinceLastActivity >= this.options.lifespan && this.heartstoppedtime == null ){ // start the countdown to stop palpitation unless the user intervines this.lastRitesSwitch(this.options.context==null?this:this.options.context); } if( this.sessionisalive ){ //console.log('palpitation'); this.palpitation = new ApiClient({ 'apimethod': this.options.apimethod, 'method': 'get', 'queryparams':{ 'objectId':this.options.objectId }, onSuccess:function(text){ var json = JSON.decode(text,true); this.options.onSuccess(json.response, this); }.bind(this) }); } }, lastRitesSwitch:function(context){ context.lastRites(this); }, lastRites:function(context){ //console.log('last rites'); // so, time has elapsed (three hours by default). Let's check now if the user has a persistent session // put this page on DNR this.endHeartbeat(); document.fireEvent('heartbeat_lastrites'); // open a modalbox with the last rites warning this.lastritesmodal = new Modalbox({ 'title':window.translations('media-js-heartbeat-your-session-will-expire') }); var modalcontent = this.lastritesmodal.bodypart; var ritesdiv = new Element('div').inject(modalcontent,'top'); var modalpad = new Element('div', {'class':'ig-modal-pad'}).wraps(modalcontent); var warning = new Element('p', { 'styles':{ 'text-align':'center' }, 'html': [ window.translations('media-js-heartbeat-page-idle-warning-part1'), '', (Math.round(this.options.lifespan / (60*60*1000) * 100) / 100), ' ', window.translations('media-js-heartbeat-hours'), '. ', window.translations('media-js-heartbeat-session-will-expire-warning') ].join('') }).inject(ritesdiv,'bottom'); this.countdowndiv = new Element('div',{ 'id':'lastritescountdown', 'styles':{ 'text-align':'center' }, 'html':' ' }).inject(ritesdiv,'bottom'); var checkbuttonwrap = new Element('div',{ 'styles':{ 'text-align':'center', 'margin-top':'20px' } }).inject(ritesdiv,'bottom'); var checkbutton = new Element('input',{ 'type':'button', 'value':window.translations('media-js-heartbeat-keep-my-session-alive'), 'styles':{ 'margin-left':'auto', 'margin-right':'auto' }, 'class':'ig-button ig-button_blue ig-bold' }).addEvent('click',function(){ this.lastritesmodal.close(); }.bind(this)).inject(checkbuttonwrap,'bottom'); this.lastritesmodal.addEvent('close',function(){ // when you close the modal, it'll be the same as if you clicked the button. //console.log('self.sessionisalive ' + self.sessionisalive); this.endHeartbeat(); if(this.sessionisalive){ this.beatimmediately = true; this.startHeartbeat(); this.endSessionCountdown(); } }.bind(this)); this.lastritesmodal.adjustposition(); // Start the countdown this.startSessionCountdown(); }, startSessionCountdown:function(){ if(this.sessionisalive){ // if the session is dead, there's no bringing it back // we'll refresh the countdown every 500ms? even though we show countdown in seconds.. // i guess this is to aid in any ui glitches that would make seconds seem longer? this.heartstoppedtime = (new Date()).getTime();//dddd.getTime(); if(this.options.sessiontimeout <= 0){ this.sessionIsDead(); } else { this.sessioncountdown = this.sessionCountdown.periodical(500, this); } } }, endSessionCountdown:function(){ this.sessioncountdown = clearInterval(this.sessioncountdown); this.heartstoppedtime = null; }, sessionCountdown:function(){ //console.log('sessionCountdown'); if( this.countdowndiv ){ var h = this.heartstoppedtime; // in milliseconds // how many seconds have elapsed var dddd = new Date(); var nowtime = dddd.getTime(); // also in milliseconds var flatline = nowtime - h; var secondstodie = Math.floor( (this.options.sessiontimeout - flatline) / 1000 ); var minutes = Math.floor(secondstodie/60); var seconds = secondstodie - (minutes * 60); // Update the screen this.sessionCountdownUpdateSwitch(this.options.context==null?this:this.options.context, minutes, seconds); if(secondstodie <= 0){ //alert('your session has timed out.'); this.sessionIsDead(); //console.log('this.sessionisalive ' + this.sessionisalive); } } }, sessionCountdownUpdateSwitch:function(context, minutes, seconds){ context.sessionCountdownUpdate(this, minutes, seconds); }, sessionCountdownUpdate:function(context, minutes, seconds){ this.countdowndiv.set('html', window.translations('media-js-heartbeat-your-session-will-expire-in-colon') + minutes + window.translations('media-js-heartbeat-minsec-separator') + Utils.zeroPad(seconds,2)); }, sessionIsDead:function(){ // session is dead, tell the user. it would be nice if we could just show them a login form and restart the session.. but we can't :( this.sessionisalive = false; this.endSessionCountdown(); this.endHeartbeat(); // Update the screen this.sessionIsDeadUpdateSwitch(this.options.context==null?this:this.options.context); if(this.lastritesmodal){ this.lastritesmodal.adjustposition(); } document.fireEvent('heartbeat_sessionisdead'); }, sessionIsDeadUpdateSwitch:function(context){ context.sessionIsDeadUpdate(this); }, sessionIsDeadUpdate:function(context){ if (this.lastritesmodal) { this.lastritesmodal.setcontents(window.translations('media-js-heartbeat-your-session-expired')); this.lastritesmodal.settitle(window.translations('media-js-heartbeat-session-expired')); } } }); window.addEvent('domready',function(){ if (Igloo && Igloo.asset_Heartbeat) { var cardio; Object.each(Igloo.asset_Heartbeat, function(object, id){ cardio = new Heartbeat(object); }); } }); var ReservationKeepAlive = new Class({ Implements: [Options], options: { lifespan: (2 * 60 * 60 * 1000), // milliseconds until you get a warning = 2 hours heartrate: (15 * 1000), // milliseconds between palpitations = 15 seconds sessiontimeout: (5 * 60 * 1000), // milliseconds until session times out on the platform = 5 minute objectId: null, isInQueue: false, curtain: 'js-reservation-curtain', notice: 'js-reservation-notice' }, initialize: function(trigger, options){ // set the options this.setOptions(options || {}); // No timeout if (this.options.isInQueue) { this.options.sessiontimeout = 0; } // Render overlay this.curtain = $(this.options.curtain); if (this.curtain) { var overlayHeight = $(trigger).getHeight(); this.notice = $(this.options.notice); if (this.notice) { overlayHeight = overlayHeight - this.notice.getHeight(); } this.overlay = this.curtain.getElements('.ig-curtain-overlay')[0]; this.overlay.setStyle('height', overlayHeight); } // Define the heartbeat this.reservationBeat = new Heartbeat({ 'lifespan':this.options.lifespan, 'heartrate':this.options.heartrate, 'sessiontimeout':this.options.sessiontimeout, 'apimethod':'igloo/reservationbeat', 'objectId':this.options.objectId, 'context':this, 'onSuccess':function(response, context){ if (this.options.isInQueue) { // The user is waiting their turn to edit if (response == null) { // Reservation freed up! Refresh the page! this.availableBox = new Modalbox({ 'width':300, 'draggable':false, 'title':window.translations('system-reserve-reservation_is_yours'), 'onClose':function(){ // refresh the page document.location = document.location.toString().split('#')[0]; } }).setcontents('
'+window.translations('system-reserve-refreshing_the_page')+'
'); this.pageRefresh = function(){ document.location = document.location.toString().split('#')[0]; }.delay(2000, this); // 2 seconds delay } else { // Reservation is still held by another person // DO NOTHING } } else { // The user is holding reservation if (response == null) { // Reservation is still there... // DO NOTHING } else { // Oops! Someone has stolen the reservation! this.thief = new ApiClient({ 'apimethod': 'users/' + response.createdEventStamp.userId, 'method': 'get', onSuccess:function(text){ var json = JSON.decode(text,true); this.alertReserveSteal(json.response.name.fullName, context); }.bind(this), onFailure:function(){ this.alertReserveSteal('', context); }.bind(this) }); } } }.bind(this) }) }, alertReserveSteal:function(thiefName, context){ context.sessionIsDead(); this.oopsBox = new Modalbox({ 'width':300, 'blanketcolor':'#101000', 'shadowcolor':'#FFF099', 'draggable':false, 'title':'Caution!' }).setcontents('
' + '

' + (thiefName==''?window.translations('system-reserve-reservation_taken_away_by_unknown'):window.translations('system-reserve-reservation_taken_away_by')+''+thiefName+'') + '

' + '
'+ window.translations('system-reserve-reservation_taken_away-info') + '
' + '
'); }, lastRites:function(context){ // Don't stop the heartbeat! // open a modalbox with the last rites warning if (this.options.isInQueue) { context.lastritesmodal = new Modalbox({ 'title':window.translations('system-reserve-queue_idle'), 'draggable':false }); var modalcontent = context.lastritesmodal.bodypart; var modalpad = new Element('div', {'class':'ig-modal-pad'}).wraps(modalcontent); // Refresh the page on close context.lastritesmodal.addEvent('close',function(){ document.location = document.location.toString().split('#')[0]; }); } else { context.lastritesmodal = new Modalbox({ 'title':window.translations('system-reserve-your_reservation_will_expire'), 'draggable':false }); var modalcontent = context.lastritesmodal.bodypart; var ritesdiv = new Element('div').inject(modalcontent,'top'); var modalpad = new Element('div', {'class':'ig-modal-pad'}).wraps(modalcontent); var warning = new Element('p', { 'html': [ window.translations('system-reserve-page_idle_warning'), '', (Math.round(this.options.lifespan / (60*60*1000) * 100) / 100), ' ', window.translations('media-js-heartbeat-hours'), '. ', window.translations('system-reserve-reservation_will_expire_warning') ].join('') }).inject(ritesdiv,'bottom'); context.countdowndiv = new Element('div',{ 'id':'lastritescountdown', 'styles':{ 'text-align':'center' }, 'html':' ' }).inject(ritesdiv,'bottom'); var checkbuttonwrap = new Element('div',{ 'styles':{ 'text-align':'center', 'margin-top':'20px' } }).inject(ritesdiv,'bottom'); var checkbutton = new Element('input',{ 'type':'button', 'value':window.translations('system-reserve-keep_my_reservation_alive'), 'styles':{ 'margin-left':'auto', 'margin-right':'auto' }, 'class':'ig-button ig-button_blue ig-bold' }).addEvent('click',function(){ context.lastritesmodal.close(); }.bind(this)).inject(checkbuttonwrap,'bottom'); context.lastritesmodal.addEvent('close',function(){ // when you close the modal, it'll be the same as if you clicked the button. context.endHeartbeat(); if(context.sessionisalive){ context.beatimmediately = true; context.startHeartbeat(); context.endSessionCountdown(); } }.bind(context)); } context.lastritesmodal.adjustposition(); // Start the countdown context.startSessionCountdown(); }, sessionCountdownUpdate:function(context, minutes, seconds){ context.countdowndiv.set('html', window.translations('system-reserve-your_reservation_will_expire_in_colon') + minutes + window.translations('media-js-heartbeat-minsec-separator') + Utils.zeroPad(seconds,2)); }, sessionIsDeadUpdate:function(context){ if (context.lastritesmodal) { if (this.options.isInQueue) { context.lastritesmodal.setcontents(window.translations('system-reserve-queue_idle-info')); } else { context.lastritesmodal.setcontents(window.translations('system-reserve-your_reservation_expired')); context.lastritesmodal.settitle(window.translations('system-reserve-reservation_expired')); } } } }); window.addEvent('domready',function(){ if (Igloo && Igloo.asset_app_reservation) { var liveReservation; Object.each(Igloo.asset_app_reservation, function(object, id){ liveReservation = new ReservationKeepAlive(id, object); }); } }); window.addEvent('domready', function(){ if ( Igloo && Igloo.asset_app_pageHeaderSearch ){ var elements = []; Object.each(Igloo.asset_app_pageHeaderSearch, function(object, id){ var elem = $(id); if (elem){ if (!elem.dataobj || typeOf(elem.dataobj)!='hash'){ elem.dataobj = new Hash(elem.dataobj || object); } elem.dataobj.combine(object); elements.push(elem); } }); elements.each(function(elem){ // Create the igDropdown var menu = new igDropdown(elem.dataobj.igDropdown.trigger, null, elem.dataobj.igDropdown.options); }); } });var jsGroupSubscription = new Class({ Implements: [Options, Events], options:{ 'groupId':null, 'objId':null, 'parentId':null, 'frequency':'Never', 'subExists':'False' }, initialize:function(trigger, options){ var self = this; self.setOptions(options || {}); var groupId = self.options.groupId; //var therow = $(trigger); // Search Area /*var addMoreSubButton = $('js-groupSubAdd'); var addMoreSub = $('js-groupSubSearch'); if(addMoreSubButton){ var addSubscription = new Fx.Slide(addMoreSub, { duration: 400, transition: Fx.Transitions.linear.easeOut }).hide(); addMoreSubButton.addEvent('click', function(event){ event.stop(); addSubscription.toggle(); }); }*/ self.response = {}; self.elements = {}; self.elements.trigger = $(trigger); self.elements.freqdiv = $("freqdiv_"+groupId); self.elements.subExist = $("subExists_"+groupId); //console.log(therow); //console.log(self); //console.log("got here!"); //button var btnInstant = $("frequency_Instant_"+groupId); var btnDaily = $("frequency_Daily_"+groupId); var btnWeekly = $("frequency_Weekly_"+groupId); var btnMonthly = $("frequency_Monthly_"+groupId); var btnNone = $("frequency_None_"+groupId); //adding events btnInstant.addEvent("click", function(){ self.updateFreq("Instant"); }); btnDaily.addEvent("click", function(){ self.updateFreq("Daily"); }); btnWeekly.addEvent("click", function(){ self.updateFreq("Weekly"); }); btnMonthly.addEvent("click", function(){ self.updateFreq("Monthly"); }); btnNone.addEvent("click", function(){ self.updateFreq("Never"); }); }, updateFreq:function(frequency){ var self = this; self.options.frequency = frequency; if(self.options.subExists == 'True'){ //it exists, lets update self.gsupdate(); } else{ //it doesn't exist, lets make it self.gscreate(); } }, gscreate:function(){ var self = this; if(self.options.frequency != "Never"){ //========================= AJAX - ADD GROUP SUBSCRIPTION ============================= var gscreateViaAjax = new ApiClient({ 'headers':{'Accept': 'application/xml'}, 'apimethod':'groupsubscriptions/add', 'queryparams':{ 'paramList':'objectId,parentId,groupId,frequency', 'paramTypes':'id,id,id,string' }, 'postdata':{ 'groupId':self.options.groupId, 'objectId':self.options.objId, 'parentId':self.options.parentId, 'frequency':self.options.frequency }, onRequest:function(instance){ window.fireEvent( "gscreateRequest" + self.options.objectId ); }, onSuccess:function(text,xml){ //window.fireEvent("gscreateSuccess"); self.response.frequency = self.options.frequency; var freqdiv = $("freqdiv_"+self.options.groupId); freqdiv.set("html", window.translations('admin-groups-'+self.response.frequency)); //create the hidden input so that the next time we do something with this group, the info is updated self.options.subExists = "True"; }, onFailure:function(instance){ // Handle Exceptions if(this.status != null) { if (this.status == "404") { // Object is gone - refresh the page and behold document.location = document.location.toString().split('#')[0]; } else if (this.status == "403") { // Object is permed - refresh the page and behold document.location = document.location.toString().split('#')[0]; } else if (this.status == "422") { // Subscription already exists self.gsupdate(); } else { window.fireEvent( "gscreateFailure" + self.options.objectId ); } } else { window.fireEvent( "gscreateFailure" + self.options.objectId ); } } }); } else{ //do nothing, it was already none. self.options.subExists = "False"; //lets just make sure. this is a redundancy check } }, gsupdate:function(){ var self = this; if(self.options.frequency != "Never"){ //========================= AJAX - MODIFY GROUP SUBSCRIPTION ============================= var gsupdateViaAjax = new ApiClient({ 'headers':{'Accept': 'application/xml'}, 'apimethod':'groupsubscriptions/update', 'queryparams':{ 'paramList':'objectId,groupId,frequency', 'paramTypes':'id,id,string' }, 'postdata':{ 'groupId':self.options.groupId, 'objectId':self.options.objId, 'frequency':self.options.frequency }, onRequest:function(instance){ window.fireEvent( "gsupdateRequest" + self.options.objectId ); }, onSuccess:function(text,xml){ self.response.frequency = self.options.frequency; var freqdiv = $("freqdiv_"+self.options.groupId); freqdiv.set("html", window.translations('admin-groups-' + self.response.frequency)); self.options.subExists = "True"; }, onFailure:function(instance){ // Handle Exceptions if(this.status != null) { if (this.status == "404") { // Object is gone - refresh the page and behold document.location = document.location.toString().split('#')[0]; } else if (this.status == "403") { // Object is permed - refresh the page and behold document.location = document.location.toString().split('#')[0]; } else if (this.status == "422") { // Subscription already exists window.fireEvent( "gsupdateSuccess", null ); } else { window.fireEvent( "gsupdateFailure" + self.options.objectId ); } } else { window.fireEvent( "gsupdateFailure" + self.options.objectId ); } } }); } else{ //deleting the subscription, frequency = "None" //========================= AJAX - DELETE GROUP SUBSCRIPTION ============================= var gsupdateViaAjax = new ApiClient({ 'headers':{'Accept': 'application/xml'}, 'apimethod':'groupsubscriptions/delete', 'queryparams':{ 'paramList':'objectId,groupId', 'paramTypes':'id,id' }, 'postdata':{ 'groupId':self.options.groupId, 'objectId':self.options.objId }, onRequest:function(instance){ window.fireEvent( "gsdeleteRequest" + self.options.objectId ); }, onSuccess:function(text,xml){ self.response.frequency = self.options.frequency; var freqdiv = $("freqdiv_"+self.options.groupId); freqdiv.set("html", ""); //blank it //remove the hidden input self.options.subExists = "False"; }, onFailure:function(instance){ // Handle Exceptions if(this.status != null) { if (this.status == "404") { // Object is gone - refresh the page and behold document.location = document.location.toString().split('#')[0]; } else if (this.status == "403") { // Object is permed - refresh the page and behold document.location = document.location.toString().split('#')[0]; } else if (this.status == "422") { // Subscription already exists window.fireEvent( "gsdeleteSuccess", null ); } else { window.fireEvent( "gsdeleteFailure" + self.options.objectId ); } } else { window.fireEvent( "gsdeleteFailure" + self.options.objectId ); } } }); } }// /gsupdate }); window.addEvent('domready', function(){ if (Igloo && Igloo.asset_groupSubscription) { var groupsub; Object.each(Igloo.asset_groupSubscription, function(object, id){ groupsub = new jsGroupSubscription(id, object); }); } }); function applyAjaxInlineedit(elements){ var toolsjson = { "H1": "input", "H2": "input", "H3": "input", "H4": "input", "H5": "input", "H6": "input", "DIV": "input", "DL": "input", "DT": "input", "CODE": "textarea", "P": "textarea", "BLOCKQUOTE": "textarea", "B": "input", "U": "input", "I": "input", "SPAN": "input", "LI": "input" }; var stylepropertyjson = { "props": [{ "prop": "fontFamily", "css": "font-family" }, { "prop": "fontStyle", "css": "font-style" }, { "prop": "fontWeight", "css": "font-weight" }, { "prop": "textAlign", "css": "text-align"}] }; elements.each(function(elem) { if (elem.dataobj) { var dataobj = JSON.decode(elem.dataobj) || elem.dataobj; var self = this; if (dataobj.inlineedit) { var motionDeleted = $('js-motionDeleted') if (motionDeleted) { // no edit on deleted motions } else { elem.addClass('eip'); // this puts some styling on it, with the hover effect, etc. elem.onclick = function(e) { var dataobj = JSON.decode(elem.dataobj) || elem.dataobj; var objectid = dataobj.inlineedit.objectid; var objectidwithouthyphensorcurlies = objectid.replace(/\-/g, '').replace(/\{/g, '').replace(/\}/g, ''); var safetymargin = 5; var multilingual = dataobj.multilingual; if (!multilingual) { elem.oldvalue = elem.innerHTML; } else { //multilingual exists self.languages = multilingual.languages.split(","); self.oldvalue = []; self.languages.each(function(lang){ self.oldvalue[lang] == $("id_"+objectid+"_"+lang).get('value'); }); } // the element that contains the value is not always the element that was clicked. // targetelement is the element that gets hidden and replaced with the form var targetelement = elem; if (dataobj.inlineedit.targetelement) { targetelement = $(dataobj.inlineedit.targetelement); } // put some more references into the elem elem.targetelement = targetelement; elem.objectid = objectid; var elemcoords = targetelement.getCoordinates(); var eip = new Element('div', { 'id': 'eip' }); eip.setStyle('display', 'block'); eip.controlelement = elem; var tatype = "input"; if (dataobj.inlineedit.withmultiline) { if (dataobj.inlineedit.withmultiline == 'true') { tatype = "textarea"; } } else { if (toolsjson[targetelement.tagName] == "textarea") { tatype = "textarea"; } } if (tatype == "textarea") { var ta = new Element('textarea', { 'class': 'eipta', 'styles': { 'display': 'block', 'width': (elemcoords.width - targetelement.getStyle('padding-left').toInt() - targetelement.getStyle('padding-right').toInt() - safetymargin) + 'px', 'height': (elemcoords.height - targetelement.getStyle('padding-top').toInt() - targetelement.getStyle('padding-bottom').toInt()) + 'px', 'top': elemcoords.top + 5 + 'px', 'left': elemcoords.left + 'px', 'z-index': 90 } }); } else { if (!multilingual){ var ta = new Element('input', { 'style': 'font-size:1em;', 'class': 'eipta', 'type': 'text', 'maxlength': dataobj.inlineedit.maxlength || '250' }); // apply element styles to the editor, so it looks similar for (var m = 0; m < stylepropertyjson.props.length; m++) { ta.style[stylepropertyjson.props[m].prop] = targetelement.getStyle(stylepropertyjson.props[m].css); } } else { //build out the multiple inputs, each with the proper class self.ta = {}; self.tf = {}; // the flag for auto-translate, should be in DOM already as a hidden input field self.ot = {}; // tracking the original text, so that we can determine if it has changed self.languages.each(function(lang){ //each input is a self.ta[lang] self.ta[lang] = new Element('input', { 'style': 'font-size:1em;', 'class': 'eipta lang-pane', 'type': 'text', 'maxlength': dataobj.inlineedit.maxlength || '250' }); for (var m = 0; m < stylepropertyjson.props.length; m++) { self.ta[lang].style[stylepropertyjson.props[m].prop] = targetelement.getStyle(stylepropertyjson.props[m].css); } }); } } // add the buttons var tbutts = new Element('div', { 'class': 'eipbutts' }); var tform = new Element('form', { 'class': 'eipform module', 'method': 'get', 'action': '' }); var tsave = new Element('input', { 'class': 'ig-button ig-bold js-submitbutton', 'type': 'button', 'value': dataobj.inlineedit.savetext, 'disabled': 'true' }); var tcancel = new Element('input', { 'class': 'ig-button ig-button_gray', 'type': 'button', 'value': (dataobj.inlineedit.canceltext) ? (dataobj.inlineedit.canceltext) : window.translations('comps-title-Cancel') }); // assemble the structure tsave.inject(tbutts, 'bottom'); tcancel.inject(tbutts, 'bottom'); if (!multilingual){ ta.inject(tform, 'bottom'); } else { var ttabcontainer = new Element('div'); var tpanes = new Element('div', { 'class':'panes' }); var ttabs = new Element('div', { 'class':'tabs langtabs' }); ttabs.inject(tform, 'bottom'); tpanes.inject(tform, 'bottom'); self.languages.each(function(lang){ if (lang != multilingual.defaultlang){ self.ta[lang].addClass('hide'); } self.ta[lang].inject(tpanes, 'bottom'); var langtab = new Element('span',{ 'class':'tab', 'html':window.translations('admin-lang-code_'+lang) }); if (lang == multilingual.defaultlang){ langtab.addClass('ig-activeTab'); } langtab.inject(ttabs, 'bottom'); }); var tabs = new jsTabs(null,null,{ 'tabsClass':'tab', 'panesClass':'lang-pane', 'container':tform, 'locationchange':false }); } tbutts.inject(tform, 'bottom'); tform.inject(eip, 'bottom'); eip.inject(targetelement, 'before'); targetelement.addClass('hide'); // add references to these elements on elem elem.tsave = tsave; elem.tcancel = tcancel; elem.tbutts = tbutts; elem.tform = tform; elem.eip = eip; if (!multilingual){ elem.ta = ta; // if there's an action img, hide it. if ($('link_' + objectidwithouthyphensorcurlies)) { $('link_' + objectidwithouthyphensorcurlies).addClass('hide'); } // if the value is empty, disable the save button if (ta.value.trim() == '') { tsave.disabled = (ta.value.trim() == ''); } // add events ta.onkeyup = function() { tsave.disabled = (ta.value.trim() == ''); } } else { if ($('link_' + objectidwithouthyphensorcurlies)) { $('link_' + objectidwithouthyphensorcurlies).addClass('hide'); } var allisempty = true; self.languages.each(function(lang){ ta_elem = self.ta[lang]; allisempty = false; }); if (!allisempty){ tsave.disabled = true; } } tform.onsubmit = function() { elem.saveit(multilingual); return false; } tcancel.onclick = function(e) { elem.cancelit(); return false; } tsave.onclick = function(e) { elem.saveit(multilingual); return false; } if (!multilingual){ ta.onkeyup = function() { enablesubmitbutton(); } } else { self.languages.each(function(lang){ self.ta[lang].addEvent('keyup', function(){ enablesubmitbutton(); }); }); } var enablesubmitbutton = function() { if (!multilingual){ if (ta.value.trim().length > 0) { tsave.disabled = false; } else { tsave.disabled = true; } } else { trimgood = false; self.languages.each(function(lang){ if (self.ta[lang].value.trim().length > 0){ trimgood = true; } }); if (trimgood){ tsave.disabled = false; } else { tsave.disabled = true; } } } var newvalue = targetelement.get('text'); if (!multilingual){ ta.set('value', newvalue); ta.focus(); ta.select(); } else { var targetbase = targetelement.get('id'); self.languages.each(function(lang){ self.ta[lang].set('value', $(targetbase+"_"+lang).get('value')); self.ot[lang] = $(targetbase+"_"+lang).get('value'); self.tf[lang] = $(targetbase+"_"+lang+"_auto").get('value'); }); } enablesubmitbutton(); return false; } // end of elem.onclick } /****************************************************/ /* DEFINE THE SAVEIT FUNCTION, AS AN OBJECT OF ELEM */ /****************************************************/ elem.saveit = function(multilingual) { var elem = this; var dataobj = JSON.decode(elem.dataobj) || elem.dataobj; var eip = elem.eip; var ta = elem.ta; var tbutts = elem.tbutts; var targetelement = elem.targetelement; var objectid = elem.objectid; var objectidwithoutcurlies = objectid.replace(/\{/g, '').replace(/\}/g, ''); var objectidwithouthyphensorcurlies = objectid.replace(/\-/g, '').replace(/\{/g, '').replace(/\}/g, ''); /* display a saving message */ tbutts.empty(); var savingmessage = new Element('div', { 'id': 'savingmessage' + objectid, 'class': 'savingmessage normal' }).set('html', decodeURIComponent(dataobj.inlineedit.savingmessage)).inject(tbutts, 'bottom'); var postdata = {}; if (!multilingual){ var newvalue = ta.value; postdata.title = newvalue; } else { self.languages.each(function(lang){ postdata['title_'+lang] = self.ta[lang].get('value'); //if tf[lang] was true, then check to see if it was changed. if changed, it's now false if (self.tf[lang] == "true"){ if (self.ta[lang].get('value') != self.ot[lang]){ self.tf[lang] = "false"; } } postdata['title_'+lang+'_auto'] = self.tf[lang]; }); } var renameajax = new ApiClient({ 'apimethod': 'objects/' + objectid + '/rename', 'postdata':postdata, 'sendimmediately': false, onRequest: function() { targetelement.addClass('hide'); }, onSuccess: function() { var returnstring = this.response.text; var returnjson = JSON.decode(returnstring, true); if (returnjson != null) { if (multilingual){ var targetbase = targetelement.get('id'); self.languages.each(function(lang){ $(targetbase+"_"+lang).set('value', self.ta[lang].get('value')); }); } if (returnjson.response.value) { targetelement.set('text', Utils.htmldecode(returnjson.response.value)); } // since this was a success, rename other things on the page too // this does a rename on the navigation, and should be removed if a generalized class is to be made: var otherelems = $$('.datum-nameof-' + objectidwithoutcurlies); otherelems.each(function(otherelem) { otherelem.set('text', Utils.htmldecode(returnjson.response.value)); }); if (multilingual){ if (self.tf[multilingual.defaultlang] == "false" && $("AT_"+objectid+"_title")){ $("AT_"+objectid+"_title").addClass('hide'); } } else { document.title = document.title.replace(new RegExp(elem.oldvalue.escapeRegExp(), ''), newvalue); } if ($('savingmessage' + objectid)) { $('savingmessage' + objectid).destroy(); } targetelement.removeClass('hide'); eip.destroy(); } else { $('savingmessage' + objectid).destroy(); targetelement.removeClass('hide'); eip.destroy(); } // if action img exists, it was hidden. So show it now. var actionimgid = 'link_' + objectidwithouthyphensorcurlies; if ($(actionimgid)) { $(actionimgid).removeClass('hide'); } }, onFailure: function() { // fail. $('savingmessage' + objectid).destroy(); targetelement.removeClass('hide'); eip.destroy(); // if action img exists, show it. var actionimgid = 'link_' + objectidwithouthyphensorcurlies; if ($(actionimgid)) { $(actionimgid).removeClass('hide'); } } }); try { renameajax.send(); } catch (err) { $('savingmessage' + objectid).destroy(); targetelement.removeClass('hide'); eip.destroy(); } } /****************************************************/ /* DEFINE THE CANCELIT FUNCTION, AS AN OBJECT OF ELEM */ /****************************************************/ elem.cancelit = function() { var elem = this; var dataobj = JSON.decode(elem.dataobj) || elem.dataobj; var eip = elem.eip; var tbutts = elem.tbutts; var targetelement = elem.targetelement; var objectid = elem.objectid; var objectidwithouthyphensorcurlies = objectid.replace(/\-/g, '').replace(/\{/g, '').replace(/\}/g, ''); targetelement.removeClass('hide'); eip.destroy(); // if there's an action img, it was hidden. So show it now. var actionimgid = 'link_' + objectidwithouthyphensorcurlies; if ($(actionimgid)) { $(actionimgid).removeClass('hide'); } } } // end if: the dataobj for this elem contains "inlineedit" } // end if: the elem contains a dataobj }); } window.addEvent('domready', function(){ if (Igloo && Igloo.asset_inlineedit) { var elements = []; Object.each(Igloo.asset_inlineedit, function(object, id) { var elem = $(id); if (!elem.dataobj || typeOf(elem.dataobj) != 'hash') { elem.dataobj = new Hash(elem.dataobj || object); } elem.dataobj.combine(object); elements.push(elem); }); applyAjaxInlineedit(elements); } }); window.addEvent('bootstrap4finished', function(){ var elements = window.dependents['inlineedit'] || []; applyAjaxInlineedit(elements); }); /* @js: manageGroup @Purpose/Description: Calls an API method that returns a list of users to add or remove from a group Uses the auto complete user search to add users Interface is via one modal box @Last Modified: February 10th 2013 @copyright: Copyright � 2011, IGLOO Software, All rights reserved. */ var manageGroup = new Class({ Implements: [Options, Events], options: { 'id': null, 'name': "", 'action': "", 'blockRename': false, 'blockModify': false, 'blockSelf': false, 'spaceId': null, 'spaceTitle': '', 'canCreateInCommunity': false, 'injectNewMemberGroupHere': '', 'injectNewSpaceGroupHere': '', 'userId': null, 'igDropdown': null, 'blockdelete': false, 'tablelayout': false // used for a create action, to control what type of element is added. }, /* instance vars */ name: "", trigger: null, modalElements: {}, groupTypes: { ADMIN: 1, MEMBERS: 0 }, usersInGroup: [], originalUsers: [], initialize: function(trigger, options) { var self = this; this.setOptions(options || {}); this.name = Utils.htmldecode(self.options.name); this.trigger = $(trigger); this.addEvents(); }, addEvents: function() { this.trigger.addEvent('click', function(event) { event.preventDefault(); this.create(); } .bind(this)); } .protect(), buildModalDialog: function() { // modal buttons this.buildModalButtons(); this.buildModalInputFields(); if (!this.options.blockModify) { this.buildModalGroupNameElement(); } this.buildModalGroupCore(); } .protect(), buildModalButtons: function() { var self = this; this.modalElements.buttons = new Element('div', { 'class': 'modalfooter' }).adopt( new Element('input', { 'tabindex': '3', 'type': 'button', 'class': 'ig-button ig-button_gray ig-right', 'value': window.translations('comps-message-Cancel') }).addEvent('click', function() { self.close(); }), new Element('input', { 'tabindex': '2', 'type': 'button', 'class': 'ig-button ig-bold js-submitbutton', 'value': ((this.options.action.ciCompare('create')) ? window.translations('system-access-Create') : window.translations('system-access-Update')) }).addEvent('click', function() { self.makeChanges(); }) ); } .protect(), buildModalInputFields: function() { //Group name input field this.modalElements.inputField = new Element('div', { 'class': 'ig-formitem ig-mediummarginbottom' }).adopt( new Element('label', { 'for': 'group_name', 'html': window.translations('system-access-Group_Name') + ':' }), new Element('div', { 'class': 'ig-text ig-nomargin' }).adopt( new Element('span').adopt( new Element('input', { 'tabindex': '1', 'autocomplete': 'off', 'type': 'text', 'name': 'group_name', 'class': 'js-group_name', 'id': 'group_name', 'value': this.name, 'maxlength': '100' }) ) ) ); //User search input field this.modalElements.tempPeopleToAddInputElem = new Element('input', { 'tabindex': '1', 'autocomplete': 'off', 'type': 'text', 'name': 'temp_peopleToAdd', 'class': 'ig-peopleToAdd js-temp_peopleToAdd', 'id': 'temp_peopleToAdd' }); } .protect(), buildModalGroupNameElement: function() { // Group Name this.modalElements.groupNameElem = new Element('div'); this.modalElements.peopleToAdd = new Element('div', { 'class': 'ig-modalmembersAdd' }).adopt( new Element('div', { 'class': 'title' }).adopt( new Element('span', { 'class': 'text ig-recipients-box' }).adopt( new Element('span', { 'class': 'ig-access-adduser ig-left', 'html': window.translations('system-access-Add_user'), 'title': window.translations('system-access-Add_user') }), this.modalElements.tempPeopleToAddInputElem ) ) ).addEvent('keypress', function(event) { if (event.key.toLowerCase() == 'enter') { return false; } }); if (this.options.action == 'create' && this.options.spaceId == null && !this.options.blockRename) { this.modalElements.groupNameElem.adopt(this.modalElements.inputField); } else if (!this.options.blockModify && this.options.action == 'create') { // Set field to blank as an alternative one will be displayed this.modalElements.inputField = ''; // Figure out which scope options to show var selectField = new Element('select', { 'class': 'js-selectedOption' }) if (this.options.canCreateInCommunity) { selectField.adopt( new Element('option', { 'html': this.options.spaceTitle, 'value': 'true' }), new Element('option', { 'html': window.translations('system-access-Community'), 'value': 'false' }) ); } else { selectField.adopt( new Element('option', { 'html': this.options.spaceTitle, 'value': 'true' }) ); } this.modalElements.groupNameElem.adopt( new Element('div', { 'class': 'ig-formitem ig-mediummarginbottom ig-clearfix' }).adopt( new Element('div', { 'class': ' ig-width175 ig-right' }).adopt( new Element('label', { 'for': 'where', 'html': window.translations('system-access-Where') + ':' }), new Element('div', { 'class': 'ig-select ig-nomargin', 'id': 'where' }).adopt( new Element('span').adopt(selectField) ) ), new Element('div', { 'class': 'ig-width175 ig-left' }).adopt( new Element('label', { 'for': 'group_name', 'html': window.translations('system-access-Group_Name') + ':' }), new Element('div', { 'class': 'ig-text ig-nomargin' }).adopt( new Element('span').adopt( new Element('input', { 'tabindex': '1', 'autocomplete': 'off', 'type': 'text', 'name': 'group_name', 'class': 'js-group_name', 'value': this.name }) ) ) ) ) ) } } .protect(), buildModalGroupCore: function() { var membersListClass = ''; // Not allowed to rename if (this.options.blockRename) { this.modalElements.inputField = ''; membersListClass = 'ig-norename'; } // Not allowed to change membership if (this.options.blockModify) { peopleToAdd = ''; membersListClass = 'ig-noadd'; } // Not allowed to make any changes if (this.options.blockRename && this.options.blockModify) { this.modalElements.buttons = ''; membersListClass = 'ig-alone'; } // this is the main modal skeleton var self = this; this.groupCore = new Element('div', { 'class': 'ig-modal-pad ig-compose' }).adopt( new Element('form', { 'class': 'modalform ig-form' }).adopt( this.modalElements.groupNameElem, this.modalElements.inputField, new Element('div', { // Group Name 'class': 'ig-modalmembers ' + membersListClass }).adopt( this.modalElements.peopleToAdd, new Element('ul', { // People to remove 'class': 'ig-portrait ig-nomargin ig-users js-users' }) ), this.modalElements.buttons ).addEvent('onvalidformsubmit', function() { self.makeChanges(); }) ); } .protect(), doMemberSyncApi: function(apiMethod, postdata, successFunc) { var self = this; var memberSyncAPI = new ApiClient({ 'apimethod': apiMethod, 'method': 'post', 'postdata': postdata, onRequest: function() { self.element_overlay.inject(self.topMost, 'top'); }, onSuccess: function(text) { var returnjson = JSON.decode(text, true); if (returnjson.response != null && typeOf(self[successFunc]) == 'function') { self[successFunc](returnjson); } }, onFailure: function(xhr) { var returnstring = xhr.responseText; var returnjson = JSON.decode(returnstring, true); if (returnjson.exception != null) { // Single exception var err = returnjson.exception; var userError = ""; if (err.type.ciContains('data_objectalreadyexists')) { // group exists error var userError = window.translations('system-access-group_already_exits'); } else if (err.type.ciContains('authorization_permissionsmembersonly')) { // user doesn't exist error var userError = window.translations('system-access-group_user_not_member'); } else { // catch all error var userError = window.translations('media-js-error_saving_group'); } // Display error message if (userError != "") { Utils.modalAlert(userError); } } self.element_overlay.dispose(); } }); } .protect(), makeChanges: function() { this.groupName = this.groupCore.getElement('input[name=group_name]'); this.newGroupName = ""; if (this.groupName && (this.groupName.value != '')) { this.newGroupName = Utils.htmlencode(this.groupName.value); } else { this.newGroupName = this.name; } if (this.newGroupName.trim() == "") { injectpopup(this.groupName, window.translations("profile-settings-error_required_field")); return; } // Curtain and spinner over whole modal this.topMost = this.groupCore.getParent('div'); var overlay_height = this.topMost.getHeight(); this.element_overlay = new Element('div', { 'class': 'ig-curtain' }); new Element('div', { 'class': 'ig-curtain-overlay', 'style': 'height: ' + overlay_height + 'px;' }).inject(this.element_overlay); new Element('div', { 'class': 'ig-loader-large', 'style': 'height: ' + overlay_height + 'px;' }).inject(this.element_overlay); if (this.options.action == 'update') { var apiMethod = 'usergroups/' + this.options.id + '/members/sync'; var postdata = { 'ids': this.usersInGroup.join(','), 'originalids': this.originalUsers.join(','), 'rename': this.newGroupName }; this.doMemberSyncApi(apiMethod, postdata, 'updateSyncSuccess'); } else if (this.options.action == 'create') { var selected = this.groupCore.getElement('.js-selectedOption'); this.parentElement = $(this.options.injectNewMemberGroupHere); if (selected) { if (selected.get('value') == 'false') { this.options.spaceId = null; } else { this.parentElement = $(this.options.injectNewSpaceGroupHere); } } else { this.options.spaceId = null; } var apiMethod = 'usergroups/addwithusers'; var postdata = { 'ids': this.usersInGroup.join(','), 'groupname': this.newGroupName, 'spaceId': this.options.spaceId }; this.doMemberSyncApi(apiMethod, postdata, 'createSyncSuccess'); } }, createSyncSuccess: function(returnjson) { var self = this; if (this.parentElement) { var allowRenameClass = this.options.blockRename ? '' : ' js-allowRename'; var allowModifyClass = this.options.blockModify ? '' : ' js-allowModify'; var allowSelfClass = this.options.blockSelf ? '' : ' js-allowSelf'; if (this.options.tablelayout) { var entityLink = new Element('a', { 'id': 'js-' + returnjson.response.id + '-name', 'class': 'icon icon-group icon-paddingfix js-' + returnjson.response.id + '-name', 'href': '#', 'title': this.newGroupName, 'html': this.newGroupName }); var entityOptionsLink = new Element('a', { 'id': 'js-actionstrigger_' + returnjson.response.id, 'class': 'actionslink', 'href': '#', 'title': window.translations('admin-members-Actions'), 'html': window.translations('admin-members-Actions') }); var newUserGroup = new Element('tr', { 'id': 'childId_' + returnjson.response.id }).adopt( new Element('td', { 'class': 'name ig-indent' }).adopt(entityLink, entityOptionsLink), new Element('td', { 'id': 'js-' + returnjson.response.id + '-size', 'class': 'size js-' + returnjson.response.id + '-size', 'html': returnjson.response.numMembers }) ); var where = 'before'; var manageGroupTrigger = entityLink.id; } else { var entityLink = new Element('a', { 'href': '#', 'id': 'js-usergroups_' + returnjson.response.id, 'class': 'js-usergroup js-' + returnjson.response.id + '-name' + allowRenameClass + allowModifyClass + allowSelfClass, 'html': this.newGroupName }).addEvent('click', function(event) { var newDropdown = new igDropdown(this, 'createRule', { 'align': 'bottom-right', 'direction': 'n', 'offset_x': 17, 'offset_y': 13, 'menu': 'createRule', 'target': 'js-createrule' }); }); var countLink = new Element('a', { 'href': '#', 'id': 'js-usernumbers_' + returnjson.response.id, 'title': window.translations('system-access-Edit_group') }).adopt( new Element('span', { 'class': 'ig-num js-' + returnjson.response.id + '-size', 'html': returnjson.response.numMembers }) ); var newUserGroup = new Element('li', { 'id': 'js-usergroups_list_' + returnjson.response.id, 'class': 'js-group ig-highlight' }).adopt(entityLink, countLink); var where = 'top'; var manageGroupTrigger = countLink.id; } newUserGroup.inject(this.parentElement, where); // Attach ManageGroup asset to the new group new manageGroup(manageGroupTrigger, { 'id': returnjson.response.id, 'name': self.newGroupName, 'action': 'update', 'userId': self.options.userId, 'blockSelf': self.options.blockSelf, 'igDropdown': self.options.igDropdown }); if (this.options.tablelayout) { // deal with the menu. var floatMenuBody = new Element('div', { 'class': 'ig-floatmenu ig-floatmenu_gray ig-floatmenu_actions' }); if (this.options.spaceId == null) { floatMenuBody.adopt( new Element('a', { 'class': 'icon ig-default action-subscriptions', 'title': window.translations('media-js-Subscriptions'), 'href': '/admin/membership/groupsubscription?action=view&d=' + returnjson.response.id, 'html': window.translations('media-js-Subscriptions') }) ); } if (!this.options.blockdelete) { var deleteLink = new Element('a', { 'class': 'icon ig-border_top action-delete js-clickClose', 'title': window.translations('comps-actions-Delete'), 'href': '/admin/membership/groups?action=delete&d=' + returnjson.response.id, 'html': window.translations('comps-actions-Delete') }).addEvent('click', function(e) { e.stop(); $('childId_' + returnjson.response.id).ajaxDelete(returnjson.response.id, window.translations('comps-actions-Delete_Group_prompt')); }); floatMenuBody.adopt(deleteLink); } var actionMenu = new Element('div', { 'id': 'js-actionsMenu_' + returnjson.response.id, 'class': 'ig-actionsmenu hide' }).adopt( new Element('div', { 'class': 'ig-floatmenu-tip' }), floatMenuBody ); actionMenu.inject(document.body, 'bottom'); var selectRoleDropdown = new igDropdown(entityOptionsLink, 'js-actionsMenu_' + returnjson.response.id, { 'align': 'left', 'closeDelay': '0' }); } // Interact with Access (if applicable) now that we're done manipulating the DOM if (Igloo.asset_app_access && Igloo.asset_app_access['access']) { var accessAsset = $('access'); var qualifier = ''; if (this.options.spaceId) { qualifier = this.options.spaceTitle; } accessAsset.fireEvent('addPermissionEvents', [this.parentElement.id, 'group', qualifier]); // Let's reopen the Create A Rule dropdown if (Igloo.asset_igDropdown['js-createrule']) { var createRuleDropdown = $('js-createrule'); createRuleDropdown.fireEvent('showDropdown'); } // Let's help the user and assume that they created the group to give it a Rule: // Open the Select Role dropdown var selectRoleDropdown = new igDropdown(entityLink, 'createRule', { 'align': 'bottom-right', 'direction': 'n', 'offset_x': 17, 'offset_y': 13, 'target': 'js-createrule' }); selectRoleDropdown.show(); // Set the events manually accessAsset.fireEvent('setPermissionEvents', [returnjson.response.id, this.newGroupName, 'group', qualifier]); } } //Clear all the values for next use this.usersInGroup.empty(); this.originalUsers.empty(); this.element_overlay.dispose(); this.close(); }, updateSyncSuccess: function(returnjson) { // Number of users var numUsers = returnjson.response.numMembers; //NOTE: This is a hack to reduce the number of members across groups since the API response does not return sufficient data //Check if the # of users is 0 and the user is modifying the members group var sizeElements = $$('.size'); if (sizeElements && typeOf(sizeElements) == 'array' && sizeElements.length > 0) { if (numUsers === 0 && returnjson.response.type === 10) { sizeElements.each(function(item) { item.set('html', '0'); }); //otherwise if the number of users in a group is more than the number of users in the members group then reset the total of that group } else if (returnjson.response.type === 10) { //Always set the # of members to what's returned from the API sizeElements[this.groupTypes.MEMBERS].set('html', numUsers); sizeElements.each(function(item) { if (Number.from(item.get('html')) > numUsers) { item.set('html', numUsers); } }); } } // Elements with group name if (this.groupName) { this.name = (returnjson.response.name) ? Utils.htmldecode(returnjson.response.name) : this.newGroupName; var groupMentionsOnPage = $$('.js-' + this.options.id + '-name'); groupMentionsOnPage.each(function(item) { item.empty(); // Remove name item.adopt( new Element('span', { 'title': Utils.htmlencode(this.name), 'text': Utils.htmlencode(this.name.truncate(40, '...')) }) ); //if the name is too long truncate accordingly } .bind(this)); } // Elements with group size var groupSizeMentionsOnPage = $$('.js-' + this.options.id + '-size'); groupSizeMentionsOnPage.each(function(item) { item.set('html', numUsers) }); this.element_overlay.dispose(); this.usersInGroup.empty(); this.originalUsers.empty(); this.close(); }, getMemberList: function() { var self = this; var memberViewAPI = new ApiClient({ 'apimethod': 'usergroups/' + self.options.id + '/members/view', 'method': 'get', onRequest: function() { if (self.element_overlay && self.topMost) { self.element_overlay.inject(self.topMost, 'top'); } }, onSuccess: function(text, xml) { var returnstring = text; var returnjson = JSON.decode(returnstring, true); var usersArea = self.groupCore.getElement('.js-users'); usersArea.empty(); var usersArray = new Array(); returnjson.response.items.each(function(item) { usersArray.unshift({ 'email': item.email, 'firstName': item.name.firstName, 'hasPhoto': item.hasPhoto, 'htmlEmail': Utils.htmlencode(item.email), 'htmlFirstName': Utils.htmlencode(item.name.firstName), 'htmlLastName': Utils.htmlencode(item.name.lastnName), 'htmlNameSpace': '@' + Utils.htmlencode(item.namespace), 'lastName': item.name.lastName, 'name': item.name.fullName, 'namespace': item.namespace, 'originalHref': item.href, 'userTo': item.id }); }); self.buildInitialMemberListElement(usersArray, 0, 999); if (self.element_overlay) { self.element_overlay.dispose(); } // Set focus now that we are done loading (on Add People) var people_toAdd = self.modalElements.tempPeopleToAddInputElem; if (people_toAdd && !self.options.blockModify) { people_toAdd.focus(); } else { // This is here in case somebody allowed eding of the Name but not Members... weirdos var group_name = self.groupCore.getElement('input[name=group_name]'); if (group_name && !self.options.blockRename) { group_name.focus(); } } }, onFailure: function(xhr) { var returnstring = xhr.responseText; var returnjson = JSON.decode(returnstring, true); if (returnjson.exception != null) { // Single exception var err = returnjson.exception; // group exists error if (err.type == 'Data_ObjectAlreadyExists') { var userError = window.translations('system-access-group_already_exits'); var errormsg = new Modalbox({ 'title': window.translations('media-js-Error') }).setcontents('

' + userError + '

'); } else if (err.type == "Data_DoesNotExist") { var userError = window.translations('system-access-data_does_not_exist'); var errormsg = new Modalbox({ 'title': window.translations('media-js-Error') }).setcontents('

' + userError + '

'); } else { if (returnjson.exception.innerException) { // Exact error var errormsg = new Modalbox({ 'title': window.translations('media-js-Error') }).setcontents('

' + returnjson.exception.innerException.message + '

'); } } } self.close(); self.element_overlay.dispose(); } }); }, create: function() { var self = this; // Stop auto-hide on the related dropdown (if specified) if (Igloo.asset_igDropdown[self.options.igDropdown]) { var relatedDropdown = $(self.options.igDropdown); relatedDropdown.fireEvent('stopAutoHide'); } // Create the modal self.newModal(); if (self.options.action == 'update') { // Curtain and spinner over whole modal this.topMost = self.groupCore.getParent('div'); var overlay_height = this.topMost.getHeight(); this.element_overlay = new Element('div', { 'class': 'ig-curtain' }); new Element('div', { 'class': 'ig-curtain-overlay', 'style': 'height: ' + overlay_height + 'px;' }).inject(this.element_overlay); new Element('div', { 'class': 'ig-loader-large', 'style': 'height: ' + overlay_height + 'px;' }).inject(this.element_overlay); this.getMemberList(); } else { // Set focus on the Name field (since we're creating new group) var group_name = self.groupCore.getElement('input[name=group_name]'); if (group_name) { group_name.focus(); } } }, newModal: function() { var self = this; this.buildModalDialog(); var modalTitle = (self.name) ? Utils.htmlencode(self.name) + ' – ' + window.translations('system-access-Details') : window.translations('system-access-New_Group'); // will open a new modalbox adopting the groupCore as the body this.modal = new Modalbox({ 'width': '450', 'reusable': false, 'position': { 'absolute': {} }, 'title': (modalTitle), 'adopt': self.groupCore, 'onOpen': function() { bootstrap(this.mymodalfront); // Update value (in case changed by another asset) var group_name = self.groupCore.getElement('input[name=group_name]'); if (group_name) { group_name.value = self.name; } }, 'onClose': function() { self.autocompleter.closeList(); $$('.ig-form-validation-popup').dispose(); var inputGroupName = self.groupCore.getElement('.js-group_name') if (inputGroupName) inputGroupName.value = self.name; var inputAddUsers = this.modalElements.tempPeopleToAddInputElem; if (inputAddUsers) inputAddUsers.value = ''; var elemUsers = self.groupCore.getElement('.js-users'); if (elemUsers) elemUsers.set('html', ''); // Resume auto-hide on the related dropdown (if specified) if (Igloo.asset_igDropdown[self.options.igDropdown]) { var relatedDropdown = $(self.options.igDropdown); } } .bind(this) }); this.buildAutocompleter(); }, buildAutocompleter: function() { var self = this; // create an instance of the AutocompleteUserSearch class this.autocompleter = new AutocompleteSearchDisplayUser({ 'inputBox': self.modalElements.tempPeopleToAddInputElem.id, 'qType': Igloo.mSearchType.EMAIL + Igloo.mSearchType.NAME + Igloo.mSearchType.NAMESPACE, 'searchMethod': 'personaSmall', 'autohighlightfirst': true, 'onSelect': function(user) { var inputField = self.modalElements.tempPeopleToAddInputElem; if (inputField.value == "" || !user) { if ($(inputField.id + 'validationpopup')) { destroypopup(inputField); } return false; } //Display an error to the user if the selected user exists in the list already if (self.usersInGroup.contains(user.userTo)) { injectpopup(inputField, window.translations('system-access-User_already_exists')); } else if (self.options.userId == user.userTo) { if (self.options.blockSelf) { injectpopup(inputField, window.translations('system-access-Cannot_AddRemove_Self')); } else { self.addMember(user); } } else { self.addMember(user); } inputField.addEvent('focus', function(event) { destroypopup(this); }); } }); }, close: function() { var self = this; this.usersInGroup.empty(); this.originalUsers.empty(); if (self.modal) { self.modal.close(); } }, buildInitialMemberListElement: function(users, beginningNumber, endingNumber, append) { var userToArray = []; if (this.moreDisplay) { this.moreDisplay.destroy(); delete this.moreDisplay; } var listHolder = new Element('ul', { 'class': 'ig-portrait ig-nomargin ig-users js-users' }); if (beginningNumber == 0) { Array.each(users, function(user) { userToArray.push(user.userTo); }); } endingNumber = (endingNumber < users.length - 1) ? endingNumber : users.length - 1; for (var i = beginningNumber; i <= endingNumber; i++) { var user = users[i]; var person = this.buildPerson(user, true); person.inject(listHolder, 'bottom'); } this.beginning = endingNumber + 1; this.ending = endingNumber + 1000; if (endingNumber != users.length - 1) { this.buildLoadMoreButton(users); } else if (this.moreDisplay) { this.moreDisplay.destroy(); } var showShowMore = false; if (endingNumber != users.length - 1) { showShowMore = true; } this.pushListToDisplay(listHolder, showShowMore, append); if (beginningNumber == 0) { this.originalUsers.empty().append(userToArray); this.usersInGroup.append(userToArray); } this.setInputFocus(); }, pushListToDisplay: function(listHolder, showShowMore, append) { var usersArea = this.groupCore.getElement('.js-users'); if (append) { usersArea.adopt(listHolder.getElements('li')); if (showShowMore) { this.moreDisplay.inject(usersArea, 'bottom'); } } else { listHolder.replaces(usersArea); if (showShowMore) { this.moreDisplay.inject(listHolder, 'bottom'); } } }, buildLoadMoreButton: function(users) { var self = this; if (!this.moreDisplay) { this.moreDisplay = new Element('li', { 'html': '' + window.translations('comps-common-Load_More') + '', 'class': 'ig-cursorpointer' }).setStyles({ 'background-color': '#F5F5F5', 'border': '1px solid #CCCCCC', 'font-size': '1em', 'margin-left': '62px', 'margin-top': '10px', 'padding': '10px 25px', 'text-align': 'center' }).addEvent('click', function(e) { this.set('html', '' + window.translations('media-js-loading_ellp') + ''); window.setTimeout(function() { self.buildInitialMemberListElement(users, self.beginning, self.ending, true); }, 1000); }); } else { this.moreDisplay.set('html', '' + window.translations('comps-common-Load_More') + ''); } }, addMember: function(user) { var usersArea = this.groupCore.getElement('.js-users'); var person = this.buildPerson(user, false); person.inject(usersArea, 'top'); if (user && user.userTo) { this.usersInGroup.include(user.userTo); } this.setInputFocus(); }, setInputFocus: function() { var visibleInput = null; if (!this.options.blockModify) { visibleInput = this.modalElements.tempPeopleToAddInputElem; visibleInput.value = ''; } else if (!this.options.blockRename) { // under the current implementation we should never get here Object.each(this.modalElements, function(element) { visibleInput = element.getElement('js-group_name'); }); } if (visibleInput) { visibleInput.focus(); } }, buildPerson: function(user, initialLoad) { var self = this; var addedClass = "added"; if (initialLoad) { addedClass = ""; } var userImageSrc = (user.hasPhoto) ? '/download-profile/' + user.userTo + '/profile/crsmall' : '/cmedia/img/none.gif;v0'; if (this.options.blockModify) { var username = new Element('div', { // Insert the users' name 'class': 'ig-profile_info', 'html': ('

' + user.name + '

') }); } else { var username = new Element('div', { // Insert the users' name 'class': 'ig-profile_info', 'html': ('

' + user.name + '

') }); // it's always safe to remove other users but if blockSelf is true, then you cannot remove yourself if ((this.options.userId != user.userTo) || (this.options.userId == user.userTo && !this.options.blockSelf)) { username.adopt( new Element('a', { 'href': '#', 'id': user.userTo, 'class': 'remove-link small ig-nomargin js-' + user.userTo + ' ' + addedClass, 'html': window.translations('comps-message-Remove') }).addEvent('click', function(event) { event.stop(); self.removeUser(this.id); }) ); } } var person = new Element('li', { 'class': 'ig-left', 'html': '' }).adopt(username); return person; }, // Function to add/remove the Undo class to the selected object removeUser: function(id) { var self = this; this.usersInGroup.erase(id); var linkElem = this.groupCore.getElement('.js-' + id); var removedUser = linkElem.previousSibling; if (linkElem.hasClass('undo')) { linkElem.removeClass('undo'); // Remove the styles for a removed user $(removedUser).removeClass('italic ig-light_font ig-strikethrough'); // Set the link to read 'Remove' linkElem.set('html', window.translations('system-access-Remove')); // add to list this.usersInGroup.include(id); } else { linkElem.addClass('undo'); // Add the styles for a removed user $(removedUser).addClass('italic ig-light_font ig-strikethrough'); // Set the link to read 'Undo' linkElem.set('html', window.translations('system-access-Undo')); // remove from list this.usersInGroup.erase(id); } } }); window.addEvent('domready', function() { if (Igloo.asset_manageGroup) { var elem; Object.each(Igloo.asset_manageGroup, function(object, id) { elem = $(id); if (elem && object) { var group = new manageGroup(elem.id, object); } }); } }); window.addEvent('bootstrap4finished', function() { var elements = window.dependents['manageGroup']; if (elements) { elements.each(function(elem) { var group = new manageGroup(elem.id, elem.dataobj['manageGroup']); }); } });window.addEvent('domready', function() { var eventInProgress = false; var handler = function(event) { var target = $(event.target); if (target.nodeName == 'OBJECT' || target.nodeName == 'EMBED') { return; } //we don't care to handle clicking on flash object if (target && !target.hasClass('js-menuActions')) { target = target.getParent('.js-menuActions'); } if (target) { if (target.menu && (event.rightClick && target.hasClass('js-rightClick'))) { target.menu.show(event.client); } else { if ((event.rightClick && target.hasClass('js-rightClick')) || (!event.rightClick && !target.hasClass('js-rightClick'))) { event.preventDefault(); var targetId = target.id; var targetIdSplit = targetId.split('_'); var childId = targetIdSplit[1] || null; if (!$('actions_' + childId) && !eventInProgress) { // no menu exists for this element var menuRequest = new ApiClient({ 'headers': { 'Accept': 'application/xml' }, 'apimethod': 'igloo/widgets/39/render', 'queryparams': { 'paramList': 'objectId', 'paramTypes': 'id' }, 'postdata': { 'objectId': childId }, onRequest: function() { eventInProgress = true; window.igLoadingCursor.addLoader(); }, onComplete: function() { eventInProgress = false; window.igLoadingCursor.removeLoader(); }, onSuccess: function(text, xml) { var APIresponse = Utils.IARParse(xml); var menuHtml = new Element('div', { 'html': APIresponse.apihtml }); if (!menuHtml || !menuHtml.getElement('div')) { Utils.modalAlert(window.translations('media-js-error_general')); return false; } target.menu = menuHtml.getElement('div').inject(document.body); var menuId = target.menu.id; // we need to bootstrap the contents of the menu because it might need the 'confirm' asset or the 'reservesteal' asset bootstrap(target.menu); var triggerEvent = 'click'; if (event.rightClick && target.hasClass('js-rightClick')) { triggerEvent = 'rightClick'; } target.menu = new igDropdown(targetId, null, { 'menu': menuId, 'triggerEvent': triggerEvent }); if (event.rightClick && target.hasClass('js-rightClick')) { target.menu.show(event.client); } else { target.menu.show(); } menuHtml.destroy(); } }); } } } } }; document.addEvents({ // mouseup is for IE & Safari because they don't fire a 'click' event on right-click: 'mouseup': handler, // these are for FF because it handles the contextmenu through the click and dblclick events: 'click': handler, 'dblclick': handler }); // for IE and Sarafi we need to handle the contextmenu event // this is what displays the system menu and we want to stop this when we're listening for right-click document.addEvent('contextmenu', function(event) { var target = $(event.target); if (target.nodeName == 'OBJECT') { return; } //we don't care to handle clicking on flash object if (target && !target.hasClass('js-menuActions')) { target = target.getParent('.js-menuActions'); } if (target && target.hasClass('js-rightClick')) { event.preventDefault(); } }); }); var Minimodal = new Class({ Implements: [Options], options:{ 'injectat':'bottom', 'injectpoint':$(document.body), 'trigger':null, 'x-offset':-12, 'y-offset':-35, 'customclass':'', 'width':null }, initialize:function(options){ this.setOptions(options); this.options.trigger = $(this.options.trigger); this.minimodalform = new Element('div',{'id':'minimodalform', 'class':'comp-inlinemodalborder'}).inject(this.options.injectpoint, this.options.injectat); if(this.options.customclass){ this.minimodalform.addClass(this.options.customclass); } this.minimodalcontent = new Element('div',{'class':'comp-inlinemodalcontent'}).inject(this.minimodalform); this.minimodalwrap = new Element('div',{'class':'comp-inlinemodalwrap ig-clearfix'}).inject(this.minimodalcontent); this.minimodalformform = new Element('form',{'class':'ig-form ig-clearfix'}).inject(this.minimodalwrap,'top'); this.minimodalnobr = new Element('nobr').inject(this.minimodalformform); this.contentformnobr = this.minimodalnobr; this.contentform = this.minimodalform; if(this.options.width){ this.minimodalcontent.setStyles({ 'width' : this.options.width }); } var self = this; //the key handler for closing this dropdown using 'esc' document.addEvent('keyup', function(event){ if (event.key == 'esc'){ var targetTag = ($(event.target).tagName) ? $(event.target).tagName.toLowerCase() : ""; if (targetTag != 'input' && targetTag != 'textarea'){ //if it's not an input... self.close(); } else { $(event.target).blur(); //lose focus from the input } } }); }, shadow:function(){ var coordinates = this.getCoordinatesSafe(this.options.trigger); // IE6 Wrap Fix (#9839) - reset the container Width to the Width of the content during the mid-render phase // Note the +3px fix. IE6 needs it or it will create a blank line under the button whenever its class changes this.minimodalcontent.setStyles({ 'width' : this.minimodalwrap.getCoordinates()['width'] + 3 }); // IE6 Wrap Fix (#9839) - only now set Top and Left on the modal form this.minimodalform.setStyles({ 'left' : coordinates.left + this.options['x-offset'], 'top' : coordinates.top + this.options['y-offset'] }); var minimodalformsize = this.minimodalform.getCoordinates(); if((window.getSize().x - coordinates.left) < (minimodalformsize.width + 16)){ this.minimodalform.setStyles({ 'left' : '', 'right' : 18, 'top' : coordinates.top + this.options['y-offset'] }); } if((window.getSize().y + document.body.getScroll().y) < (minimodalformsize.height + minimodalformsize.top)){ this.minimodalform.setStyles({ 'top' : (window.getSize().y + document.body.getScroll().y) - (minimodalformsize.height + 16) }); } //Reset minimodalformsize after screen check var minimodalformsize = this.minimodalcontent.getCoordinates(); this.minimodalshadow = new Element('div',{'id':'comp-minimodalshadow'}).inject(this.minimodalform, 'before').set('html', ' '); this.minimodalshadow.setStyles({ 'width' : minimodalformsize.width + 8, 'height' : minimodalformsize.height + 8, 'left' : minimodalformsize.left - 4, 'top' : minimodalformsize.top - 4 }); }, resize:function(){ // IE6 Wrap Fix (#9839) - reset the Width stytle to itself + 3px... suprisingly that fixes the wrapping... as odd as it may sound this.minimodalcontent.setStyle('width', this.minimodalcontent.getCoordinates()['width'] + 2); var coordinates = this.getCoordinatesSafe(this.options.trigger); var minimodalformsize = this.minimodalform.getCoordinates(); if((window.getSize().x - coordinates.left) < (minimodalformsize.width + 16)){ this.minimodalform.setStyles({ 'left' : '', 'right' : 18, 'top' : coordinates.top + this.options['y-offset'] }); } //Reset minimodalform size after screen check var minimodalformsize = this.minimodalform.getCoordinates(); this.minimodalshadow.setStyles({ 'width' : minimodalformsize.width + 8, 'height' : minimodalformsize.height + 8, 'left' : minimodalformsize.left - 4, 'top' : minimodalformsize.top - 4 }); }, close:function(){ document.fireEvent('closeValidationPopups'); if ($(this.minimodalform)) { $(this.minimodalform).destroy(); } if ($(this.minimodalshadow)) { $(this.minimodalshadow).destroy(); } }, getCoordinatesSafe:function(target){ // what is up with this? why is getCoordinates failing? var coordinates = {}; if( !$(target) ){ //console.log(['target', target]); coordinates.top = 0; coordinates.left = 0; return coordinates; } try{ coordinates = target.getCoordinates(); //console.log([target, coordinates]); }catch(e){ //alert(e); try{ coordinates = target.getBoundingClientRect(); coordinates.top += document.documentElement.scrollTop; coordinates.bottom += document.documentElement.scrollTop; }catch(ex){ //console.log(target); } } return coordinates; } }); function applyRemovecookie(elements){ elements.each(function(elem){ if (elem.dataobj){ var dataobj = JSON.decode(elem.dataobj) || elem.dataobj; if( dataobj.removecookie ){ var cookiename = dataobj.removecookie; Cookie.dispose(cookiename, {path: '/'}); } } }); var igAlertContainer = $('ig-alert-container'); if( igAlertContainer ){ igAlertContainer.addEvent('click', function(){ igAlertContainer.disposeSlideFade(); }); } } window.addEvent('domready', function(){ if(Igloo && Igloo.asset_removecookie){ var elements = []; Object.each(Igloo.asset_removecookie, function(object, id){ var elem = $(id); if(elem){ if(!elem.dataobj || typeOf(elem.dataobj)!='hash'){ elem.dataobj = new Hash(elem.dataobj || object); } elem.dataobj.combine(object); elements.push(elem); } applyRemovecookie(elements); }); } }); window.addEvent('bootstrap4finished', function(){ var elements = window.dependents['removecookie'] || []; applyRemovecookie(elements); }); /* This handler makes the microblog in the userbar do stuff. */ var appMicroblogUserbarHandler = new Class({ Implements: [Options, Events], options:{ 'action':null, 'message':null, 'trigger':null }, initialize:function(options) { var self = this; // set the options this.setOptions(options || {}); if (this.options.action === null || this.options.message === null || this.options.trigger === null) { // all options are mandatory. return false; } // set the parameters this.trigger = $(this.options.trigger); this.userbarmicroblog = window.microblog_post; if (this.userbarmicroblog && this.trigger) { // disabled to kill the microblog namespace stuff. this.trigger.addEvent('click', function(e){ e.preventDefault(); switch(self.options.action){ case 'openMenu': self.userbarmicroblog.openPane(); break; case 'openMenuDefaultText': self.userbarmicroblog.mbSlidepane.removeEvents('paneOpen'); self.userbarmicroblog.mbSlidepane.addEvent('paneOpen', function(elem){ if ($(self.options.message)) { self.userbarmicroblog.insertText($(self.options.message).get('text')); } }); self.userbarmicroblog.openPane(); break; } }); } } });