"use strict"; !function(e){function n(){}function t(e,n){return function(){e.apply(n,arguments)}}function o(e){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof e)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],s(e,this)}function i(e,n){for(;3===e._state;)e=e._value;return 0===e._state?void e._deferreds.push(n):(e._handled=!0,void o._immediateFn(function(){var t=1===e._state?n.onFulfilled:n.onRejected;if(null===t)return void(1===e._state?r:u)(n.promise,e._value);var o;try{o=t(e._value)}catch(i){return void u(n.promise,i)}r(n.promise,o)}))}function r(e,n){try{if(n===e)throw new TypeError("A promise cannot be resolved with itself.");if(n&&("object"==typeof n||"function"==typeof n)){var i=n.then;if(n instanceof o)return e._state=3,e._value=n,void f(e);if("function"==typeof i)return void s(t(i,n),e)}e._state=1,e._value=n,f(e)}catch(r){u(e,r)}}function u(e,n){e._state=2,e._value=n,f(e)}function f(e){2===e._state&&0===e._deferreds.length&&o._immediateFn(function(){e._handled||o._unhandledRejectionFn(e._value)});for(var n=0,t=e._deferreds.length;n= 1) { attachment.media.width = pictureStandardSize; attachment.media.height = pictureStandardSize / imageRatio; } else { attachment.media.width = pictureStandardSize; attachment.media.height = pictureStandardSize / imageRatio; } attachment.element.insertBefore( attachment.media, attachment.info); }; attachment.media.src = path; attachment.media.className = "infostream-attachment-media"; }; var link = document.createElement("A"); link.target = "_blank"; switch (type) { case "link": loadPicture(attachment.pathValue); //was url before, but does not make sense... link.href = url; if(attachment.titleValue === "placeholder"){ link.textContent = "Media loading, please wait"; } else if(attachment.titleValue === "error"){ link.textContent = "Error with the given URL"; } else { link.textContent = attachment.titleValue } if (attachment.descriptionValue != undefined) { attachment.description.textContent = attachment.descriptionValue.substring(0, 400) + '...'; } break; case "file": if ( helper.isZipFile( attachment.pathValue ) || helper.isPDF( attachment.pathValue ) ) { link.textContent = name; link.href = attachment.pathValue; link.target = "_blank"; attachment.element.appendChild(attachment.info); attachment.description.textContent = "Vorsicht! Bitte nur Dateien von vertrauenswürdigen Tradern laden!"; } else { loadPicture(attachment.pathValue); link.href = attachment.pathValue; } break; case "link-youtube": var youtubeUrl = "https://www.youtube.com/watch?v=" + url; loadYoutube(url); link.href = youtubeUrl; link.textContent = attachment.titleValue; if (attachment.descriptionValue != undefined) { attachment.description.textContent = attachment.descriptionValue.substring(0, 400) + '...'; } break; default: //console.log("invalid attachment type: " + type); } attachment.title.appendChild(link); attachment.getTitle = function () { return attachment.titleValue; }; attachment.setTitle = function (newName) { attachment.titleValue = newName; link.textContent = newName; }; attachment.getType = function () { return type; }; attachment.setType = function (newType) { type = newType; }; attachment.getPath = function () { if ( attachment.pathValue != null ) { return attachment.pathValue.replace('/preview', '') } else { return attachment.pathValue; } }; attachment.getUrl = function () { return url; }; attachment.getDescription = function () { return attachment.descriptionValue; }; attachment.setDescription = function (newDescription) { attachment.descriptionValue = newDescription; if (newDescription != undefined) { attachment.description.textContent = newDescription.substring(0, 400) + '...'; } else{ attachment.description.textContent = ""; } }; return attachment; } function AttachmentManager(element) { var attachmentManager = {}; //var attachment; var attachments = []; attachmentManager.element = element; attachmentManager.element.className = "infostream-attachment-manager"; attachmentManager.attachmentContainer = document.createElement("DIV"); attachmentManager.attachmentContainer.className = "infostream-post-bodyAttachments"; attachmentManager.attachmentContainer.style.display = "none"; attachmentManager.element.appendChild(attachmentManager.attachmentContainer); var onRemoveAttachmentCallback; var onAttachmentActionCallback; var savedMediaPath; /*attachmentManager.removeAttachment = function ( ) { if (attachment) { attachmentManager.attachmentContainer.removeChild(attachment.element); attachment = undefined; attachmentManager.attachmentContainer.style.display = "none"; } }; */ attachmentManager.removeAttachment = function ( attachment ) { if (attachment) { attachmentManager.attachmentContainer.removeChild(attachment.element); var i, l = attachments.length; for ( i = 0; i < l; i++ ) { if ( attachment == attachments[i] ) { attachments.splice(i, 1); break; } } if ( attachments.length == 0 ) { attachmentManager.attachmentContainer.style.display = "none"; } } }; var addCloseButton = function ( attachment ) { var closeButton = document.createElement("BUTTON"); closeButton.textContent = "X"; closeButton.className = "infostream-attachment-remove"; closeButton.onclick = function () { attachmentManager.removeAttachment( attachment ); if (onRemoveAttachmentCallback) { onRemoveAttachmentCallback(); } if ( onAttachmentActionCallback ) { onAttachmentActionCallback(); } }; attachment.element.appendChild(closeButton); }; /* var addCloseButton = function () { var closeButton = document.createElement("BUTTON"); closeButton.textContent = "X"; closeButton.className = "infostream-attachment-remove"; closeButton.onclick = function () { attachmentManager.removeAttachment( ); if (onRemoveAttachmentCallback) { onRemoveAttachmentCallback(); } if ( onAttachmentActionCallback ) { onAttachmentActionCallback(); } }; attachment.element.appendChild(closeButton); }; */ attachmentManager.addFile = function (data, placeholder) { attachmentManager.removeAttachment( placeholder ); //attachmentManager.removeAttachment(); //depends of if it is new or editing a post, the path could be full domain or not var path = data.path.indexOf(projectDomain) !== -1 ? data.path : projectDomain + data.path; var attachment = new EditableAttachment(data.name, path, "file"); attachmentManager.attachmentContainer.appendChild(attachment.element); attachmentManager.attachmentContainer.style.display = "block"; addCloseButton(attachment); attachments.push( attachment ); if ( onAttachmentActionCallback ) { onAttachmentActionCallback(); } }; attachmentManager.addLink = function (data, placeholder) { var image = data.image; if (image && image.indexOf("/") === 0) { image = image.slice(1); } else if (data.path) { savedMediaPath = data.path; } placeholder.setTitle(data.title); placeholder.setPicture(savedMediaPath || data.protocol + data.host + "/" + image || "/public/images/default.png"); //"/public/images/default.png" placeholder.setDescription(data.description); addCloseButton( placeholder ); if ( onAttachmentActionCallback ) { onAttachmentActionCallback(); } }; attachmentManager.addYouTube = function (data, placeholder) { attachmentManager.removeAttachment( placeholder ); var attachment = new EditableAttachment(data.title, null, "link-youtube", data.ytId, data.description); attachmentManager.attachmentContainer.appendChild(attachment.element); attachmentManager.attachmentContainer.style.display = "block"; addCloseButton( attachment ); attachments.push( attachment ); if ( onAttachmentActionCallback ) { onAttachmentActionCallback(); } }; attachmentManager.addWaitingPlaceholder = function (url, placeholder) { attachmentManager.removeAttachment(placeholder); var attachment = new EditableAttachment("placeholder", "/public/images/default.png", "link", url); //"/public/images/default.png" attachmentManager.attachmentContainer.appendChild(attachment.element); attachmentManager.attachmentContainer.style.display = "block"; addCloseButton( attachment ); attachments.push( attachment ); return attachment; }; attachmentManager.addErrorImage = function (placeholder) { attachmentManager.removeAttachment(placeholder); var attachment = new EditableAttachment("error", "/public/images/error.png", "link"); attachmentManager.attachmentContainer.appendChild(attachment.element); attachmentManager.attachmentContainer.style.display = "block"; addCloseButton( attachment ); attachments.push( attachment ); }; attachmentManager.setScreenshot = function (newPath, waitin_atach) { if (waitin_atach.getTitle() !== "placeholder") { waitin_atach.setPicture(newPath); } else { savedMediaPath = newPath; } }; attachmentManager.setAttachmentToEdit = function (newAttachment) { var attachment = newAttachment; attachmentManager.attachmentContainer.appendChild(newAttachment.element); attachmentManager.attachmentContainer.style.display = "block"; addCloseButton( attachment ); attachments.push( attachment ); }; attachmentManager.createDragAndDropper = function (element) { element.ondragover = function (event) { element.style.border = "4px dashed #7eaad1"; event.preventDefault(); }; element.ondragleave = function (event) { element.style.border = ""; event.preventDefault(); }; element.ondrop = function (event) { event.stopPropagation(); event.preventDefault(); element.style.border = ""; //attachmentManager.removeAttachment(); this.uploadFile( event.dataTransfer.files ) }.bind( this ); element.onpaste = function( event ) { var items = event.clipboardData.items; var i, l = items.length; for ( i = 0; i < l; i++ ) { if ( items[i]['kind'] == 'file' && items[i]['type'] == 'image/png' ) { this.uploadFile( [items[i].getAsFile()] ) } } }.bind(this) }; attachmentManager.uploadFile = function( data ) { if ( data.length == 0 ) { return; } var uploader = new UploadCreator(); if ( data[0].type == "application/x-zip-compressed" && data[0].size/1024 > 200 ) { //check filesize in kB alertManager.inform("Max zip size: 200kB"); } else { uploader.createFileUpload(data[0], function (fileObject) { if ( fileObject.result ) { socketGateway.emit("uploadPostFile", fileObject, function (data) { if (data.response === "ok") { attachmentManager.addFile(data); } else { if ( data.message != undefined ) { alertManager.inform(data.message); } else { alertManager.inform("Dateityp ist nicht erlaubt / Max size: 3MB"); } } }); } else { alertManager.inform(fileObject.message) } }); } }; attachmentManager.createButtonUploader = function (element) { element.onchange = function (event) { this.uploadFile( event.target.files) }.bind(this); }; /*attachmentManager.emptyPreviewWindow = function () { if (attachment) { attachmentManager.attachmentContainer.removeChild(attachment.element); } attachment = undefined; attachment = undefined;ta attachmentManager.attachmentContainer.style.display = "none"; }; */ attachmentManager.emptyPreviewWindow = function () { var i, l = attachments.length; for ( i = 0; i < l; i++ ) { attachmentManager.attachmentContainer.removeChild(attachments[i].element); } attachments = []; attachmentManager.attachmentContainer.style.display = "none"; }; attachmentManager.getAttachments = function () { return attachments; }; attachmentManager.onRemoveAttachment = function (callback) { onRemoveAttachmentCallback = callback; }; attachmentManager.onAttachmentAction = function (callback) { onAttachmentActionCallback = callback; }; return attachmentManager; } function EditableAttachment(name, path, type, url, description) { var editableAttachment = new Attachment(name, path, type, url, description, true ); (editableAttachment.makeEditable = function () { editableAttachment.title.contentEditable = true; editableAttachment.title.onkeyup = function () { editableAttachment.setTitle(editableAttachment.title.textContent); } })(); return editableAttachment; } /* A screen containing the main infostream and the post editor */ function ChatScreen (id, username, startTimestamp) { var chatScreen = {}; chatScreen.element = document.createElement("DIV"); chatScreen.infoStream; var postEditor; chatScreen.infoStreamLoadedCallback; var newPostCallback; var input = document.createElement("DIV"); chatScreen.output; var loadButton; chatScreen.newPostsInfo; chatScreen.loadingContainer = document.createElement("DIV"); chatScreen.loading; chatScreen.numberOfPostsShown = numberOfPostsShown; chatScreen.firstLoad = true; chatScreen.moreToFetch = true; chatScreen.alreadyFetching = false; chatScreen.fetchInfoStream = function (callback) { chatScreen.alreadyFetching = true; chatScreen.loading = document.createElement("DIV"); chatScreen.loading.textContent = "Loading more..."; chatScreen.loadingContainer.appendChild(chatScreen.loading); chatScreen.loadingContainer.className = "loading-more"; socketGateway.emit("loadInfoStream", { "numberOfPostsShown": chatScreen.numberOfPostsShown, "firstLoad" : chatScreen.firstLoad }, function (data) { chatScreen.firstLoad = false; if ( data.result != undefined && !data.result ) { chatScreen.loading.textContent = data.message; } else { chatScreen.moreToFetch = data["moreToFetch"]; chatScreen.loadingContainer.removeChild(chatScreen.loading); chatScreen.alreadyFetching = false; callback(data["posts"]); } }); }; chatScreen.startLivePost = function ( data ) { //nothing live for normal, only for groups }; var addPost = function (args) { args["origin"] = "main"; socketGateway.emit("addPost", args , function (args) { startTimestamp = args.timestamp; newPostCallback(startTimestamp, id, username); chatScreen.infoStream.addPostAtBeginning( { "postid": args.id, "posterName": username, "posterid": id, "readerid": id, "timestamp": args.timestamp, "text": args.text, "attachments": args.attachments, "tags": args.tags, "stocks": args.stocks, "cloud": args.cloud, "news": args.news, "edited": false, "replies" : [], "picturePath": args.picturePath, "nice_title" : args.nice_title } ); }); }; var createPostEditor = function (input) { postEditor = new MainPostEditor(id, input, false, [], [], [], null, false); postEditor.init(); postEditor.onPost(addPost); }.bind( this ); var getScrollDimensions = function (homeViewer) { var dimensions = {}; dimensions["fullHeight"] = homeViewer.scrollHeight; dimensions["scrollTop"] = homeViewer.scrollTop; dimensions["clientHeight"] = homeViewer.clientHeight; dimensions["currentHeight"] = dimensions["scrollTop"] + dimensions["clientHeight"]; return dimensions; }; chatScreen.activateOnScroll = function (homeViewer) { homeViewer.onscroll = function ( force ) { var dimensions = getScrollDimensions(homeViewer); //console.log( dimensions["currentHeight"] , dimensions["fullHeight"], dimensions["currentHeight"] >= dimensions["fullHeight"] ) //round for UHD if(force === true || dimensions["currentHeight"] >= dimensions["fullHeight"]){ if(!chatScreen.alreadyFetching && chatScreen.moreToFetch){ chatScreen.numberOfPostsShown += 10; chatScreen.fetchInfoStream(function (data) { chatScreen.infoStream.addOlderToInfoStream(data); if(chatScreen.infoStreamLoadedCallback){ chatScreen.infoStreamLoadedCallback(); } }); } } }; }; chatScreen.deactivateOnScroll = function (homeViewer) { homeViewer.onscroll = null; }; ////////////////////////////////////////////////////////////////////////////////////////////////////// // PUBLIC ////////////////////////////////////////////////////////////////////////////////////////////////////// chatScreen.loadInfoStream = function () { if(!chatScreen.alreadyFetching){ chatScreen.numberOfPostsShown = numberOfPostsShown; chatScreen.output.appendChild(chatScreen.infoStream.element_always_top); chatScreen.output.appendChild(chatScreen.infoStream.element); chatScreen.output.appendChild(chatScreen.loadingContainer); chatScreen.fetchInfoStream(function (data) { chatScreen.infoStream.buildInfoStream(data); if(chatScreen.infoStreamLoadedCallback){ chatScreen.infoStreamLoadedCallback(); } }); } }; chatScreen.onInfoStream = function (callback) { chatScreen.infoStreamLoadedCallback = callback; }; chatScreen.onNewPost = function (callback) { newPostCallback = callback; }; chatScreen.removeListeners = function () { socketGateway.unsubscribe("addContactPost", chatScreen); socketGateway.unsubscribe("sendWebsiteData", postEditor); }; var removeLoadButton = function () { chatScreen.newPostsInfo.removeChild(loadButton); loadButton = null; }; chatScreen.createLoadButton = function (callback) { return; if(loadButton){ removeLoadButton(); } loadButton = document.createElement("BUTTON"); loadButton.className = "load-new-button"; loadButton.innerHTML = "Load new posts"; loadButton.onclick = function () { callback(); chatScreen.loadInfoStream(); removeLoadButton(); }; chatScreen.newPostsInfo.appendChild(loadButton); }; chatScreen.createUI = function () { input.type = "file"; input.className = "infostream-input"; chatScreen.output = document.createElement("DIV"); chatScreen.output.className = "infostream-output"; chatScreen.newPostsInfo = document.createElement("DIV"); chatScreen.newPostsInfo.className = "infostream-newPosts"; chatScreen.output.appendChild(chatScreen.newPostsInfo); chatScreen.element.appendChild(input); chatScreen.element.appendChild(chatScreen.output); chatScreen.infoStream = new InfoStream(username, id); chatScreen.loadInfoStream(); createPostEditor(input); this.postSharedElement = function(element){ postEditor.stocksManager.processData(element); }; currentView.setNewView( { type : 'chat', id : 'main', onChangeView : null, calls : { postSharedElement : [ this, this.postSharedElement ] } } ) }.bind(this); return chatScreen; } /* A screen containing the infostream of a group and its post editor */ function GroupChatScreen(groupid, id, username, startTimestamp, writers, group_title_element, group_name, group_settings ) { var groupChatScreen = new ChatScreen(id, username, startTimestamp); groupChatScreen.element = document.createElement("DIV"); groupChatScreen.postEditor = undefined; groupChatScreen.live_elements = {}; this.postSharedElement = function(element){ groupChatScreen.postEditor.stocksManager.processData(element); }; currentView.setNewView( { type : 'groups', id : groupid, onChangeView : function(){ currentHome.unsubscribe( 'livePosting' , groupChatScreen.onLivePost, groupChatScreen ); currentHome.unsubscribe( 'newMemberPost' , groupChatScreen.onNewMemberPost, groupChatScreen ); if ( groupChatScreen.postEditor!= undefined && groupChatScreen.postEditor.isLivePosting() ){ groupChatScreen.postEditor.sendLivePostingData('end'); } }, calls : { postSharedElement : [ this, this.postSharedElement ] } } ) var newPostCallback; var new_posts_counter = 0; var input = document.createElement("DIV"); groupChatScreen.output; groupChatScreen.newPostsInfo; groupChatScreen.fetchInfoStream = function (callback) { groupChatScreen.alreadyFetching = true; groupChatScreen.loading = document.createElement("DIV"); groupChatScreen.loading.textContent = "Loading more..."; groupChatScreen.loadingContainer.appendChild(groupChatScreen.loading); groupChatScreen.loadingContainer.className = "loading-more"; socketGateway.emit("loadGroupInfoStream", { "numberOfPostsShown": groupChatScreen.numberOfPostsShown, "groupid": groupid, "sort" : group_settings["sort"] }, function (data) { groupChatScreen.moreToFetch = data["moreToFetch"]; groupChatScreen.loadingContainer.removeChild(groupChatScreen.loading); groupChatScreen.alreadyFetching = false; callback(data["posts"]); }); }; groupChatScreen.onNewMemberPost = function( data ) { if ( data.groupid == groupid ) { new_posts_counter++; var name_span = document.createElement("SPAN") name_span.textContent = group_name; var count_span = document.createElement("BUTTON"); count_span.style.clear = "both"; count_span.style.background = "#63a263"; count_span.style.color = "white"; count_span.style.marginLeft = "0px"; count_span.textContent = new_posts_counter + " neue Nachricht" + ( new_posts_counter > 1 ? "en" : "" ) + " (hier aktualisieren)"; count_span.onclick = function( event ) { currentHome.group( groupid ); event.stopPropagation(); event.preventDefault(); } group_title_element.innerHTML = ""; group_title_element.appendChild( name_span ); group_title_element.appendChild( count_span ); if ( newPostCallback ) { newPostCallback(); } //todo check autorefresh settings and reload with API currentHome.group(groupid) } }; groupChatScreen.onLivePost = function ( data ) { if ( data.group == groupid ) { //I can see what others are seeing. This live post is interesting for the group if ( data.type == 'start' ) { createLivePostingReader( data ); groupChatScreen.live_elements[data.poster].setPostHeadTitle( data.title ); groupChatScreen.live_elements[data.poster].setPostContent( data.text ); if ( data.attachment_data != undefined ) { groupChatScreen.live_elements[data.poster].setPostAttachmentData( data.attachment_data ); } } else if ( data.type == 'end' ) { var live_post = groupChatScreen.live_elements[data.poster]; if ( live_post != undefined ) { live_post.element.parentNode.removeChild(live_post.element); delete groupChatScreen.live_elements[data.poster]; } if ( data.poster == currentUser.id ) { //could be closed from server. Change button. if ( groupChatScreen.postEditor!= undefined && groupChatScreen.postEditor.isLivePosting() ){ groupChatScreen.postEditor.pauseLivePostingActivity(); } } setTimeout( function(){ groupChatScreen.loadInfoStream(); }, 1000 ) } else if ( data.type == 'title' ) { if ( groupChatScreen.live_elements[data.poster] == undefined ) { createLivePostingReader( data ); } groupChatScreen.live_elements[data.poster].setPostHeadTitle( data.title ); } else if ( data.type == 'text' ) { if ( groupChatScreen.live_elements[data.poster] == undefined ) { createLivePostingReader( data ); } groupChatScreen.live_elements[data.poster].setPostContent( data.text ); //Editors do not scroll. More than 1 Live do not scroll. if ( groupChatScreen.live_elements[currentUser.id] == undefined && Object.keys(groupChatScreen.live_elements).length == 1 ) { var live_post = groupChatScreen.live_elements[data.poster]; live_post.footer.scrollIntoView(false) } } else if ( data.type == 'live-post-data' ) { if ( groupChatScreen.live_elements[data.poster] == undefined ) { createLivePostingReader( data ); } groupChatScreen.live_elements[data.poster].setPostAttachmentData( data.attachment_data ); if ( groupChatScreen.live_elements[currentUser.id] == undefined && Object.keys(groupChatScreen.live_elements).length == 1 ) { var live_post = groupChatScreen.live_elements[data.poster]; live_post.footerReplies.scrollIntoView(false) } } } }; var createLivePostingReader = function( data ) { var live_post = groupChatScreen.live_elements[data.poster]; if ( live_post != undefined ) { live_post.element.parentNode.removeChild(live_post.element); delete groupChatScreen.live_elements[data.poster]; } groupChatScreen.live_elements[data.poster] = groupChatScreen.infoStream.addPostAtBeginning( { "type" : 'live', "postid": -1, "posterName": data.poster_name, "posterid": data.poster, "readerid": id, "timestamp": '', "text": '', "attachments": [], "tags": [], "stocks": [], "news": [], "cloud": [], "replies": [], "edited": false, "picturePath": data.poster_picture, "groupid": data.group }, true ); }; var addPost = function (args) { args["groupid"] = groupid; args["origin"] = "group"; socketGateway.emit("addGroupPost", args, function (args) { startTimestamp = args.timestamp; newPostCallback(startTimestamp, id, username); groupChatScreen.infoStream.addPostAtBeginning({ "postid": args.id, "posterName": username, "posterid": id, "readerid": id, "timestamp": args.timestamp, "text": args.text, "title": args.title, "attachments": args.attachments, "tags": args.tags, "stocks": args.stocks, "news": args.news, "cloud": args.cloud, "replies": [], "edited": false, "picturePath": args.picturePath, "groupid": args.groupid, "nice_title" : args.nice_title }); }); }; var createPostEditor = function (input) { groupChatScreen.postEditor = new MainPostEditor(id, input, false, [], [], [], groupid, true); groupChatScreen.postEditor.init(); groupChatScreen.postEditor.onPost(addPost); }; ////////////////////////////////////////////////////////////////////////////////////////////////////// // PUBLIC ////////////////////////////////////////////////////////////////////////////////////////////////////// groupChatScreen.onNewPost = function (callback) { newPostCallback = callback; }; groupChatScreen.removeListeners = function () { socketGateway.unsubscribe("addGroupMemberPost", groupChatScreen); socketGateway.unsubscribe("sendWebsiteData", groupChatScreen.postEditor); }; groupChatScreen.createUI = function () { input.type = "file"; input.className = "infostream-input"; groupChatScreen.output = document.createElement("DIV"); groupChatScreen.output.className = "infostream-output"; groupChatScreen.newPostsInfo = document.createElement("DIV"); groupChatScreen.newPostsInfo.className = "infostream-newPosts"; groupChatScreen.output.appendChild(groupChatScreen.newPostsInfo); groupChatScreen.element.appendChild(input); groupChatScreen.element.appendChild(groupChatScreen.output); groupChatScreen.infoStream = new InfoStreamGroup(username, id, groupid); groupChatScreen.loadInfoStream(); if ( writers.length == 0 || writers.indexOf(currentUser.id) != -1 ) { createPostEditor(input); } else { input.innerHTML = '
- Kein Schreiberecht -
'; //infostream-input } currentHome.subscribe( 'livePosting' , groupChatScreen.onLivePost, groupChatScreen ); currentHome.subscribe( 'newMemberPost' , groupChatScreen.onNewMemberPost, groupChatScreen ); socketGateway.emit("getGroupLivePosting", groupid , function (data) { if ( data ) { var key; for ( key in data ){ groupChatScreen.onLivePost(data[key]); } } } ) }; return groupChatScreen; } /* A screen containing the main infostream and the post editor */ function StreamScreen (id, username) { var streamScreen = {}; streamScreen.element = document.createElement("DIV"); streamScreen.infoStream; var postEditor; streamScreen.infoStreamLoadedCallback; var newPostCallback; var selected_stocks = [ "DE0005140008","DE0005190003","DE0005200000","DE0005439004","DE0005552004","DE0005557508","DE0005785604", "DE0005785802","DE0005810055","DE0006047004","DE0006048432","DE0006062144","DE0006231004","DE0006599905", "DE0007037129","DE0007100000","DE0007164600","DE0007236101","DE0007472060","DE0007500001","DE0007664039", "DE0008232125","DE0008404005","DE0008430026","DE000A1EWWW0","DE000A1ML7J1","DE000BASF111","DE000BAY0017", "DE000ENAG999","IE00BZ12WP82"]; var input = document.createElement("DIV"); streamScreen.output; streamScreen.newPostsInfo; streamScreen.loadingContainer = document.createElement("DIV"); streamScreen.loading; streamScreen.numberOfPostsShown = 10; streamScreen.firstLoad = true; streamScreen.moreToFetch = true; streamScreen.alreadyFetching = false; streamScreen.getUserAvailableLists = function( callback ) { getUserTDLists } streamScreen.fetchInfoStream = function (callback) { streamScreen.alreadyFetching = true; streamScreen.loading = document.createElement("DIV"); streamScreen.loading.textContent = "Loading more..."; streamScreen.loadingContainer.appendChild(streamScreen.loading); streamScreen.loadingContainer.className = "loading-more"; socketGateway.emit("loadStream", { "numberOfPostsShown": streamScreen.numberOfPostsShown, "stocks" : selected_stocks, // "firstLoad" : streamScreen.firstLoad }, function (data) { streamScreen.firstLoad = false; if ( data.result != undefined && !data.result ) { streamScreen.loading.textContent = data.message; } else { streamScreen.moreToFetch = data["moreToFetch"]; streamScreen.loadingContainer.removeChild(streamScreen.loading); streamScreen.alreadyFetching = false; callback(data["posts"]); } }); }; var getScrollDimensions = function (homeViewer) { var dimensions = {}; dimensions["fullHeight"] = homeViewer.scrollHeight; dimensions["scrollTop"] = homeViewer.scrollTop; dimensions["clientHeight"] = homeViewer.clientHeight; dimensions["currentHeight"] = dimensions["scrollTop"] + dimensions["clientHeight"]; return dimensions; }; streamScreen.activateOnScroll = function (homeViewer) { homeViewer.onscroll = function ( force ) { var dimensions = getScrollDimensions(homeViewer); if( force === true || dimensions["currentHeight"] >= dimensions["fullHeight"]){ if(!streamScreen.alreadyFetching && streamScreen.moreToFetch){ streamScreen.numberOfPostsShown += 10; streamScreen.fetchInfoStream(function (data) { streamScreen.infoStream.addOlderToInfoStream(data); if(streamScreen.infoStreamLoadedCallback){ streamScreen.infoStreamLoadedCallback(); } }); } } }; }; streamScreen.deactivateOnScroll = function (homeViewer) { homeViewer.onscroll = null; }; ////////////////////////////////////////////////////////////////////////////////////////////////////// // PUBLIC ////////////////////////////////////////////////////////////////////////////////////////////////////// streamScreen.loadInfoStream = function () { if(!streamScreen.alreadyFetching){ streamScreen.numberOfPostsShown = numberOfPostsShown; streamScreen.output.appendChild(streamScreen.infoStream.element_always_top); streamScreen.output.appendChild(streamScreen.infoStream.element); streamScreen.output.appendChild(streamScreen.loadingContainer); streamScreen.fetchInfoStream(function (data) { streamScreen.infoStream.buildInfoStream(data); if(streamScreen.infoStreamLoadedCallback){ streamScreen.infoStreamLoadedCallback(); } }); } }; streamScreen.onInfoStream = function (callback) { streamScreen.infoStreamLoadedCallback = callback; }; streamScreen.onNewPost = function (callback) { newPostCallback = callback; }; streamScreen.removeListeners = function () { socketGateway.unsubscribe("addContactPost", streamScreen); socketGateway.unsubscribe("sendWebsiteData", postEditor); }; streamScreen.createUI = function () { input.type = "file"; input.className = "infostream-input"; var description = document.createElement('DIV') description.className = "group-element" var marketplace_title = document.createElement('div'); marketplace_title.className = "home-subheader bigger" marketplace_title.textContent = "In deinem Stream findest du die Inhalte von Personen oder Bots, denen du folgst." var marketplace_link = document.createElement('div'); marketplace_link.textContent = "> Marketplace erkunden"; marketplace_link.className = "home-subheader bigger"; marketplace_link.style.cursor = "pointer"; marketplace_link.style.textDecoration = "underline"; marketplace_link.style.paddingTop = "0px"; marketplace_link.style.paddingBottom = "5px"; marketplace_link.onclick = function(event) { currentHome.api.openMarketPlace({}, function(){}); } description.appendChild(marketplace_title); description.appendChild(marketplace_link); streamScreen.element.appendChild(description); streamScreen.output = document.createElement("DIV"); streamScreen.output.className = "infostream-output"; streamScreen.output.style.marginTop = "10px"; streamScreen.newPostsInfo = document.createElement("DIV"); streamScreen.newPostsInfo.className = "infostream-newPosts"; streamScreen.output.appendChild(streamScreen.newPostsInfo); //streamScreen.element.appendChild(input); streamScreen.element.appendChild(streamScreen.output); streamScreen.infoStream = new InfoStream(username, id); streamScreen.loadInfoStream(); }; return streamScreen; } /* A screen containing the main infostream and the post editor */ function OverviewScreen (id, username) { var overviewScreen = {}; overviewScreen.element = document.createElement("DIV"); overviewScreen.infoStream; var titlesOptions = { 0 : "Heute", 3 : "3 Tage", 7: "7 Tage", 28: "4 Wochen" } var selectedOption = 3; var selectedIsin = null; var stocks_selector; overviewScreen.infoStreamLoadedCallback; var newPostCallback; overviewScreen.output; var loadButton; overviewScreen.newPostsInfo; overviewScreen.loadingContainer = document.createElement("DIV"); overviewScreen.loading; overviewScreen.numberOfPostsShown = numberOfPostsShown; overviewScreen.firstLoad = true; overviewScreen.moreToFetch = true; overviewScreen.alreadyFetching = false; overviewScreen.fetchInfoStream = function (callback) { overviewScreen.alreadyFetching = true; overviewScreen.loadingContainer.textContent = ""; overviewScreen.loading = document.createElement("DIV"); overviewScreen.loading.textContent = "Loading more..."; overviewScreen.loadingContainer.appendChild(overviewScreen.loading); overviewScreen.loadingContainer.className = "loading-more"; socketGateway.emit( "loadPostsWithStocks", { "numberOfPostsShown": overviewScreen.numberOfPostsShown, "firstLoad" : overviewScreen.firstLoad, "isin" : selectedIsin, "timeframe" : selectedOption }, function (data) { overviewScreen.firstLoad = false; if ( data.result != undefined && !data.result ) { overviewScreen.loading.textContent = data.message; } else { overviewScreen.moreToFetch = data["moreToFetch"]; overviewScreen.loadingContainer.removeChild(overviewScreen.loading); overviewScreen.alreadyFetching = false; callback(data["posts"]); } }); }; var getScrollDimensions = function (homeViewer) { var dimensions = {}; dimensions["fullHeight"] = homeViewer.scrollHeight; dimensions["scrollTop"] = homeViewer.scrollTop; dimensions["clientHeight"] = homeViewer.clientHeight; dimensions["currentHeight"] = dimensions["scrollTop"] + dimensions["clientHeight"]; return dimensions; }; overviewScreen.activateOnScroll = function (homeViewer) { homeViewer.onscroll = function ( force ) { var dimensions = getScrollDimensions(homeViewer); if(force === true || dimensions["currentHeight"] >= dimensions["fullHeight"]){ if(!overviewScreen.alreadyFetching && overviewScreen.moreToFetch){ overviewScreen.numberOfPostsShown += 10; overviewScreen.fetchInfoStream(function (data) { overviewScreen.infoStream.addOlderToInfoStream(data); if(overviewScreen.infoStreamLoadedCallback){ overviewScreen.infoStreamLoadedCallback(); } }); } } }; }; overviewScreen.deactivateOnScroll = function (homeViewer) { homeViewer.onscroll = null; }; ////////////////////////////////////////////////////////////////////////////////////////////////////// // PUBLIC ////////////////////////////////////////////////////////////////////////////////////////////////////// overviewScreen.createOverviewSection = function () { //todo emit to get overview menus var container = document.createElement("DIV") container.className = "group-element"; container.style.border = "0"; overviewScreen.element.appendChild( container ); var title = document.createElement("DIV"); title.textContent = "Über diese Aktien wird diskutieren"; title.className = "home-subheader"; title.style.fontSize = "16px"; title.style.height = "35px"; title.style.padding = "5px 9px"; title.style.marginTop = "0px"; title.style.color = "inherit"; container.appendChild(title); var tabs_selector = document.createElement("DIV"); tabs_selector.className = "home-subheader"; tabs_selector.style.marginTop = "-10px"; container.appendChild( tabs_selector ); if(environment === "tradingdesk"){ tabs_selector.style.marginTop = "-25px"; } stocks_selector = document.createElement("DIV"); stocks_selector.className = "home-subheader"; stocks_selector.style.height = "auto"; stocks_selector.style.maxHeight = "300px"; stocks_selector.style.overflowY = "auto"; stocks_selector.style.marginTop = "-10px"; stocks_selector.style.padding = "5px 9px"; stocks_selector.style.color = "inherit"; container.appendChild( stocks_selector ); socketGateway.emit("getOverview", {}, function (response) { this.createStocksSelector(response[selectedOption]); var key, tab; for ( key in response ) { tab = document.createElement("button"); tab.style.fontSize = "13px"; tab.textContent = titlesOptions[key]; tab.className = "submenu-bar-button timeframe" + ( key == selectedOption ? " selected" : "" ); tab.onclick = function( event ){ var selected_tabs = document.getElementsByClassName("submenu-bar-button timeframe selected"); var i, l = selected_tabs.length; for (i = 0; i < l; i++) { selected_tabs[i].className = selected_tabs[i].className.replace('selected', ''); } this.tab.className += " selected"; selectedOption = this.key; selectedIsin = null; this.that.createStocksSelector(response[this.key]); this.that.loadInfoStream(); event.preventDefault(); event.stopPropagation(); }.bind( { tab : tab, key : key, that : this } ) tabs_selector.appendChild( tab ); } }.bind( this )); }; overviewScreen.createStocksSelector = function ( stocks ) { if ( stocks.length == 0 ) { stocks_selector.textContent = "Selected timeframe has no posts related to stocks."; } else { stocks.sort( function(a,b) { var weight_a = a.count + ( a.replies * 0.5 ); var weight_b = b.count + ( b.replies * 0.5 ); if ( weight_a > weight_b ) { return -1 } if ( weight_a < weight_b ) { return 1 } return 0; } ) var table = document.createElement("TABLE"); table.style.width = "100%"; var i, l = stocks.length, tr, td_name, td_isin, td_count; for ( i = 0; i < l; i++ ) { tr = document.createElement("TR"); if ( selectedIsin == stocks[i].isin ) { tr.className += " isin-selected-row"; } tr.style.lineHeight = "18px"; tr.style.cursor = "pointer"; tr.onclick = function(event){ selectedIsin = this.isin; this.that.loadInfoStream(); var selected_tabs = document.getElementsByClassName("isin-selected-row"); var i, l = selected_tabs.length; for (i = 0; i < l; i++) { selected_tabs[i].className = selected_tabs[i].className.replace('isin-selected-row', ''); } event.target.parentNode.className += " isin-selected-row"; }.bind( { isin : stocks[i].isin, that : this } ) td_name = document.createElement("TD"); td_name.style.cursor = "pointer"; td_name.style.textDecoration = "underline"; td_name.textContent = stocks[i].name; td_isin = document.createElement("TD"); td_isin.style.cursor = "pointer"; td_isin.textContent = stocks[i].isin; td_count = document.createElement("TD"); td_count.textContent = stocks[i].count + " Beiträge, " + stocks[i].replies + " Kommentar" + (stocks[i].replies > 0 ? 'e' : ''); tr.appendChild( td_name ); tr.appendChild( td_isin ); tr.appendChild( td_count ); table.appendChild(tr); } stocks_selector.textContent = ""; stocks_selector.appendChild(table); } }; overviewScreen.loadInfoStream = function () { overviewScreen.infoStream.resetInfoStream(); overviewScreen.infoStream.element.innerHTML = ""; overviewScreen.firstLoad = true; overviewScreen.numberOfPostsShown = numberOfPostsShown; overviewScreen.output.appendChild(overviewScreen.infoStream.element_always_top); overviewScreen.output.appendChild(overviewScreen.infoStream.element); overviewScreen.output.appendChild(overviewScreen.loadingContainer); overviewScreen.fetchInfoStream(function (data) { overviewScreen.infoStream.buildInfoStream(data); if(overviewScreen.infoStreamLoadedCallback){ overviewScreen.infoStreamLoadedCallback(); } }); }; overviewScreen.onInfoStream = function (callback) { overviewScreen.infoStreamLoadedCallback = callback; }; overviewScreen.onNewPost = function (callback) { newPostCallback = callback; }; overviewScreen.removeListeners = function () { }; var removeLoadButton = function () { overviewScreen.newPostsInfo.removeChild(loadButton); loadButton = null; }; overviewScreen.close = function (onCloseCallback) { overviewScreen.element.parentNode.removeChild( overviewScreen.element ) if ( onCloseCallback ) { onCloseCallback(); } }; overviewScreen.createUI = function () { overviewScreen.output = document.createElement("DIV"); overviewScreen.output.className = "infostream-output"; overviewScreen.newPostsInfo = document.createElement("DIV"); overviewScreen.newPostsInfo.className = "infostream-newPosts"; overviewScreen.createOverviewSection(); overviewScreen.output.appendChild(overviewScreen.newPostsInfo); overviewScreen.element.appendChild(overviewScreen.output); overviewScreen.infoStream = new InfoStream(username, id); overviewScreen.loadInfoStream(); currentView.setNewView( { type : 'overview', id : 'main', onChangeView : null, calls : { postSharedElement : [ this, this.postSharedElement ] } } ) }.bind(this); return overviewScreen; } /* A child of TradersScreen containing the users a user follows. */ function FollowsScreen(id, viewerid) { currentView.setNewView( { type : 'follows', id : parseInt(id), onChangeView : null } ) var followsScreen = new TradersScreen("Followed Traders"); socketGateway.emit("loadFollowedUsers", id, function (data) { var i, dataLength = data.length; if (dataLength > 0) { followsScreen.createTableHeader(); for (i = 0; i < dataLength; i++) { followsScreen.createTrader(data[i], id, viewerid, 'follows'); } } }); return followsScreen; } /* A child of TradersScreen containing the followers of a user. */ function FollowerScreen(id, viewerid) { currentView.setNewView( { type : 'follower', id : parseInt(id), onChangeView : null } ) var followerScreen = new TradersScreen("Followers"); socketGateway.emit("loadFollowers", id, function (data) { var i, dataLength = data.length; if (dataLength > 0) { followerScreen.createTableHeader(); for (i = 0; i < dataLength; i++) { followerScreen.createTrader(data[i], id, viewerid, 'follower'); } } }); return followerScreen; } /* A screen showing a list of traders. */ function TradersScreen(title) { var followScreen = {}; followScreen.element = document.createElement("DIV"); var table; var follow = {}; var createUI = function () { var header = document.createElement("H2"); header.className = "title"; header.appendChild(document.createTextNode(title)); table = document.createElement("DIV"); table.className = "group-table"; followScreen.element.className = "followScreen groups-container"; followScreen.element.appendChild(header); }; followScreen.createTableHeader = function () { followScreen.element.appendChild(table); }; followScreen.createTrader = function (data, profileId, viewerid, view) { var id = data.id; var username = data.username; var picturePath = data.picturePath; var followers = data.followers; var follows = data.follows; var send_email = data.send_email; var element = document.createElement("DIV"); element.className = "group-element user"; var picture = document.createElement("IMG"); picture.className = "picture"; picture.src = projectDomain + picturePath; var pic_section = document.createElement("DIV"); pic_section.className = "frame"; pic_section.appendChild(picture); element.appendChild(pic_section); var info_section = document.createElement("DIV"); info_section.className = "info-section"; element.appendChild(info_section); var th2 = document.createElement("DIV"); th2.className = "name"; th2.onclick = function () { socketGateway.emit("getProfile", { "userid": id }); }; th2.appendChild(document.createTextNode(username)); info_section.appendChild(th2); var th3 = document.createElement("DIV"); th3.className = "sec"; var followers_title = document.createElement("DIV"); followers_title.className = "sec-title"; followers_title.appendChild(document.createTextNode("Followers")); th3.appendChild(followers_title); var followers_number = document.createElement("DIV"); followers_number.className = "sec-number"; followers_number.appendChild(document.createTextNode(followers)); th3.appendChild(followers_number); info_section.appendChild(th3); var th4 = document.createElement("DIV"); th4.className = "sec"; var follows_title = document.createElement("DIV"); follows_title.className = "sec-title"; follows_title.appendChild(document.createTextNode("Folge ich")); th4.appendChild(follows_title); var follows_number = document.createElement("DIV"); follows_number.className = "sec-number"; follows_number.appendChild(document.createTextNode(follows)); th4.appendChild(follows_number); info_section.appendChild(th4); if (viewerid == profileId) { //is my own view var emailButton = document.createElement("INPUT"); emailButton.type = "checkbox"; emailButton.checked = send_email; emailButton.onchange = function () { socketGateway.emit("changeFollowedEmailNotification", { "id": id, "send_email" : emailButton.checked }, function () { }); }; var th5 = document.createElement("DIV"); th5.className = "sec"; var email_title = document.createElement("DIV"); email_title.className = "sec-title"; email_title.appendChild(document.createTextNode("Email notification")); th5.appendChild(email_title); var email_input = document.createElement("DIV"); email_input.className = "sec-number"; email_input.appendChild(emailButton); th5.appendChild(email_input); var followButton = document.createElement("BUTTON"); followButton.textContent = data.followed ? "Entfolgen" : "Folgen"; followButton.className = data.followed ? "cancel" : "ok"; followButton.onclick = function () { alertManager.ask("Wirklich entfolgen?", function () { socketGateway.emit("unfollowUser", { "id": id }, function () { table.removeChild(element); delete follow[id]; }); }); }; var blockButton = document.createElement("BUTTON"); blockButton.textContent = data.blocked ? "Aufheben" : "Blockieren"; blockButton.className = data.blocked ? "cancel" : "ok"; blockButton.onclick = function () { alertManager.ask("Blockierung aufheben?", function () { socketGateway.emit("unblockOtherUser", { "id": id }, function () { table.removeChild(element); delete follow[id]; }); }); }; var th6 = document.createElement("DIV"); th6.className = "sec-title button"; if (view == 'follows') { th6.appendChild(followButton); //info_section.appendChild(th5); //push not implemented yet. info_section.appendChild(th6); } else if (view === "blocked") { th6.appendChild(blockButton); // info_section.appendChild(th5); info_section.appendChild(th6); } } table.appendChild(element); follow[id] = { "username": username, "picturePath": picturePath, "followers": followers, "element": element }; }; createUI(); return followScreen; } /* The entry point for creating and entering a group. */ function GroupsScreen(id, viewerid, subheader_element, callback ) { var groupsScreen = {}; currentView.setNewView( { type : 'groups', id : 'all', onChangeView : function(){ currentHome.unsubscribe( 'onUpdateCurrentUserPermissions' , groupsScreen.onUpdateCurrentUserPermissions, groupsScreen ); } } ) groupsScreen.onUpdateCurrentUserPermissions = function(){ }; groupsScreen.element = document.createElement("DIV"); groupsScreen.addGroupButton = null; groupsScreen.createGroup = function() { if ( groupsScreen.addGroupButton ) { groupsScreen.addGroupButton.click(); } } var pictureStandardSize = 250; groupsScreen.groups = {}; var myGroupsTable; var premiumGroupsTable; var promotedGroupsTable; var otherGroupsTable; var createGroupsTable; var groupDescriptionScreen; var isUserLoggedIn = function () { return id !== undefined; }; var isOwner = function () { return id !== undefined && id == viewerid; }; var createUI = function (callback) { groupsScreen.element.innerHTML = ""; var myGroupsDiv = document.createElement("DIV"); myGroupsDiv.className = "groups-container"; var otherGroupsDiv = document.createElement("DIV"); otherGroupsDiv.className = "groups-container"; var createGroupsDiv = document.createElement("DIV"); createGroupsDiv.className = "groups-container"; var premiumGroupsDiv = document.createElement("DIV"); premiumGroupsDiv.className = "groups-container"; var promotedGroupsDiv = document.createElement("DIV"); promotedGroupsDiv.className = "groups-container"; /* JOINED groups */ var myGroupsTitle = document.createElement("DIV"); myGroupsTitle.className = "title"; myGroupsTitle.appendChild(document.createTextNode("Mitgliedschaften")); myGroupsTable = document.createElement("DIV"); myGroupsTable.className = "groups-table"; myGroupsDiv.appendChild(myGroupsTitle); /* premium groups */ var premiumGroupsTitle = document.createElement("DIV"); premiumGroupsTitle.className = "title"; premiumGroupsTitle.appendChild(document.createTextNode("Moderierte TraderFox-Gruppen (nur für Kunden)")); premiumGroupsTable = document.createElement("DIV"); premiumGroupsTable.className = "groups-table"; premiumGroupsDiv.appendChild(premiumGroupsTitle); /*promoted groups*/ var promotedGroupsTitle = document.createElement("DIV"); promotedGroupsTitle.className = "title"; promotedGroupsTitle.appendChild(document.createTextNode("")); promotedGroupsTable = document.createElement("DIV"); promotedGroupsTable.className = "groups-table"; promotedGroupsDiv.appendChild(promotedGroupsTitle); /* Available groups */ var otherGroupsTitle = document.createElement("DIV"); otherGroupsTitle.className = "title"; otherGroupsTitle.appendChild(document.createTextNode("Weitere Gruppen")); otherGroupsTable = document.createElement("DIV"); otherGroupsTable.className = "groups-table"; otherGroupsDiv.appendChild(otherGroupsTitle); var groupsNotAvailable = document.createTextNode("Keine Gruppen vorhanden."); if (isUserLoggedIn()) { if (isOwner()) { if ( subheader_element != undefined ) { var AllButton = document.createElement("BUTTON"); AllButton.textContent = "Alle"; AllButton.className = "submenu-bar-button selected"; AllButton.onclick = function () { createGroupsDiv.style.display = 'block'; premiumGroupsDiv.style.display = 'block'; myGroupsDiv.style.display = 'block'; promotedGroupsDiv.style.display = 'block'; otherGroupsDiv.style.display = 'block'; selectButton(AllButton); }; subheader_element.appendChild(AllButton); var ModerierteButton = document.createElement("BUTTON"); ModerierteButton.textContent = "Premium"; ModerierteButton.className = "submenu-bar-button"; ModerierteButton.onclick = function () { createGroupsDiv.style.display = 'none'; premiumGroupsDiv.style.display = 'block'; myGroupsDiv.style.display = 'none'; promotedGroupsDiv.style.display = 'block'; otherGroupsDiv.style.display = 'none'; selectButton(ModerierteButton); }; subheader_element.appendChild(ModerierteButton); var MyButton = document.createElement("BUTTON"); MyButton.textContent = "Mitgliedschaften"; MyButton.className = "submenu-bar-button"; MyButton.onclick = function () { createGroupsDiv.style.display = 'none'; premiumGroupsDiv.style.display = 'none'; myGroupsDiv.style.display = 'block'; promotedGroupsDiv.style.display = 'none'; otherGroupsDiv.style.display = 'none'; selectButton(MyButton); }; subheader_element.appendChild(MyButton); } var createGroupsTitle = document.createElement("DIV"); createGroupsTitle.className = "title"; createGroupsDiv.appendChild(createGroupsTitle); groupsScreen.element.appendChild(createGroupsDiv); groupsScreen.element.appendChild(promotedGroupsDiv); groupsScreen.element.appendChild(premiumGroupsDiv); groupsScreen.element.appendChild(myGroupsDiv); var addGroupButton = document.createElement("BUTTON"); groupsScreen.addGroupButton = addGroupButton; addGroupButton.className = "add-group-button"; addGroupButton.textContent = "Gruppe hinzufügen +"; var createGroupScreen; addGroupButton.onclick = function () { if(!createGroupScreen){ addGroupButton.textContent = "Gruppe hinzufügen -"; createGroupScreen = new GroupCreator(); createGroupScreen.onDecision(function (args) { if (args) { if (groupsNotAvailable.parentNode === otherGroupsDiv) { otherGroupsDiv.removeChild(groupsNotAvailable); } myGroupsDiv.appendChild(myGroupsTable); args["membersCount"] = 1; addMyGroup(args); } addGroupButton.disabled = false; }); createGroupsDiv.appendChild(createGroupScreen.element); } else{ addGroupButton.textContent = "Gruppe hinzufügen +"; createGroupsDiv.removeChild(createGroupScreen.element); createGroupScreen = undefined; } }; createGroupsTitle.appendChild(addGroupButton); } groupsScreen.element.appendChild(promotedGroupsDiv); groupsScreen.element.appendChild(premiumGroupsDiv); groupsScreen.element.appendChild(myGroupsDiv); } else { myGroupsDiv.style.display = "none"; } if (isOwner()) { groupsScreen.element.appendChild(otherGroupsDiv); } groupDescriptionScreen = document.createElement("DIV"); groupsScreen.element.appendChild(groupDescriptionScreen); socketGateway.emit("loadGroupsList", id, function (data) { var dataLength = data.length, i, group; if (dataLength > 0) { myGroupsDiv.appendChild(myGroupsTable); otherGroupsDiv.appendChild(otherGroupsTable); premiumGroupsDiv.appendChild(premiumGroupsTable); promotedGroupsDiv.appendChild(promotedGroupsTable); } else { otherGroupsDiv.appendChild(groupsNotAvailable) } for (i = 0; i < dataLength; i++) { group = data[i]; if ( group.promoted == 'Y' ) { addPromotedGroup(group); if ( group.joined ) { addMyGroup(group); } } else if (group.permission == 'chatrooms' ) { addPremiumGroup(group); if ( group.joined ) { addMyGroup(group); } } else if (group.joined) { addMyGroup(group); } else { addOtherGroup(group); } } if ( callback ) { callback(); } }); }; groupsScreen.convertOtherGroupToMyGroup = function (groupid) { var group = groupsScreen.groups[groupid]; var element = group.element; var groupName = group.groupName; var membersCount = group.membersCount; var picturePath = group.picturePath; var newElement = createGroup({ "groupid": groupid, "name": groupName, "membersCount": membersCount + 1, "picturePath": picturePath }); var button = document.createElement("BUTTON"); button.textContent = "Ansehen"; button.onclick = function () { currentHome.group(groupid); }; button.className = "open-group-button"; newElement.appendChild(button); otherGroupsTable.removeChild(element); myGroupsTable.appendChild(newElement); group.element = newElement; }; groupsScreen.convertMyGroupToOtherGroup = function (groupid) { var group = groupsScreen.groups[groupid]; var element = group.element; var groupName = group.groupName; var membersCount = group.membersCount; var picturePath = group.picturePath; var newElement = createGroup({ "groupid": groupid, "name": groupName, "membersCount": membersCount, "picturePath": picturePath }); var button = document.createElement("BUTTON"); button.textContent = "Beitreten"; button.onclick = function () { alertManager.ask("Möchten Sie der Gruppe beitreten?", function () { joinGroup(newElement, groupid, groupName, membersCount, picturePath); }); }; button.className = "join-group-button"; newElement.appendChild(button); myGroupsTable.removeChild(element); otherGroupsTable.appendChild(newElement); group.element = newElement; }; var addMyGroup = function (args) { var groupElement = createGroup(args); if (isOwner()) { var button = document.createElement("BUTTON"); button.textContent = "Öffnen"; button.onclick = function () { currentHome.group(args.id); }; button.className = "open-group-button"; groupElement.appendChild(button); } else { //todo implement checking of other user groups if I am also in } myGroupsTable.appendChild(groupElement); }; var addPremiumGroup = function (args) { var groupElement = createGroup(args); if (isUserLoggedIn()) { if (args.joined) { var button = document.createElement("BUTTON"); button.textContent = "Öffnen"; button.onclick = function () { currentHome.group(args.id); /*socketGateway.emit("openGroup", { "groupid": args.id }); */ }; button.className = "open-group-button"; groupElement.appendChild(button); } else { if (currentUser.allowed_permissions[args.permission] ) { //== 'Y' var button = document.createElement("BUTTON"); button.textContent = "Beitreten"; button.onclick = function () { alertManager.ask("Möchten Sie der Gruppe beitreten?", function () { joinGroup(groupElement, args.id, args.name, args.membersCount, args.picturePath); }); }; button.className = "join-group-button"; groupElement.appendChild(button); } else { var button = document.createElement("BUTTON"); button.textContent = "Kunde werden"; button.onclick = function () { helper.createAdsWindow( permsLinks[args.permission].img, permsLinks[args.permission].order ) }; button.className = "open-group-button cancel"; groupElement.appendChild(button); } } } premiumGroupsTable.appendChild(groupElement); }; var addPromotedGroup = function (args) { var groupElement = createGroup(args); if ( isUserLoggedIn() ) { if (args.joined) { var button = document.createElement("BUTTON"); button.textContent = "Open"; button.onclick = function () { currentHome.group( args.id, function(){} ); }; button.className = "open-group-button"; groupElement.appendChild(button); } else if ( args.permission == null || currentUser.allowed_permissions[args.permission]) { // == 'Y' var button = document.createElement("BUTTON"); button.textContent = "Beitreten"; button.onclick = function () { alertManager.ask("Möchten Sie der Gruppe beitreten?", function () { joinGroup(groupElement, args.id, args.name, args.membersCount, args.picturePath); }); }; button.className = "join-group-button"; groupElement.appendChild(button); } else { var button = document.createElement("BUTTON"); button.textContent = "Kunde werden"; button.onclick = function () { helper.createAdsWindow( permsLinks[args.permission].img, permsLinks[args.permission].order ) }; button.className = "open-group-button cancel"; groupElement.appendChild(button); } } else { //todo implement checking of other user groups if I am also in } promotedGroupsTable.appendChild(groupElement); }; var addOtherGroup = function (args) { var groupElement = createGroup(args); if (isUserLoggedIn() && isOwner()) { var button = document.createElement("BUTTON"); button.textContent = "Beitreten"; button.onclick = function () { alertManager.ask("Möchten Sie der Gruppe beitreten?", function () { joinGroup(groupElement, args.id, args.name, args.membersCount, args.picturePath); }); }; button.className = "join-group-button"; groupElement.appendChild(button); } else { //todo implement checking of other user groups if I am also in } otherGroupsTable.appendChild(groupElement); }; var joinGroup = function (groupElement, groupid, groupName, membersCount, picturePath) { socketGateway.emit("joinGroup", { "groupid": groupid }, function (data) { if (data.result) { currentHome.group(groupid); currentHome.api.sendEvent( { 'type' : 'notification', 'event' : 'update-groups', 'value' : 'join' } ) //groupsScreen.convertOtherGroupToMyGroup(groupid); } else { if (permsLinks[data.permission] != undefined) { helper.createAdsWindow( permsLinks[data.permission].img, permsLinks[data.permission].order ) } else { alert(data.error + ': ' + data.permission) } } }); }; var createGroup = function (args) { var groupName = args.name; var groupDescription = args.description; var membersCount = args.membersCount || 0; var picturePath = args.picturePath; var groupElement = document.createElement("DIV"); groupElement.className = "group-element"; var groupPictureCell = document.createElement("DIV"); groupPictureCell.className = "picture"; var groupPicture = new Image(); groupPicture.onload = function () { var imageRatio = groupPicture.width / groupPicture.height; if (imageRatio >= 1) { groupPicture.width = pictureStandardSize; groupPicture.height = pictureStandardSize / imageRatio; } else { groupPicture.width = pictureStandardSize; groupPicture.height = pictureStandardSize / imageRatio; } }; groupPicture.src = projectDomain + picturePath; groupPictureCell.appendChild(groupPicture); groupPictureCell.onclick = function () { showGroupInfo(args.id || args.groupid); }; var post_count = document.createElement("SPAN"); post_count.style.color = "#CE0C2F"; post_count.style.float = "left"; post_count.style.clear = "both"; if ( args.new_posts == 1 ) { post_count.textContent = " (1 new post)"; } else if ( args.new_posts > 1 ) { post_count.textContent = " (" +args.new_posts + " new posts)"; } post_count.onclick = function( event ) { currentHome.group(args.id || args.groupid) event.stopPropagation(); event.preventDefault(); } var group_name_span = document.createElement("SPAN"); group_name_span.textContent = groupName; group_name_span.style.float = "left"; var groupNameElement = document.createElement("DIV"); groupNameElement.appendChild( group_name_span ); groupNameElement.appendChild(post_count ); groupNameElement.className = "name"; groupNameElement.onclick = function () { showGroupInfo(args.id || args.groupid); }; var membersCountElement = document.createElement("DIV"); var memebers_text = args.show_members == 'Y' ? ( membersCount == 1 ? "1 Mitglied" : membersCount + " Mitglieder" ) : 'TraderFox-Abonennten mit Zugangsberechtigung'; membersCountElement.appendChild(document.createTextNode( memebers_text)); membersCountElement.className = "count"; var groupDescriptionElement = document.createElement("DIV"); groupDescriptionElement.appendChild(document.createTextNode(groupDescription)); groupDescriptionElement.className = "description"; groupElement.appendChild(groupPictureCell); groupElement.appendChild(groupNameElement); groupElement.appendChild(groupDescriptionElement); groupElement.appendChild(membersCountElement); groupsScreen.groups[args.id] = { "element": groupElement, "membersCount": membersCount, "groupName": groupName, "picturePath": picturePath, "groupPictureElement": groupPicture }; return groupElement; }; var selectButton = function (button) { deselectButtons(); button.className += " selected"; }; var deselectButtons = function () { var buttons = document.getElementsByClassName("submenu-bar-button selected"); var i, l = buttons.length; for (i = 0; i < l; i++) { buttons[i].className = buttons[i].className.replace("selected", ""); } }; var showGroupInfo = function (groupid) { socketGateway.emit("getGroupInfo", groupid); }; currentHome.subscribe( 'onUpdateCurrentUserPermissions' , groupsScreen.onUpdateCurrentUserPermissions, groupsScreen ); createUI( callback ); return groupsScreen; } /* The entry point for creating and entering a group. */ function UserGroupsScreen(id, viewerid) { var groupsScreen = {}; currentView.setNewView( { type : 'groups', id : 'all', onChangeView : function(){ currentHome.unsubscribe( 'onUpdateCurrentUserPermissions' , groupsScreen.onUpdateCurrentUserPermissions, groupsScreen ); } } ) groupsScreen.onUpdateCurrentUserPermissions = function(){ //todo update group buttons }; groupsScreen.element = document.createElement("DIV"); var pictureStandardSize = 250; groupsScreen.groups = {}; var myGroupsTable; var premiumGroupsTable; var promotedGroupsTable; var otherGroupsTable; var createGroupsTable; var groupDescriptionScreen; var isUserLoggedIn = function () { return id !== undefined; }; var isOwner = function () { return id !== undefined && id == viewerid; }; var createUI = function () { groupsScreen.element.innerHTML = ""; var myGroupsDiv = document.createElement("DIV"); myGroupsDiv.className = "groups-container"; /* user JOINED groups */ var myGroupsTitle = document.createElement("DIV"); myGroupsTitle.className = "title"; myGroupsTitle.appendChild(document.createTextNode("Mitgliedschaften")); myGroupsTable = document.createElement("DIV"); myGroupsTable.className = "groups-table"; myGroupsDiv.appendChild(myGroupsTitle); myGroupsDiv.appendChild(myGroupsTable); groupsScreen.element.appendChild(myGroupsDiv); groupDescriptionScreen = document.createElement("DIV"); groupsScreen.element.appendChild(groupDescriptionScreen); socketGateway.emit("loadUserGroupsList", { userid : id } , function (data) { var l = data.length, i; for ( i = 0; i < l; i++) { addMyGroup(data[i]); } }); }; var addMyGroup = function (args) { var button; var groupElement = createGroup(args); if ( args.joined ) { button = document.createElement("BUTTON"); button.className = "open-group-button"; button.textContent = "Öffnen"; button.onclick = function () { currentHome.group(args.id); }; groupElement.appendChild(button); } else { if ( args.permission == null || currentUser.allowed_permissions[args.permission] ) { //== 'Y' button = document.createElement("BUTTON"); button.className = "join-group-button"; button.textContent = "Beitreten"; button.onclick = function () { alertManager.ask("Möchten Sie der Gruppe beitreten?", function () { joinGroup(groupElement, args.id, args.name, args.membersCount, args.picturePath); }); }; } else { button = document.createElement("BUTTON"); button.className = "open-group-button cancel"; button.textContent = "Kunde werden"; button.onclick = function () { helper.createAdsWindow( permsLinks[args.permission].img, permsLinks[args.permission].order ) }; } if ( currentUser.id != undefined ) { groupElement.appendChild(button); } } myGroupsTable.appendChild(groupElement); }; var createGroup = function (args) { var groupName = args.name; var groupDescription = args.description; var membersCount = args.membersCount || 0; var picturePath = args.picturePath; var groupElement = document.createElement("DIV"); groupElement.className = "group-element"; var groupPictureCell = document.createElement("DIV"); groupPictureCell.className = "picture"; var groupPicture = new Image(); groupPicture.onload = function () { var imageRatio = groupPicture.width / groupPicture.height; if (imageRatio >= 1) { groupPicture.width = pictureStandardSize; groupPicture.height = pictureStandardSize / imageRatio; } else { groupPicture.width = pictureStandardSize; groupPicture.height = pictureStandardSize / imageRatio; } }; groupPicture.src = projectDomain + picturePath; groupPictureCell.appendChild(groupPicture); groupPictureCell.onclick = function () { showGroupInfo(args.id || args.groupid); }; var post_count = document.createElement("SPAN"); post_count.style.color = "#CE0C2F"; post_count.style.float = "left"; post_count.style.clear = "both"; if ( args.new_posts == 1 ) { post_count.textContent = " (1 new post)"; } else if ( args.new_posts > 1 ) { post_count.textContent = " (" +args.new_posts + " new posts)"; } post_count.onclick = function( event ) { currentHome.group(args.id || args.groupid) event.stopPropagation(); event.preventDefault(); } var group_name_span = document.createElement("SPAN"); group_name_span.textContent = groupName; group_name_span.style.float = "left"; var groupNameElement = document.createElement("DIV"); groupNameElement.appendChild( group_name_span ); groupNameElement.appendChild(post_count ); groupNameElement.className = "name"; groupNameElement.onclick = function () { showGroupInfo(args.id || args.groupid); }; var membersCountElement = document.createElement("DIV"); var memebers_text = args.show_members == 'Y' ? ( membersCount == 1 ? "1 Mitglied" : membersCount + " Mitglieder" ) : 'TraderFox-Abonennten mit Zugangsberechtigung'; membersCountElement.appendChild(document.createTextNode( memebers_text)); membersCountElement.className = "count"; var groupDescriptionElement = document.createElement("DIV"); groupDescriptionElement.appendChild(document.createTextNode(groupDescription)); groupDescriptionElement.className = "description"; groupElement.appendChild(groupPictureCell); groupElement.appendChild(groupNameElement); groupElement.appendChild(groupDescriptionElement); groupElement.appendChild(membersCountElement); groupsScreen.groups[args.id] = { "element": groupElement, "membersCount": membersCount, "groupName": groupName, "picturePath": picturePath, "groupPictureElement": groupPicture }; return groupElement; }; var showGroupInfo = function (groupid) { socketGateway.emit("getGroupInfo", groupid); }; var joinGroup = function (groupElement, groupid, groupName, membersCount, picturePath) { socketGateway.emit("joinGroup", { "groupid": groupid }, function (data) { if ( data.result ) { currentHome.group(groupid); } else { if (permsLinks[data.permission] != undefined) { helper.createAdsWindow( permsLinks[data.permission].img, permsLinks[data.permission].order ) } else { alert(data.error + ': ' + data.permission) } } }); }; currentHome.subscribe( 'onUpdateCurrentUserPermissions' , groupsScreen.onUpdateCurrentUserPermissions, groupsScreen ); createUI(); return groupsScreen; } /* A Group that contains its header and the groupChatScreen. Could possibly be merged with groupChatScreen. */ function Group(args) { var group = {}; group.chatScreen; group.auto_reload_input; group.sort_input; group.is_writing = false; var groupid = args.groupid; var userid = args.userid; var username = args.username; var latestPostTimestamp = args.latestPostTimestamp; var groupName = args.groupName; var membersCount = args.membersCount; var picture = args.picture; var writers = args.writers; var is_admin = args.isAdmin; var onLeaveCallback; var default_settings = { "sort" : "activity", //post "auto_update" : false //post } group.settings = currentUser.group_settings[args.groupid] != undefined ? currentUser.group_settings[args.groupid] : default_settings; socketGateway.emit("setGroupNotificationsAsRead", { "groupid": groupid }, function () {}); group.element = document.createElement("DIV"); group.submitGroupSettings = function( callback ){ group.settings["sort"] = group.sort_input.value; group.settings["auto_update"] = group.auto_reload_input.checked; socketGateway.emit( "updateGroupSettings", { group_id : groupid, value : group.settings }, function(response){ currentUser.group_settings[groupid] = group.settings; if ( callback ) { callback(); } } ); }; group.createSettingsMenu = function( element ) { element.innerHTML = ""; //auto reload; var auto_reload_div = document.createElement("DIV"); auto_reload_div.style.float = "left"; auto_reload_div.style.width = "100%"; auto_reload_div.style.border = "1px solid rgb(192, 193, 197) !important"; auto_reload_div.style.borderRadius = "2px"; auto_reload_div.style.padding = "0px"; var auto_reload_tag = document.createElement("DIV"); auto_reload_tag.textContent = " Automatisch aktualisieren "; auto_reload_tag.style.float = "left"; auto_reload_tag.style.marginTop = "1px"; group.auto_reload_input = document.createElement("INPUT"); group.auto_reload_input.type = "checkbox"; group.auto_reload_input.style.float = "right"; group.auto_reload_input.style.marginTop = "3px"; group.auto_reload_input.checked = group.settings["auto_update"]; group.auto_reload_input.onchange = function( event ) { group.submitGroupSettings( function(){} ); event.stopPropagation(); event.preventDefault(); } auto_reload_div.appendChild( auto_reload_tag ); auto_reload_div.appendChild( group.auto_reload_input ); element.appendChild( auto_reload_div ); //sort var sort_div = document.createElement("DIV"); sort_div.style.float = "left"; sort_div.style.clear = "both"; sort_div.style.marginTop = "4px"; group.sort_input = document.createElement("SELECT"); group.sort_input.setAttribute('style', 'border-color:rgb(192, 193, 197) !important;background:white !important;float:left;'); var sort_by_post = document.createElement("OPTION"); sort_by_post.textContent = "Sortieren nach Postingzeit"; sort_by_post.value = "post"; sort_by_post.selected = group.settings["sort"] == "post"; group.sort_input.appendChild( sort_by_post ); var sort_by_activity = document.createElement("OPTION"); sort_by_activity.textContent = "Sortieren nach Aktivität"; sort_by_activity.value = "activity"; sort_by_activity.selected = group.settings["sort"] == "activity"; group.sort_input.appendChild( sort_by_activity ); group.sort_input.onchange = function( event ) { group.submitGroupSettings( function(){ currentHome.group( groupid ) } ); event.stopPropagation(); event.preventDefault(); } //sort_div.appendChild(sort_tag); sort_div.appendChild(group.sort_input); element.appendChild( sort_div ); }; (group.createUI = function () { var groupHeader = document.createElement("DIV"); groupHeader.className = "groups-container group-header"; var groupPictureContainer = document.createElement("DIV"); groupPictureContainer.className = "group-image-container"; var groupPicture = document.createElement("IMG"); groupPicture.className = "group-image"; groupPicture.src = projectDomain + picture; var groupTitle = document.createElement("DIV"); groupTitle.className = "title"; groupTitle.style.cursor = "pointer"; groupTitle.textContent = groupName; groupTitle.title = groupName + " neu laden"; groupTitle.onclick = function( event ) { currentHome.group( groupid ) event.stopPropagation(); event.preventDefault(); } var leaveGroupButton = document.createElement("BUTTON"); leaveGroupButton.className = "cancel group-info"; leaveGroupButton.textContent = "Gruppe verlassen"; leaveGroupButton.onclick = function () { alertManager.ask("Gruppe '" + groupName + "' verlassen?", function () { socketGateway.emit("leaveGroup", { "userid": userid, "groupid": groupid }, function () { onLeaveCallback(groupid); currentHome.api.sendEvent( { 'type' : 'notification', 'event' : 'update-groups', 'value' : '' } ) }); }); }; var settings_row = document.createElement("DIV"); settings_row.className = "group-settings-area"; group.createSettingsMenu(settings_row); group.chatScreen = new GroupChatScreen(groupid, userid, username, latestPostTimestamp, writers, groupTitle, groupName, group.settings ); group.chatScreen.createUI(); group.is_writing = false; if ( group.chatScreen.postEditor != undefined ) { group.chatScreen.postEditor.textField.onfocus = function(){ group.is_writing = true; } group.chatScreen.postEditor.textField.onblur = function(){ group.is_writing = false; } } group.chatScreen.onNewPost(function (newTimestamp, posterid) { if ( newTimestamp ) { latestPostTimestamp = newTimestamp; } if ( group.settings["auto_update"] && !group.is_writing ) { currentHome.group( groupid ); } }); group.chatScreen.onInfoStream(function () { }); var tr2 = document.createElement("DIV"); var descriptionCell = document.createElement("SPAN"); descriptionCell.className = "title-container"; var description = document.createElement("DIV"); description.className = "description"; description.textContent = args.description; descriptionCell.appendChild(description); tr2.appendChild(descriptionCell); groupPictureContainer.appendChild(groupPicture); groupHeader.appendChild(groupPictureContainer); groupHeader.appendChild(groupTitle); groupHeader.appendChild(tr2); if (!args.isAdmin) { groupHeader.appendChild(leaveGroupButton); } groupHeader.appendChild(settings_row); group.element.appendChild(groupHeader); group.element.appendChild(group.chatScreen.element); })(); //used to change the position of the Group in the GroupsScreen group.onLeave = function (callback) { onLeaveCallback = callback; }; return group; } /* An form for creating a new group. */ function GroupCreator() { var groupCreator = {}; var onDecisionCallback; var groupImageObject; var pictureStandardSize = 250; groupCreator.element = document.createElement("DIV"); groupCreator.element.className = "group-form"; var name_module = document.createElement("DIV"); name_module.className = "section"; var groupName = document.createElement("INPUT"); groupName.type = "text"; var nameTitle = document.createElement("DIV"); nameTitle.className = "title"; nameTitle.appendChild(document.createTextNode("Bezeichnung der Gruppe")); name_module.appendChild(nameTitle); name_module.appendChild(groupName); groupCreator.element.appendChild(name_module); var description_module = document.createElement("DIV"); description_module.className = "section"; var descriptionTitle = document.createElement("DIV"); descriptionTitle.appendChild(document.createTextNode("Beschreibung")); descriptionTitle.className = "title"; var groupDescription = document.createElement("TEXTAREA"); groupDescription.onkeydown = function () { setTimeout(function () { //resize text field groupDescription.style.cssText = 'height:auto; padding:0'; groupDescription.style.cssText = 'height:' + ( groupDescription.scrollHeight + 10 ) + 'px'; }, 0); }; description_module.appendChild(descriptionTitle); description_module.appendChild(groupDescription); groupCreator.element.appendChild(description_module); var buttons_module = document.createElement("DIV"); buttons_module.className = "section"; var createButton = document.createElement("BUTTON"); createButton.textContent = "Gruppe anlegen"; createButton.className = "ok group-creator"; createButton.onclick = function () { socketGateway.emit("addGroup", { "groupName": groupName.value, "groupDescription": groupDescription.value, "groupImage": groupImageObject }, function (args) { if (args.response === "ok") { onDecisionCallback(args); groupCreator.element.parentNode.removeChild(groupCreator.element); currentHome.api.sendEvent( { 'type' : 'notification', 'event' : 'update-groups', 'value' : '' } ) } else { alertManager.inform("Bezeichnung bereits vergeben!"); } }); }; var groupPictureUploadContainer = document.createElement("DIV"); groupPictureUploadContainer.className = "group-picture-uploader"; var pictureContainer = document.createElement("LABEL"); pictureContainer.for = "change-picture"; var pictureElement = document.createElement("IMG"); pictureContainer.appendChild(pictureElement); var uploader = new UploadCreator(); var pu = new PictureUploader({ "startingPicture": projectDomain + "/groupPictures/default.png", "viewport": { width: 150, height: 75 }, "boundary": { width: 205, height: 130 } }); pu.onUploadReady(this, function (fileObject, blob) { groupCreator.element.appendChild(buttons_module); groupImageObject = fileObject; uploader.readFileAsDataURL(blob, function (result) { pu.createCropper(result); }); }); pu.onUploadCanceled(this, function () { groupCreator.element.appendChild(buttons_module); }); pu.onChangePictureClick(this, function () { groupCreator.element.removeChild(buttons_module); }); pu.createCropper(); pu.createChangeButton(); groupPictureUploadContainer.appendChild(pu.element); var resizePicture = function (result) { var newPicture = document.createElement("IMG"); newPicture.onmousedown = function (event) { event.preventDefault(); //avoid redropping the picture in the box }; newPicture.onload = function () { var imageRatio = newPicture.width / newPicture.height; if (imageRatio >= 1) { newPicture.width = pictureStandardSize; newPicture.height = pictureStandardSize / imageRatio; } else { newPicture.width = pictureStandardSize; newPicture.height = pictureStandardSize / imageRatio; } pictureContainer.replaceChild(newPicture, pictureElement); pictureElement = newPicture; pictureContainer.className = "picture-selected"; }; newPicture.src = result; }; var fileUploadButton = document.createElement("INPUT"); fileUploadButton.type = "file"; fileUploadButton.accept = ".jpg,.gif,.png,.jpeg"; fileUploadButton.id = "change-picture"; fileUploadButton.style.position = "absolute"; fileUploadButton.style.visibility = "hidden"; fileUploadButton.onchange = function (event) { var data = event.target.files; uploader.readFileAsDataURL(data[0], function (result) { resizePicture(result); if (uploadLabel.parentNode === pictureContainer) { pictureContainer.removeChild(uploadLabel); } }); uploader.createFileUpload(data[0], function (fileObject) { if ( !fileObject.result ) { alertManager.inform(fileObject.message) } else { groupImageObject = fileObject; } }); }; var uploadLabel = document.createElement("DIV"); uploadLabel.textContent = "Bild hochladen"; //pictureContainer.appendChild(uploadLabel); //pictureContainer.appendChild(fileUploadButton); groupPictureUploadContainer.ondragover = function (event) { if(uploadLabel.parentNode === pictureContainer){ pictureContainer.removeChild(uploadLabel); } groupPictureUploadContainer.style.border = "4px dashed #7eaad1"; event.preventDefault(); }; groupPictureUploadContainer.ondragleave = function (event) { pictureContainer.appendChild(uploadLabel); groupPictureUploadContainer.style.border = ""; event.preventDefault(); }; groupPictureUploadContainer.ondrop = function (event) { event.stopPropagation(); event.preventDefault(); groupPictureUploadContainer.style.border = ""; var data = event.dataTransfer.files; uploader.readFileAsDataURL(data[0], function (fileObject) { resizePicture(fileObject); }); uploader.createFileUpload(data[0], function (fileObject) { if ( !fileObject.result ) { alertManager.inform(fileObject.message) } else { groupImageObject = fileObject; } }); }; groupCreator.element.appendChild(groupPictureUploadContainer); buttons_module.appendChild(createButton); groupCreator.element.appendChild(buttons_module); groupCreator.onDecision = function (callback) { onDecisionCallback = callback; }; return groupCreator; } /* The info screen you get if you press on a group */ function GroupInfo(args) { var groupInfo = {}; var onLeaveCallback; var onJoinCallback; var groupid = args.id; groupInfo.pictureManager; groupInfo.element = document.createElement("DIV"); currentView.setNewView( { type : 'groupInfo', id : 'groupid', onChangeView : function(){ currentHome.unsubscribe( 'onUpdateCurrentUserPermissions' , groupInfo.onUpdateCurrentUserPermissions, groupInfo ); } } ) var isCurrentUserAdmin = function () { return args.admin === args.userid; }; var isCurrentUserMember = function () { return args.joined && hasCurrentUserPermission() ; }; var hasCurrentUserPermission = function() { return args.permission == null || currentUser.allowed_permissions[args.permission];// == 'Y'; }; var isCurrentUserOnline = function () { return args.userid !== undefined; }; groupInfo.onUpdateCurrentUserPermissions = function(){ resetView(); createHeader(); createMembersSection(); }; //used to change the position of the Group in the GroupsScreen groupInfo.onLeave = function (callback) { onLeaveCallback = callback; }; //used to change the position of the Group in the GroupsScreen groupInfo.onJoin = function (callback) { onJoinCallback = callback; }; var resetView = function() { groupInfo.element.innerHTML = ""; }; var createHeader = function () { var container = document.createElement("DIV"); container.className = "groups-container"; var groupInfoTable = document.createElement("DIV"); groupInfoTable.className = "group-info-table"; groupInfoTable.className = "group-info-table"; var tr0 = document.createElement("DIV"); tr0.className = "group-picture-container"; var tr1 = document.createElement("DIV"); tr1.className = "group-info-container"; groupInfo.pictureManager = new PictureUploader({ "startingPicture": projectDomain + args.picturePath, "viewport": { width: 150, height: 75 }, "boundary": { width: 205, height: 130 }, "groupid": groupid }); groupInfo.pictureManager.onUploadReady(groupInfo, function (fileObject) { fileObject["groupid"] = groupid; socketGateway.emit("uploadGroupPicture", fileObject); }); if(isCurrentUserAdmin()){ groupInfo.pictureManager.createChangeButton(); groupInfo.pictureManager.createCropper(); } else{ groupInfo.pictureManager.createPicture(); } var pictureCell = document.createElement("SPAN"); pictureCell.appendChild(groupInfo.pictureManager.element); var titleCell = document.createElement("SPAN"); titleCell.className = "title-container"; var title = document.createElement("DIV"); title.className = "title"; title.textContent = args.name; titleCell.appendChild(title); if (isCurrentUserAdmin()) { title.contentEditable = true; var resetTitleDiv = function () { editTitleOkButton.style.display = "none"; editTitleCancelButton.style.display = "none"; window.getSelection().removeAllRanges(); //remove cursor from editable title div }; var editTitleOkButton = document.createElement("BUTTON"); editTitleOkButton.textContent = "Update title"; editTitleOkButton.className = "ok group-info"; editTitleOkButton.onmousedown = function () { var data = {"title": title.textContent, "groupid": groupid, "userid": args.userid}; socketGateway.emit("changeGroupName", data, function (newTitle) { title.textContent = newTitle; resetTitleDiv(); }); }; var editTitleCancelButton = document.createElement("BUTTON"); editTitleCancelButton.textContent = "Cancel"; editTitleCancelButton.className = "cancel group-info"; editTitleCancelButton.onmousedown = function () { resetTitleDiv(); }; editTitleOkButton.style.display = "none"; editTitleOkButton.style.marginTop = "2px"; editTitleCancelButton.style.display = "none"; editTitleCancelButton.style.marginTop = "2px"; titleCell.appendChild(editTitleOkButton); titleCell.appendChild(editTitleCancelButton); title.onfocus = function () { editTitleOkButton.style.display = "block"; editTitleCancelButton.style.display = "block"; }; title.onblur = function () { editTitleOkButton.style.display = "none"; editTitleCancelButton.style.display = "none"; }; } var buttonsCell = document.createElement("SPAN"); buttonsCell.className = "buttons-container"; if (isCurrentUserOnline()) { var openButton = document.createElement("BUTTON"); openButton.textContent = "Öffnen"; openButton.className = "ok group-info"; openButton.onclick = function () { currentHome.group(args.id); }; var joinLeaveButton = document.createElement("BUTTON"); joinLeaveButton.textContent = isCurrentUserMember() ? "Verlassen" : "Beitreten"; joinLeaveButton.className = isCurrentUserMember() ? "cancel group-info" : "ok group-info"; joinLeaveButton.style.clear = "both"; if ( !hasCurrentUserPermission() ) { joinLeaveButton.textContent = "Kunde werden"; joinLeaveButton.className = "cancel group-info"; var permission_needed_info = document.createElement("DIV"); permission_needed_info.style.float = 'left'; permission_needed_info.style.clear = 'both'; permission_needed_info.textContent = " -Sie haben keine Zugriffsrechte für diese Gruppe."; } joinLeaveButton.onclick = function () { if (isCurrentUserMember() ) { alertManager.ask("Gruppe '" + args.name + "' verlassen?", function () { socketGateway.emit("leaveGroup", { "userid": args.userid, "groupid": groupid }, function () { args.joined = false; joinLeaveButton.textContent = isCurrentUserMember() ? "Verlassen" : "Beitreten"; joinLeaveButton.className = isCurrentUserMember() ? "cancel group-info" : "ok group-info"; onLeaveCallback(); }); }); } else { if ( !hasCurrentUserPermission() ) { if (permsLinks[args.permission] != undefined) { helper.createAdsWindow( permsLinks[args.permission].img, permsLinks[args.permission].order ) } } else { alertManager.ask("Der Gruppe '" + args.name + "' beitreten?", function () { socketGateway.emit("joinGroup", { "groupid": groupid }, function (data) { if (data.result) { args.joined = true; joinLeaveButton.textContent = isCurrentUserMember() ? "Verlassen" : "Beitreten"; joinLeaveButton.className = isCurrentUserMember() ? "cancel group-info" : "ok group-info"; onJoinCallback(); } else { if (permsLinks[data.permission] != undefined) { helper.createAdsWindow( permsLinks[data.permission].img, permsLinks[data.permission].order ) } else { alert(data.error + ': ' + data.permission) } } }); }); } } }; if(isCurrentUserMember()){ buttonsCell.appendChild(openButton); } if (!isCurrentUserAdmin()) { //admin can not leave/join his own group if( permission_needed_info != undefined ){ buttonsCell.appendChild(permission_needed_info); } buttonsCell.appendChild(joinLeaveButton); } } tr0.appendChild(pictureCell); tr1.appendChild(titleCell); var descriptionCell = document.createElement("SPAN"); descriptionCell.className = "title-container"; var description = document.createElement("DIV"); description.className = "description"; description.textContent = args.description; descriptionCell.appendChild(description); if (isCurrentUserAdmin()) { description.contentEditable = true; var resetDescriptionDiv = function () { editDescriptionOkButton.style.display = "none"; editDescriptionCancelButton.style.display = "none"; window.getSelection().removeAllRanges(); //remove cursor from editable title div }; var editDescriptionOkButton = document.createElement("BUTTON"); editDescriptionOkButton.textContent = "Update description"; editDescriptionOkButton.className = "ok group-info"; editDescriptionOkButton.onmousedown = function () { var data = {"description": description.textContent, "groupid": groupid, "userid": args.userid}; socketGateway.emit("changeGroupDescription", data, function (newDescription) { description.textContent = newDescription; resetDescriptionDiv(); }); }; var editDescriptionCancelButton = document.createElement("BUTTON"); editDescriptionCancelButton.textContent = "Cancel"; editDescriptionCancelButton.className = "cancel group-info"; editDescriptionCancelButton.onmousedown = function () { resetDescriptionDiv(); }; editDescriptionOkButton.style.display = "none"; editDescriptionOkButton.style.marginTop = "2px"; editDescriptionCancelButton.style.display = "none"; editDescriptionCancelButton.style.marginTop = "2px"; descriptionCell.appendChild(editDescriptionOkButton); descriptionCell.appendChild(editDescriptionCancelButton); description.onfocus = function () { editDescriptionOkButton.style.display = "block"; editDescriptionCancelButton.style.display = "block"; }; description.onblur = function () { editDescriptionOkButton.style.display = "none"; editDescriptionCancelButton.style.display = "none"; }; } tr1.appendChild(descriptionCell); if ( !isCurrentUserMember() && args.live_posting_now ) { var ongoing_live = document.createElement("DIV"); ongoing_live.innerHTML = "
 
In dieser Gruppe findet gerade ein Live-Posting statt. Du musst der Gruppe beitreten, um es sehen zu können.
"; tr1.appendChild( ongoing_live ); } tr1.appendChild(buttonsCell); groupInfoTable.appendChild(tr0); groupInfoTable.appendChild(tr1); container.appendChild(groupInfoTable); groupInfo.element.appendChild(container); }; var createMembersSection = function () { if (args.permission != null && !currentUser.allowed_permissions[args.permission] ) { // != 'Y' var groupMembersContainer = document.createElement("DIV"); groupMembersContainer.className = "groups-container members no-perms"; groupMembersContainer.innerHTML = "Das ist ein Premium-Gruppe
" + " Sie benötigen folgendes Abo: " + permsLinks[args.permission]["abo"] + ""; groupInfo.element.appendChild(groupMembersContainer); } else if ( args.show_members == 'Y' ) { var groupMembersContainer = document.createElement("DIV"); groupMembersContainer.className = "groups-container members"; var title = document.createElement("DIV"); title.className = "title"; title.textContent = "Mitglieder"; groupMembersContainer.appendChild(title); var display, members = args.members; var i, l = members.length; for (i = 0; i < l; i++) { display = createMemberDisplay(members[i]); groupMembersContainer.appendChild(display); } groupInfo.element.appendChild(groupMembersContainer); } }; var createMemberDisplay = function (member) { var element = document.createElement("DIV"); element.className = "group-element user"; var picture = document.createElement("IMG"); picture.className = "picture"; picture.src = projectDomain + member.profilePicturePath; picture.title = member.name; picture.onclick = function () { socketGateway.emit("getProfile", { "userid": member.id }); }; var pic_section = document.createElement("DIV"); pic_section.appendChild(picture); element.appendChild(pic_section); var info_section = document.createElement("DIV"); info_section.className = "info-section"; element.appendChild(info_section); var th2 = document.createElement("DIV"); th2.className = "name"; th2.onclick = function () { socketGateway.emit("getProfile", { "userid": member.id }); }; th2.appendChild(document.createTextNode(member.name)); // info_section.appendChild(th2); return element; }; groupInfo.getScrollDimensions = function () { var dimensions = {}; dimensions["fullHeight"] = groupInfo.element.parentNode.scrollHeight; dimensions["scrollTop"] = groupInfo.element.parentNode.scrollTop; dimensions["clientHeight"] = groupInfo.element.parentNode.clientHeight; dimensions["currentHeight"] = dimensions["scrollTop"] + dimensions["clientHeight"]; return dimensions; }; currentHome.subscribe( 'onUpdateCurrentUserPermissions' , groupInfo.onUpdateCurrentUserPermissions, groupInfo ); (function createUI() { resetView(); createHeader(); createMembersSection(); })(); return groupInfo; } /* A screen containing the infostream of a group and its post editor */ function LiveScreen() { var liveScreen = new Object(); liveScreen.element = document.createElement("DIV"); liveScreen.element.className = "infostream-element live"; var no_live = document.createElement("DIV"); no_live.innerHTML = "
Aktuell wird kein Live-Beitrag erstellt.
"; no_live.style.display = "none"; liveScreen.element.appendChild( no_live ); var live_posts = {}; currentView.setNewView( { type : 'live', id : 'all', onChangeView : function(){ currentHome.unsubscribe( 'livePosting' , liveScreen.onLivePost, liveScreen ); } } ) liveScreen.onLivePost = function ( data ) { var key = data.group + '|' + data.poster; if ( data.type == 'start' ) { if ( live_posts[key] == undefined ) { createLivePost( data ) } else { live_posts[key]['title'].textContent = data.title; live_posts[key]['data'] = data; } } else if ( data.type == 'end' ) { if ( live_posts[key] != undefined ) { var element = live_posts[key]['element']; element.parentNode.removeChild(element); delete live_posts[key]; } } else if ( data.type == 'title' ) { if ( live_posts[key] != undefined ) { live_posts[key]['title'].textContent = data.title; live_posts[key]['data'] = data; } else { createLivePost( data ) } } if ( Object.keys(live_posts).length == 0 ) { no_live.style.display = "block"; } else { no_live.style.display = "none"; } }; var createLivePost = function( data ) { /* * * group:95 group_name:"Test Alex" group_permissions:null group_picture:"/groupPictures/95/1496759299872.png" poster:30 poster_name:"GP" poster_picture:"/profilePictures/30/1502865868135.png" poster_title:"Software engineer" text:"123" title:"123" * * */ var element = document.createElement("DIV"); element.className = "infostream-mainpost live-post-index"; var picture_element = document.createElement("IMG"); picture_element.className = "picture"; picture_element.src = projectDomain + data.poster_picture; var author_text_container = document.createElement("DIV"); author_text_container.className = "author-container"; var author_element = document.createElement("DIV") author_element.className = "author"; author_element.textContent = data.poster_name; if ( currentUser.admin ) { var cancel_live = document.createElement("BUTTON"); cancel_live.className = "cancel"; cancel_live.style.left = "auto"; cancel_live.style.marginTop = "0px"; cancel_live.textContent = "ADMIN: Cancel this user Live Posting."; cancel_live.onclick = function( event ) { socketGateway.emit("adminCancelLivePosting", { "poster" : data.poster, "group" : data.group }, function () {} ) event.stopPropagation(); event.preventDefault(); } author_element.appendChild(cancel_live); } var description_element = document.createElement("DIV"); description_element.className = "description"; description_element.innerHTML = " hat gerade in der Gruppe " + "" + data.group_name + "" + " ein Live-Posting gestartet"; author_text_container.appendChild( author_element ) author_text_container.appendChild( description_element ) var title_element = document.createElement("DIV"); title_element.className = "title"; title_element.textContent = data.title; element.appendChild( picture_element ); element.appendChild( author_text_container ); element.appendChild( title_element ); liveScreen.element.appendChild( element ); element.onclick = function( event ) { currentHome.group( data.group, function(){} ) event.stopPropagation(); }; live_posts[data.group+'|'+data.poster] = { 'element' : element, 'title' : title_element, 'data' : data } ; } currentHome.subscribe( 'livePosting' , liveScreen.onLivePost, liveScreen ); socketGateway.emit("getAllfLivePostings", {}, function (data) { var i, l = data.length; if ( l > 0 ) { no_live.style.display = "none"; for ( i = 0; i < l; i++ ) { createLivePost( data[i] ); } } else { no_live.style.display = "block"; } } ) return liveScreen; } /* An element containing a list of posts. */ var InfoStream = function (username, userid, public_profile_id) { var infoStream = {}; var posts = {}; infoStream.element = document.createElement("DIV"); infoStream.element.className = "infostream-element"; infoStream.element_always_top = document.createElement("DIV"); infoStream.element_always_top.className = "infostream-element"; infoStream.createNewPostListeners = function (post, callback) { //the callback is to remove the notification popup post post.onDeletePost(function (replyArgs) { infoStream.deletePost(replyArgs.postid); if (callback) { callback(); } }); post.onHidePost(function (replyArgs) { infoStream.deletePost(replyArgs.postid); if (callback) { callback(); } }); post.onEditPost(function (replyArgs) { infoStream.editPost(replyArgs.postid, replyArgs.timestamp, replyArgs.text, replyArgs.attachments, replyArgs.tags, replyArgs.replies, replyArgs.stocks, replyArgs.picturePath, replyArgs.news, replyArgs.cloud, replyArgs.groupid, replyArgs.group_name); if (callback) { callback(); } }); }; infoStream.addPostAtEnd = function (args) { //for laoding more on scroll if ( args.visible == undefined || args.visible ) { if ( public_profile_id ) { args.public_profile_id = public_profile_id; } var post = new MainPost(args); infoStream.createNewPostListeners(post); post.createElement(); infoStream.element.appendChild(post.element); post.initialize(); infoStream.setPost(post); } else { infoStream.element.appendChild(this.createPermissionMissingPost( args ), infoStream.element.firstChild); } }; infoStream.addPostAtBeginning = function (args) { //for laoding data from server if ( args.visible == undefined || args.visible ) { if ( public_profile_id ) { args.public_profile_id = public_profile_id; } var post = new MainPost(args); infoStream.createNewPostListeners(post); post.createElement(); infoStream.element.insertBefore(post.element, infoStream.element.firstChild); post.initialize(); infoStream.setPost(post); } else { infoStream.element.insertBefore(this.createPermissionMissingPost( args ), infoStream.element.firstChild); } }; infoStream.createPermissionMissingPost = function( post ){ var holder = document.createElement("DIV"); holder.className = "infostream-mainpost"; holder.style.fontSize = "13px"; holder.style.padding = "3px 0px"; holder.style.backgroundColor = "#c15d5d"; holder.style.color = "white"; holder.style.cursor = "pointer"; holder.style.textAlign = "center"; holder.onclick = function( event ) { helper.createAdsWindow( permsLinks[post.permission_missing].img, permsLinks[post.permission_missing].order ) event.preventDefault(); } if ( permsLinks[post.permission_missing] == undefined ) { console.log(post.permission_missing) } holder.textContent = "Sie haben keine Zugriffsrechte für diese Gruppe. Sie benötigen folgendes Abo: " + permsLinks[post.permission_missing].abo; return holder; }; infoStream.postGroupVisible = function (post) { //console.log(post.groupid); }; infoStream.setPost = function (post) { posts[post.getId()] = post; }; infoStream.resetInfoStream = function () { posts = {}; }; infoStream.buildInfoStream = function (data) { var i, l = data.length; for (i = 0; i < l; i++) { var post = data[i]; if (!(post.postid in posts)) { if(post.roomid){ post["type"] = infoStream.determineRoomMessageType(post, i, data); } post["readerid"] = userid; infoStream.addPostAtBeginning(post); } } }; infoStream.determineRoomMessageType = function(post, index, data) { var l = data.length, type = "firstLast", nextPost; if(index === 0 && l > 1){ nextPost = data[index + 1]; type = nextPost.posterName === post.posterName ? "last" : "firstLast"; } else if(index === 0 && l === 1){ type = "firstLast"; } else if(index === l - 1){ type = "first"; } else{ var previousPost = data[index - 1]; nextPost = data[index + 1]; if(previousPost.posterName === post.posterName && nextPost.posterName === post.posterName){ type = "middle"; } else if(previousPost.posterName === post.posterName && nextPost.posterName !== post.posterName){ type = "first"; } else if(previousPost.posterName !== post.posterName && nextPost.posterName === post.posterName){ type = "last"; } } return type; }; infoStream.addOlderToInfoStream = function (data) { var i, l = data.length; for (i = l - 1; i >= 0; i--) { var post = data[i]; if (!(post.postid in posts)) { post["readerid"] = userid; infoStream.addPostAtEnd(post); } } }; infoStream.addOlderBefore = function (data) { var i, l = data.length; for (i = 0; i < l; i++) { var post = data[i]; if (!(post.postid in posts)) { post["readerid"] = userid; infoStream.addPostAtBeginning(post); } } }; infoStream.getPost = function (postid) { return posts[postid]; }; infoStream.getLastPost = function () { var lastMessageid = Math.max.apply(null, Object.keys(posts)) return posts[lastMessageid]; }; infoStream.deletePost = function (postid) { if ( posts[postid] != undefined ) { var postElement = posts[postid].element; postElement.parentNode.removeChild(postElement); delete posts[postid]; } }; infoStream.editPost = function (postid, timestamp, text, attachments, tags, replies, stocks, picturePath, news, cloud, group_id, group_name, nice_title ) { var nextSibling = posts[postid].element.nextSibling; infoStream.deletePost(postid); posts[postid] = new MainPost({ "postid": postid, "readerid": userid, "posterName": username, "posterid": userid, "timestamp": timestamp, "text": text, "attachments": attachments, "tags": tags, "stocks": stocks, "news": news, "cloud": cloud, "edited": true, "replies": replies, "picturePath": picturePath, "groupid": group_id, "groupName" : group_name, "nice_title" : nice_title }); infoStream.createNewPostListeners(posts[postid]); posts[postid].createElement(); infoStream.element.insertBefore(posts[postid].element, nextSibling); posts[postid].initialize(); }; infoStream.getPosts = function () { return posts; }; infoStream.addOlderToTweetsStream = function(tweets){ var i, l = tweets.length; for (i = 0; i < l; i++) { infoStream.addTweetAtEnd(tweets[i]); } }; infoStream.buildTweetsStream = function(tweets){ infoStream.element.innerHTML = ""; infoStream.addOlderToTweetsStream(tweets); }; infoStream.addTweetAtEnd = function (args) { var tweet = new ChartTweet(args); tweet.createElement(); infoStream.element.appendChild(tweet.element); tweet.initialize(); }; return infoStream; }; /* A child of InfoStream. Since the groups have now the same type of posts inside, it's kinda obsolete and could be replaced with InfoStream. */ var InfoStreamGroup = function (username, userid, groupid) { var infoStream = new InfoStream(username, userid); infoStream.addPostAtEnd = function (args) { if(groupid === args.groupid){ var post = new MainPost(args); infoStream.createNewPostListeners(post); post.createElement(); infoStream.element.appendChild(post.element); post.initialize(); infoStream.setPost(post); } }; infoStream.addPostAtBeginning = function (args, always_top) { if(groupid === args.groupid){ var post = new MainPost(args); if ( args.type != 'live' ) { infoStream.createNewPostListeners(post); } post.createElement(); if ( always_top ) { infoStream.element_always_top.insertBefore(post.element, infoStream.element_always_top.firstChild); } else { infoStream.element.insertBefore(post.element, infoStream.element.firstChild); } post.initialize(); if ( args.type != 'live' ) { infoStream.setPost(post); } return post; } }; return infoStream; }; /* The settings of a user. Contains email-subscriptions and a way to change the user picture. */ function StreamSettingsScreen() { this.names_map = { "wingman" : "TraderFox Wingman Chartsignale", "dpa" : "Wichtige Nachrichten bei dpa-AFX ProFeed", "calendar" : "TraderFox Kalender", "followed" : "Alle Postings von Tradern, denen ich folge" } this.special_perms = { "wingman" : "software", "dpa" : "dpa-afx" } this.stream_settings = {}; this.element = document.createElement("DIV"); this.inputs = {}; socketGateway.emit("getStreamSettings", {}, function (response) { if ( response.result ) { this.stream_settings = response.data; this.createUI(); } else { this.element.innerHTML = "
Error found. Login needed.
"; } }.bind( this )); this.saveStreamSettings = function(){ socketGateway.emit("updateStreamSettings", { stream_settings : this.stream_settings }, function (response) { //console.log( response ) } ) } this.createUI = function () { var key, checkbox; var interest_section = document.createElement("DIV") interest_section.className = "standard-section"; interest_section.innerHTML = "Meinen Stream konfigurieren" + "Legen Sie hier fest was im Stream angezeigt werden soll. Unser System lernt automatisch hinzu was Sie interessiert. Klicken Sie auf den \"Interessiert mich\" Button unter einem Post, wenn Sie etwas interessiert. "; this.element.appendChild(interest_section); //todo render cheboxes for this.stream_settings["interest"] if ( this.stream_settings["interest"] != undefined ) { for ( key in this.stream_settings["interest"] ) { checkbox = this.createCheckboxWithTitle( this.stream_settings["interest"][key], key ); checkbox.onchange = function( event ) { this.section[this.key] = !this.section[this.key]; this.that.saveStreamSettings(); event.stopPropagation(); event.preventDefault(); }.bind( { section : this.stream_settings["interest"], key : key, that : this } ) } } var bots_section = document.createElement("DIV") bots_section.className = "standard-section"; bots_section.innerHTML = "TraderFox-Bots"; this.element.appendChild(bots_section); //todo render cheboxes for this.stream_settings["bots"] if ( this.stream_settings["bots"] != undefined ) { for ( key in this.stream_settings["bots"] ) { checkbox = this.createCheckboxWithTitle( this.stream_settings["bots"][key], key ); checkbox.onchange = function( event ) { this.section[this.key] = !this.section[this.key]; this.that.saveStreamSettings(); event.stopPropagation(); event.preventDefault(); }.bind( { section : this.stream_settings["bots"], key : key, that : this } ) } } }; } StreamSettingsScreen.prototype.createCheckboxWithTitle = function ( isSelected, name ) { var checkboxContainer = document.createElement("DIV"); checkboxContainer.className = "traderchat-settings-container"; checkboxContainer.style.paddingLeft = "10px"; var boxtitle = document.createElement("DIV"); boxtitle.innerHTML = "" + this.names_map[name] + ""; boxtitle.className = "traderchat-checkbox-title"; var checkbox = document.createElement("INPUT"); checkbox.type = "checkbox"; checkbox.name = name; checkbox.checked = isSelected; checkbox.className = "traderchat-checkbox"; this.inputs[name] = checkbox; checkboxContainer.appendChild(checkbox); checkboxContainer.appendChild(boxtitle); if ( this.special_perms[name] != undefined && ( currentUser.allowed_permissions[this.special_perms[name]] == undefined || !currentUser.allowed_permissions[this.special_perms[name]] ) ) { //== 'N' checkbox.disabled = true; var box_subtitle = document.createElement("span"); box_subtitle.innerHTML = "Premium-Lizenz erforderlich: " + permsLinks[this.special_perms[name]].abo + ""; box_subtitle.style.href = permsLinks[this.special_perms[name]].order; box_subtitle.style.float = "left"; box_subtitle.style.clear = "both"; box_subtitle.style.textDecoration = "underline"; boxtitle.appendChild(box_subtitle); } this.element.appendChild(checkboxContainer); return checkbox; }; /* Child of Post. This is a post that also contains replies and attachments, and can be edited. */ function MainPost(args) { var mainPost = new Post(args); var id = parseInt(args.postid, 10); var readerid = args.readerid; var posterName = args.posterName; var posterid = parseInt(args.posterid, 10); var public_profile_id = args.public_profile_id; var highlighted_reply = args.highlighted_reply || null; var show_all_replies = args.show_all_replies != undefined ? args.show_all_replies : false; var text = args.text; var attachments = []; var tags = args.tags; var mentions = args.mentions; var stocks = args.stocks; var news = args.news; var cloud = args.cloud; var showMoreReplies = null; var repliesToShow = 5; var likeStatus = args.likeStatus; var replies = [];//args.replies ? args.replies : []; var groupid = args.groupid; var showCommentsButton = null; mainPost.element; mainPost.footer; //used for scroll mainPost.footerReplies; //used for scroll var bodyAttachments; var footerButtons; var footerReplies; var footerRepliesShow = false; var oldestReplyid; mainPost.replyEditor; mainPost.createEditButton = function () { var editButton = document.createElement("BUTTON"); editButton.textContent = "Edit"; editButton.className = "infostream-editButton"; editButton.onclick = function () { var editor = document.createElement("DIV"), i, attachmentsLength = attachments.length; mainPost.body.appendChild(editor); var postEditor = new MainPostEditor(id, editor, true, stocks, news, cloud, null, false); postEditor.init(); postEditor.textField.value = text; editor.className = editor.className += "infostream-input editor-focus"; postEditor.resizeTextField(); postEditor.getTagsFromText(text); postEditor.addTags(); /*hide original post*/ mainPost.bodyText.style.display = "none"; bodyAttachments.style.display = "none"; mainPost.menuButton.style.display = "none"; if (mainPost.readmore != null) { mainPost.readmore.style.display = "none"; } /********************/ for (i = 0; i < attachmentsLength; i++) { var attachment = attachments[i]; var attachmentObject = {}; var type = attachment.getType(); attachmentObject = { "path": attachment.getPath(), "type": type, "description": attachment.getDescription(), "url": attachment.getUrl(), "title": attachment.getTitle(), "name": attachment.getTitle() }; if (type === "file") { postEditor.attachmentManager.addFile(attachmentObject); } else if (type === "link") { postEditor.attachmentManager.setAttachmentToEdit(new EditableAttachment(attachment.getTitle(), attachment.getPath(), type, attachment.getUrl(), attachment.getDescription())); } else { attachmentObject["ytId"] = attachment.getPath(); postEditor.attachmentManager.addYouTube(attachmentObject); } } postEditor.onPost(mainPost.editPost.bind(this)); }; mainPost.menu.appendChild(editButton); }; mainPost.createBody = function () { mainPost.body = document.createElement("DIV"); mainPost.body.className = "infostream-post-body"; mainPost.bodyText = document.createElement("DIV"); mainPost.bodyText.className = "infostream-post-bodyText"; mainPost.body.appendChild(mainPost.bodyText); bodyAttachments = document.createElement("DIV"); bodyAttachments.className = "infostream-post-bodyAttachments"; if (args.attachments && args.attachments.length > 0) { createAttachments(args.attachments); } mainPost.body.appendChild(bodyAttachments); mainPost.element.appendChild(mainPost.body); mainPost.createBodyText(); }; mainPost.createFooter = function () { var footer = document.createElement("DIV"); footer.className = "infostream-post-footer"; footerButtons = document.createElement("DIV"); footerButtons.className = "footer-actions"; footerReplies = document.createElement("DIV"); footerReplies.className = "infostream-post-footerReplies"; // footerReplies.style.display = "none"; footerReplies.style.display = "float:left"; footer.appendChild(mainPost.footer_cloud); footer.appendChild(mainPost.footerStocks); footer.appendChild(mainPost.footer_news); footer.appendChild(footerButtons); footer.appendChild(footerReplies); if (readerid && args.type != 'live' ) { mainPost.replyEditor = new ReplyEditor(footer); mainPost.replyEditor.createInputField(); mainPost.replyEditor.createPostButton(); mainPost.replyEditor.onReply(function (text, tags) { socketGateway.emit("addReply", { "postid": id, "postPosterid": posterid, "text": text, "groupid": groupid }, function (args) { if (args.response === "ok") { mainPost.addReply({ "replyid": args.replyid, "readerid": readerid, "posterName": args.replyPosterName, "posterid": args.replyPosterid, "timestamp": args.timestamp, "text": args.text, "edited": false, "picturePath": args.picturePath }); mainPost.createShowCommentsButton(); createShowMoreRepliesButton(); showReplies(repliesToShow); footerReplies.style.display = "block"; } else { showRemovedPostAlert(); } }) }); mainPost.createLikeButton(); // mainPost.createCommentButton(); mainPost.createShowCommentsButton(); } if (args.cloud && args.cloud.length > 0) { mainPost.createPostCloud(); } if (args.stocks && args.stocks.length > 0) { mainPost.createPostStocks(); } if (args.news && args.news.length > 0) { mainPost.createPostNews(); } if ( currentView.type == 'chat' && ( args.group_counter > 1 || args.group_counter == 'many' ) ) { var footer_group_link = document.createElement("DIV"); footer_group_link.className = "infostream-post-group-counter"; footer_group_link.textContent = ( args.group_counter == 'many' ? ( 'Es gibt viele weitere Beiträge im "' + args.groupName + '"' ) : ( "Heute " + args.group_counter + ' weitere Beiträge in Gruppe "' + args.groupName + '"' ) ); footer_group_link.onclick = function(){ currentHome.group( groupid, function(){} ); } footer.appendChild(footer_group_link); } //if(!mainPost.isOwnPost() && readerid){ //why not liking my own stuff???!!! // mainPost.createLikeButton(); //} mainPost.element.appendChild(footer); mainPost.footer = footer; mainPost.footerReplies = footerReplies; }; mainPost.like = function (callback) { socketGateway.emit("likePost", { "postid": id, "posterid": posterid, "tags": tags, "groupid": groupid }, function (args) { if (args.response === "ok") { likeStatus = true; callback(); } else { showRemovedPostAlert(); } }); }; mainPost.unlike = function (callback) { socketGateway.emit("unlikePost", { "postid": id, "posterid": posterid, "tags": tags, "groupid": groupid }, function (args) { if (args.response === "ok") { likeStatus = false; callback(); } else { showRemovedPostAlert(); } }); }; mainPost.addReply = function (args) { var previous_element = null; var i, l = replies.length; for (i = 0; i < l; i++) { if (args.replyid == replies[i].getId()) { previous_element = replies[i].element; replies.splice(i, 1); break; } } var reply_input = mainPost.replyEditor ? mainPost.replyEditor.textField : null var reply = new Reply({ "postid": args.replyid, "readerid": args.readerid, "posterName": args.posterName, "posterid": args.posterid, "timestamp": args.timestamp, "text": args.text, "edited": args.edited, "picturePath": args.picturePath }, previous_element, reply_input ); reply.createElement(); reply.onClose(function (args) { args["postid"] = id; args["postPosterid"] = posterid; args["groupid"] = groupid; socketGateway.emit("deleteReply", args, function (args) { if (args.response === "ok") { mainPost.removeReply(args.replyid); } else { showRemovedPostAlert(); } }); }); reply.onCloseAdmin(function (args) { args["postid"] = id; args["postPosterid"] = posterid; args["groupid"] = groupid; socketGateway.emit("adminDeleteReply", args, function (args) { if (args.response === "ok") { mainPost.removeReply(args.replyid); } else { showRemovedPostAlert(); } }); }); reply.onHide(function (args) { args["postid"] = id; args["postPosterid"] = posterid; args["groupid"] = groupid; socketGateway.emit("hideReply", args, function (args) { if (args.response === "ok") { mainPost.removeReply(args.replyid); } else { showRemovedPostAlert(); } }); }); reply.onEdit(function (args) { socketGateway.emit("editReply", { "postPosterid": posterid, "postid": id, "replyid": args.id, "replyText": args.text, "timestamp": args.timestamp, "groupid": groupid }, function (args) { if (args.response === "ok") { mainPost.editReply(args); } else { showStandardError("We have found an error saving the reply, please try again."); } }); }); replies.push(reply); if ( previous_element == null) { reply.element.style.display = 'none'; //by default they are hidden. footerReplies.appendChild(reply.element); if ( public_profile_id != undefined && args.posterid == public_profile_id ) { //show if we are showing specific user activity reply.element.style.display = 'block'; } //show post because of interesting reply; if( show_all_replies ) { reply.element.style.display = 'block'; } if ( highlighted_reply == args.replyid ) { reply.element.style.backgroundColor = '#FFEB3B'; } } }; mainPost.removeReply = function (replyid) { var i, l = replies.length; for (i = 0; i < l; i++) { if (replies[i].getId() == replyid) { footerReplies.removeChild(replies[i].element); replies.splice(i, 1); break; } } mainPost.createShowCommentsButton(); }; mainPost.editReply = function (args) { var i, l = replies.length; for (i = 0; i < l; i++) { if (replies[i].getId() == args.replyid) { replies[i].element.innerHTML = ""; mainPost.addReply({ "replyid": args.replyid, "readerid": readerid, "posterName": replies[i].posterName, "posterid": args.posterid, "timestamp": args.editedTimestamp, "text": args.replyText, "edited": true, "picturePath": args.picturePath }); break; } } }; mainPost.createElement = function () { mainPost.element = document.createElement("DIV"); if ( args.type == 'live' ) { mainPost.element.className = "infostream-mainpost live"; } else { mainPost.element.className = "infostream-mainpost"; } }; mainPost.initialize = function () { //need this because must be attached before creating for getting a valid height!! mainPost.createTitle([" Bearbeitet ", " Geschrieben "]); if ( args.type == 'live' || args.title != null ) { mainPost.createPostHeadTitle(); if ( args.title != null ) { mainPost.setPostHeadTitle( args.title ); } } mainPost.createBody(); mainPost.createFooter(); mainPost.createReplies(); }; mainPost.setPostContent = function ( text ) { mainPost.text = text; mainPost.bodyText.innerHTML = ""; mainPost.createBodyText(); }; mainPost.setPostAttachmentData = function( data ){ if ( data.cloud != undefined ) { mainPost.setCloud( data.cloud ); mainPost.createPostCloud(); } if ( data.news != undefined ) { mainPost.setNews( data.news ); mainPost.createPostNews(); } if ( data.stocks != undefined ) { mainPost.setStocks( data.stocks ); mainPost.createPostStocks(); } if ( data.attachments != undefined ) { bodyAttachments.innerHTML = ""; createAttachments(data.attachments); } }; mainPost.setPostHeadTitle = function ( text ) { if( ["mobile", "messenger"].indexOf( environment ) != -1 ){ text = text.replace( "(Cloud öffnen)", ""); } mainPost.head_title.innerHTML = text; }; mainPost.createPostHeadTitle = function () { mainPost.head_title = document.createElement("DIV"); mainPost.head_title.className = "infostream-post-body title"; mainPost.element.appendChild(mainPost.head_title); mainPost.head_title.onclick = function( event ) { helper.interpretTextClicked( event ); } }; mainPost.createReplies = function () { var replyid, reply, counter = 0; var i, l = args.replies ? args.replies.length : 0; for (i = 0; i < l; i++) { reply = args.replies[i]; if ( reply == null ) { continue; } replyid = reply.id; if (!oldestReplyid || replyid < oldestReplyid) { oldestReplyid = replyid; } mainPost.addReply({ "replyid": reply.id, "readerid": readerid, "posterName": reply.posterName, "posterid": reply.posterid, "timestamp": reply.timestamp, "text": reply.text, "edited": reply.edited, "picturePath": reply.picturePath }); counter++; } mainPost.createShowCommentsButton(); createShowMoreRepliesButton(); }; var createShowMoreRepliesButton = function () { if (showMoreReplies != null || show_all_replies ) { return; } showMoreReplies = document.createElement("DIV"); showMoreReplies.style.display = replies.length > 1 ? 'block' : 'none'; showMoreReplies.textContent = "Mehr Kommentare anzeigen..."; showMoreReplies.className = "readmore replies"; footerReplies.parentNode.insertBefore(showMoreReplies, footerReplies); showMoreReplies.onclick = function () { showReplies(repliesToShow); }; }; mainPost.createLikeButton = function () { var likeButton = document.createElement("BUTTON"); if (likeStatus) { likeButton.innerHTML = "Interesting!"; } else { likeButton.innerHTML = "Interessiert mich"; } likeButton.className = "infostream-actionButton"; likeButton.onclick = function () { if (likeStatus) { mainPost.unlike(function () { likeButton.innerHTML = "Interessiert mich"; }); } else { mainPost.like(function () { likeButton.innerHTML = "Interesting!"; }); } }; footerButtons.appendChild(likeButton); }; mainPost.createCommentButton = function () { if ( args.type == 'live' ) { return; } var createCommentButton = document.createElement("BUTTON"); createCommentButton.innerHTML = "Comment"; createCommentButton.className = "infostream-actionButton create-comment"; createCommentButton.onclick = function () { //toggle }; footerButtons.appendChild(createCommentButton); }; mainPost.createShowCommentsButton = function () { if ( args.type == 'live' ) { return; } var number_of_comments = replies.length; if (showCommentsButton == null) { showCommentsButton = document.createElement("BUTTON"); footerButtons.appendChild(showCommentsButton); showCommentsButton.onclick = function () { showHideFooterReplies(); }; } showCommentsButton.innerHTML = ( number_of_comments == 1 ? "1 Kommentar" : ( number_of_comments + " Kommentare") ); showCommentsButton.className = "infostream-actionButton number-of-comments"; showLastReply(); }; var showHideFooterReplies = function () { footerRepliesShow = !footerRepliesShow; showMoreReplies.style.display = replies.length > 1 ? 'block' : 'none'; // footerReplies.style.display = footerRepliesShow ? "block" : "none"; if (footerRepliesShow) { showReplies(repliesToShow); } else { //hide all but last repliesToShow = 5; var i, l = replies.length; for (i = 0; i < l - 1; i++) { replies[i].element.style.display = "none"; } } }; var showLastReply = function () { if (replies.length > 0) { replies[replies.length - 1].element.style.display = "block"; } }; /*var showReplies = function (num_to_show) { footerRepliesShow = true; var counter = 0; var i, l = replies.length; //hide last reply always visible and only show it if needed. if (l > 0) { replies[l - 1].element.style.display = "none"; } for (i = 0; i < l; i++) { replies[i].element.style.display = "block"; counter++; if (counter >= num_to_show) { showMoreReplies.style.display = 'block'; repliesToShow += repliesToShow; break; } else { showMoreReplies.style.display = 'none'; } } };*/ var showReplies = function (num_to_show) { footerRepliesShow = true; var counter = 0; var i, l = replies.length; for (i = l - 1; i >= 0; i--) { replies[i].element.style.display = "block"; counter++; if (counter >= num_to_show + 1) { showMoreReplies.style.display = 'block'; repliesToShow += repliesToShow; break; } else { showMoreReplies.style.display = 'none'; } } }; var showRemovedPostAlert = function () { alertManager.inform("Beitrag gelöscht!", function () { }); }; var showStandardError = function (text) { var display_text = text || "Fehler!"; alertManager.inform(display_text, function () { }); }; function createAttachments(argsAttachments) { for (var i = 0; i < argsAttachments.length; i++) { var attachment = new Attachment(argsAttachments[i].title, argsAttachments[i].path, argsAttachments[i].type, argsAttachments[i].url, argsAttachments[i].description, false); attachments.push(attachment); bodyAttachments.appendChild(attachment.element); } } return mainPost; } //created: "2019-03-06 10:22:17" // data: "{"isin":"DE000A0D9PT0","stock":{"name":"MTU Aero Engines AG","source":"EI"},"adj_type":"partial","interval":99,"quote_type":"candlestick","num_to_show":204,"start_date":"2018-05-16 09:00:00","end_date":"2019-03-06 09:00:00","x_offset":0,"y_offset":80,"items":[{"type":"horizontal","from":[false,198.0451696372996],"to":[false,198.0451696372996],"color":"rgba( 128, 128, 128, 1 )","dashed_line":true,"fixed":false,"line_weight":1,"information_of_quotes":true},{"type":"text","from":["2018-12-07 09:00:00",207.27773168847958],"to":["2018-07-27 09:00:00",215.39026955621856],"text":"Qualitätswert MTU ist bereit für einen Sprung auf über 200 Euro!","fixed":false,"font":"10px Arial","background_color":"rgba( 255, 215, 0, 1 )","border_color":"rgba( 0, 0, 0, 1 )","font_color":"rgba( 0, 0, 0, 1 )"}],"scans":[],"signals":[],"subcharts_data":{}}" // icon: "https://traderfox.com/charts/5abee9a32f7a7fb026486f0967a551dc6632a1ae.png" // id: 42320 // owner_id: 10447 // post_id: 45555 // title: "MTU Aero Engines AG (0,94%)" // type: "chart" // updated: "2019-03-06 10:22:17" // visible: "Y" function ChartTweet(args) { this.id = parseInt(args.postid, 10); this.comment = args.comment; this.title = args.title; if( ["mobile", "messenger"].indexOf( environment ) != -1 ){ this.title = this.title.replace( "(Cloud öffnen)", ""); } this.post_id = args.post_id; this.image = args.icon; this.created = ( args.updated != args.created ? " Bearbeitet " : " Geschrieben " ) + helper.timestampToBeauty( args.updated ); this.element; this.body; this.bodyText; this.footer; this.cloud_container; this.createBody = function () { this.body = document.createElement("DIV"); this.body.className = "infostream-post-body"; if ( this.element.scrollWidth < 720 ) { this.body.style.width = "calc( 100% )"; } else { this.body.style.width = "calc( 50% )"; this.body.style.padding = "0px"; this.body.style.margin = "0px"; } this.bodyText = document.createElement("DIV"); this.bodyText.className = "infostream-post-bodyText"; this.bodyText.style.maxHeight = "initial"; this.body.appendChild(this.bodyText); this.element.appendChild(this.body); if ( this.title ) { this.createTweeHeadTitle(); } this.createBodyText(); this.createTweetImage(); }; this.createBodyText = function () { var container = document.createElement('DIV'); container.className = "no_translate"; this.bodyText.appendChild(container); var text = document.createElement("SPAN"); text.style.clear = "both"; text.style.float = "left"; text.innerHTML = this.comment; container.appendChild( text ); if ( this.post_id ) { var read_more = document.createElement("SPAN"); read_more.textContent = "Post öffnen"; read_more.style.color = "#cc071e"; read_more.style.cursor = "pointer"; read_more.style.textDecoration = "underline"; read_more.style.clear = "both"; read_more.style.float = "left"; read_more.onclick = function(event) { if ( this.post_id ) { currentHome.post( this.post_id, function(){} ); } event.stopPropagation(); event.preventDefault(); }.bind(this) container.appendChild( read_more ); } }; this.createTweetImage = function(){ this.cloud_container.style.display = 'block'; var cloud_container = document.createElement("DIV"); cloud_container.className = ""; //tags-container main this.cloud_container.appendChild(cloud_container); var cloud_label = document.createElement("DIV"); cloud_label.className = "tag label"; cloud_label.textContent = ""; cloud_container.appendChild(cloud_label); this.cloud_container.appendChild(cloud_container); var cloud_icon = document.createElement("DIV"); //cloud_icon.className = "icon"; cloud_icon.innerHTML = "" ; var cloud_element = document.createElement("DIV"); cloud_element.className = "tag cloud"; //"tag cloud"; cloud_element.style.width = "100%"; cloud_element.onclick = function (event) { if( environment === "tradingdesk" && currentHome.externalAction != null ){ currentHome.externalAction.fn.call(currentHome.externalAction.context, { 'type' : 'cloud', id : this.id } ); } else if( ["mobile", "messenger"].indexOf( environment ) != -1 ){ new PictureViewer(rootElement, { "path": this.image }); } event.preventDefault(); }.bind(this) cloud_element.appendChild( cloud_icon ) cloud_container.appendChild(cloud_element); }; this.createImageContainer = function(){ this.cloud_container = document.createElement("DIV"); this.cloud_container.className = "footer-actions"; this.cloud_container.style.width = "calc( 50% - 40px )"; this.cloud_container.style.display = "float:left"; this.cloud_container.style.borderBottom = "0"; if ( this.element.scrollWidth < 720 ) { this.cloud_container.style.width = "calc( 100% - 40px )"; } else { this.cloud_container.style.width = "calc( 50% - 40px )"; } this.element.appendChild(this.cloud_container); }; this.createFooter = function () { this.footer = document.createElement("DIV"); this.footer.className = "infostream-post-footer"; var footerButtons = document.createElement("DIV"); footerButtons.className = "footer-actions"; this.footer.appendChild(footerButtons); this.element.appendChild(this.footer); }; this.createElement = function () { this.element = document.createElement("DIV"); this.element.className = "infostream-mainpost"; }; this.initialize = function () { //need this because must be attached before creating for getting a valid height!! /*if ( this.title ) { this.createTweeHeadTitle(); }*/ this.createImageContainer(); this.createBody(); this.createFooter(); }; this.setPostContent = function () { this.bodyText.innerHTML = ""; this.createBodyText(); }; this.createTweeHeadTitle = function () { this.head_title = document.createElement("DIV"); this.head_title.className = ""; //this.element.appendChild(this.head_title); if ( this.element.scrollWidth < 720 ) { this.cloud_container.appendChild(this.head_title); } else { this.bodyText.appendChild(this.head_title); } this.head_title.onclick = function(event) { if ( this.post_id ) { currentHome.post( this.post_id, function(){} ); } event.stopPropagation(); event.preventDefault(); }.bind(this) var title = document.createElement("span"); title.className = "infostream-post-body title"; title.style.paddingBottom = "0px"; title.style.float = "left"; title.style.clear = "both"; title.textContent = this.title; title.style.marginLeft = "0px"; title.style.paddingLeft = "0px"; this.head_title.appendChild(title); var timestamp = document.createElement("span"); timestamp.style.float = "left"; timestamp.style.clear = "both"; //timestamp.style.marginLeft = "20px"; timestamp.textContent = this.created; timestamp.style.paddingBottom = "10px"; timestamp.style.fontSize = "11px"; this.head_title.appendChild(timestamp); }; } /* An "abstract" class for other post types to inherit. It is an element with a title containing the user, a body with text and an empty footer . */ function Post(args) { var id = parseInt(args.postid); var readerid = args.readerid; var posterName = args.posterName; var posterid = parseInt(args.posterid, 10); var groupid = args.groupid; var group_name = args.groupName; var timestamp = args.timestamp; //var text = args.text; var edited = args.edited; var picturePath = args.picturePath; var tags = args.tags; var stocks = args.stocks; var mentions = args.mentions; var news = args.news; var cloud = args.cloud; var nice_title = args.nice_title; var post = {}; if ( args.type == 'live' ) { post.show_full_content = true; } else { post.show_full_content = args.show_full_content != undefined ? args.show_full_content : false; } post.timestamp = timestamp; post.posterid = posterid; post.groupid = groupid; post.text = args.text; post.readmore = null; post.element; post.title; post.body; post.menu; post.bodyText; post.posterName = posterName; post.picturePath = picturePath; post.edited = edited; post.footer; post.footerStocks = document.createElement("DIV"); post.footerStocks.className = "footer-actions"; post.footerStocks.style.display = "none"; post.footerStocks.style.display = "float:left"; post.footer_news = document.createElement("DIV"); post.footer_news.className = "footer-actions"; post.footer_news.style.display = "none"; post.footer_news.style.display = "float:left"; post.footer_cloud = document.createElement("DIV"); post.footer_cloud.className = "footer-actions"; post.footer_cloud.style.display = "none"; post.footer_cloud.style.display = "float:left"; var onEditPostCallback; post.onDeletePostCallback; var onHidePostCallback; post.postInfoProfileInfoContainer; post.postInfoTable; post.miniProfileContainer; post.timeoutNum; post.isWordATag = function (word) { if (word.charAt(0) === "#") { return word.substr(1); } else { return false; } }; post.createBodyText = function () { var container = document.createElement('DIV'); container.className = "no_translate"; container.onclick = function( event ) { helper.interpretTextClicked( event ); } post.bodyText.appendChild(container); var parsed_text = helper.getParsedHTML(post.text); if ( mentions && mentions.length > 0 ) { parsed_text = helper.parseMentions( parsed_text, mentions ); } container.innerHTML = parsed_text; setTimeout( function(){ if (post.bodyText.offsetHeight < container.offsetHeight) { post.readmore = document.createElement('DIV'); post.readmore.className = "readmore"; post.readmore.textContent = "Mehr anzeigen..."; post.readmore.onclick = function () { if (post.bodyText.style.maxHeight != "100%") { post.bodyText.style.maxHeight = "100%"; post.readmore.textContent = "Weniger anzeigen..."; } else { post.bodyText.style.maxHeight = "75px"; post.readmore.textContent = "Mehr anzeigen..."; } } post.body.insertBefore(post.readmore, post.body.lastElementChild); if ( post.show_full_content ) { post.bodyText.style.maxHeight = "100%"; post.readmore.textContent = "Weniger anzeigen..."; } } else { post.readmore = null; } }, 200 ) }; post.stopGettingMiniProfile = function () { clearTimeout(post.timeoutNum); post.timeoutNum = undefined; }; post.getMiniProfile = function () { if (!post.timeoutNum && currentUser.id != null ) { post.timeoutNum = setTimeout(function () { socketGateway.emit("getMiniProfile", {"userid": posterid}, function (args) { if (post.miniProfileContainer && post.miniProfileContainer.parentNode === post.postInfoProfileInfoContainer) { post.postInfoProfileInfoContainer.removeChild(post.miniProfileContainer); } post.postInfoProfileInfoContainer.insertBefore(post.createMiniUserProfile(args), post.postInfoTable); post.timeoutNum = undefined; }); }, 800); } }; post.createTitle = function (actionText) { post.title = document.createElement("DIV"); post.title.className = "infostream-post-title"; post.postInfoProfileInfoContainer = document.createElement("DIV"); post.postInfoTable = document.createElement("TABLE"); var tr1 = document.createElement("TR"); tr1.className = "poster-profile-link"; var th1 = document.createElement("TH"); th1.rowSpan = 2; var picture = document.createElement("IMG"); picture.className = "profile-picture"; picture.src = projectDomain + picturePath; picture.height = 30; picture.onmouseover = function () { post.getMiniProfile(); picture.onmouseleave = function () { post.stopGettingMiniProfile(); picture.onmouseleave = null; }; }; th1.appendChild(picture); var th2 = document.createElement("TH"); th2.align = "left"; //var name = post.isOwnPost() ? "You" : posterName; var name = posterName; var nameNode = document.createElement("DIV"); nameNode.onmouseover = function () { post.getMiniProfile(); nameNode.onmouseleave = function () { post.stopGettingMiniProfile(); nameNode.onmouseleave = null; } }; nameNode.appendChild(document.createTextNode(name)); nameNode.className = "infostream-post-title name"; th2.appendChild( nameNode ); var actionNode = document.createElement("span"); actionNode.style.color = "#6D6E70"; actionNode.style.fontWeight = "normal"; nameNode.appendChild(actionNode); var tr2 = document.createElement("TR"); var th3 = document.createElement("TH"); th3.className = "infostream-post-title action-time"; var action = edited ? actionText[0] : actionText[1]; if ( args.type == 'live' ) { th3.appendChild(document.createTextNode('Live content - NOW -')); } else { actionNode.appendChild(document.createTextNode(action + post.createTimestampPresentation())); } if (args.groupName) { var groupLink = document.createElement("SPAN"); groupLink.className = "tag inline"; groupLink.textContent = args.groupName; groupLink.onclick = function () { currentHome.group(args.groupid) }; actionNode.appendChild(document.createTextNode(" in der Gruppe")); th3.appendChild(groupLink); //th3.appendChild(document.createTextNode(" ")); } tr1.onclick = function () { if (post.miniProfileContainer && post.miniProfileContainer.parentNode === post.title) { post.title.removeChild(post.miniProfileContainer); } post.stopGettingMiniProfile(); socketGateway.emit("getProfile", { "userid": posterid }); }; tr1.appendChild(th1); tr1.appendChild(th2); tr2.appendChild(th3); post.postInfoTable.appendChild(tr1); post.postInfoTable.appendChild(tr2); post.postInfoProfileInfoContainer.appendChild(post.postInfoTable); post.title.appendChild(post.postInfoProfileInfoContainer); post.element.appendChild(post.title); post.createMenu(); }; post.onDeletePost = function (callback) { post.onDeletePostCallback = callback; }; post.onHidePost = function (callback) { onHidePostCallback = callback; }; post.createRemoveButton = function () { var removeButton = document.createElement("BUTTON"); removeButton.className = "infostream-removeButton"; if (post.isOwnPost()) { removeButton.textContent = "Delete"; removeButton.className = "infostream-removeButton"; removeButton.onclick = function () { alertManager.ask("Beitrag löschen?", function () { socketGateway.emit("deletePost", { "postid": id, "groupid": groupid }, function (replyArgs) { post.onDeletePostCallback(replyArgs); }); }); }; } else { removeButton.textContent = "Hide"; removeButton.className = "infostream-removeButton"; removeButton.onclick = function () { alertManager.ask("Beitrag verstecken?", function () { socketGateway.emit("hidePost", { "postid": id, "groupid": groupid, "tags": tags }, function (replyArgs) { onHidePostCallback(replyArgs); }); }); }; } if (post.isUserLoggedIn()) { post.menu.appendChild(removeButton); } }; post.onEditPost = function (callback) { onEditPostCallback = callback; }; post.createEditButton = function () { var editButton = document.createElement("BUTTON"); editButton.textContent = "Edit"; editButton.className = "infostream-editButton"; editButton.onclick = function () { var editor = document.createElement("DIV"), i, attachmentsLength = attachments.length; post.element.appendChild(editor); var postEditor = new PostEditor(editor); postEditor.init(); postEditor.textField.value = text; postEditor.resizeTextField(); for (i = 0; i < attachmentsLength; i++) { var attachment = attachments[i]; var name = attachment.name; var path = attachment.path; var type = attachment.type; postEditor.attachmentManager.addFile(name, path, type); } postEditor.onPost(function (args) { post.editPost(args); }); }; post.menu.appendChild(editButton); }; post.createAdminRemoveButton = function () { if (post.isUserLoggedIn() && currentUser.admin) { var adminRemoveButton = document.createElement("BUTTON"); adminRemoveButton.className = "infostream-removeButton"; adminRemoveButton.textContent = "!Delete as Admin!"; adminRemoveButton.className = "infostream-removeButton admin"; adminRemoveButton.onclick = function () { alertManager.ask("Beitrag eines anderen Nutzers löschen?", function () { socketGateway.emit("adminDeletePost", { "postid": id, "groupid": groupid }, function (replyArgs) { post.onDeletePostCallback(replyArgs); }); }); }; post.menu.appendChild(adminRemoveButton); } }; post.createReplyWithMentionButton = function () { if ( post.isUserLoggedIn() ) { var link_input = document.createElement("input"); link_input.className = 'hidden-input'; link_input.value = 'https://desk.traderfox.com/traderchat/post/' + ( nice_title != null ? nice_title : id ); var externalLinkButton = document.createElement("BUTTON"); externalLinkButton.textContent = "Dieses Posting als Link verfügbar machen"; externalLinkButton.className = "infostream-removeButton"; externalLinkButton.onclick = function ( event ) { link_input.select(); document.execCommand("Copy"); // var position = helper.getOffset(event.target); currentHome.showUserFeedback( 'Der Link wurde in die Zwischenablage kopiert.', event.clientX - 100, event.clientY - 35 ) }; post.menu.appendChild(externalLinkButton); post.menu.appendChild(link_input); var id_input = document.createElement("input"); id_input.className = 'hidden-input'; id_input.value = ' [[post|' + id + ']] '; var mentionReplyButton = document.createElement("BUTTON"); mentionReplyButton.textContent = "Posting-ID in Zwischenablage kopieren"; mentionReplyButton.className = "infostream-removeButton"; mentionReplyButton.onclick = function (event) { id_input.select(); document.execCommand("Copy"); //var position = helper.getOffset(event.target); currentHome.showUserFeedback( 'Der Posting-ID wurde in die Zwischenablage kopiert.',event.clientX - 100, event.clientY - 35 ) }; post.menu.appendChild(mentionReplyButton); post.menu.appendChild(id_input); } }; post.removeMiniUserProfile = function () { post.postInfoProfileInfoContainer.onmouseleave = null; post.postInfoProfileInfoContainer.removeChild(post.miniProfileContainer); }; post.createMiniUserProfile = function (args) { var isFollowed = args.isFollowed; var isOwnProfile = args.profileid === args.readerid; var isBlocked = args.isBlocked; post.miniProfileContainer = document.createElement("DIV"); post.miniProfileContainer.className = "mini-profile-container"; var profileTable = document.createElement("TABLE"); profileTable.style.width = "100%"; var tr1 = document.createElement("TR"); var pictureCell = document.createElement("TD"); pictureCell.rowSpan = 2; pictureCell.style.width = "75px"; var picture = document.createElement("IMG"); picture.src = projectDomain + args.profilePicture; picture.height = 75; picture.width = 75; pictureCell.appendChild(picture); var nameCell = document.createElement("TD"); nameCell.className = "name"; nameCell.textContent = args.username; var followCell = document.createElement("TD"); followCell.style.textAlign = "right"; var followButton = document.createElement("BUTTON"); followButton.textContent = isFollowed ? "Entfolgen" : "Folgen"; followButton.className = isFollowed ? "cancel unfollow" : "ok follow"; followButton.onclick = function () { if (isFollowed) { alertManager.ask("Nutzer entfolgen?", function () { socketGateway.emit("unfollowUser", { "id": posterid }, function () { followButton.textContent = "Folgen"; followButton.className = "ok follow"; isFollowed = false; }); }); } else { alertManager.ask("Nutzer folgen?", function () { socketGateway.emit("followUser", { "id": posterid }, function (data) { if (data.result) { followButton.textContent = "Entfolgen"; followButton.className = "cancel unfollow"; isFollowed = true; } else { alert(data.error) } }); }); } }; if (!isOwnProfile && !isBlocked) { followCell.appendChild(followButton); } tr1.appendChild(pictureCell); tr1.appendChild(nameCell); tr1.appendChild(nameCell); tr1.appendChild(followCell); var tr2 = document.createElement("TR"); var titleCell = document.createElement("TD"); titleCell.className = "description"; titleCell.textContent = args.title; var blockCell = document.createElement("TD"); blockCell.style.textAlign = "left"; var blockButton = document.createElement("BUTTON"); blockButton.textContent = isBlocked ? "Unblock" : "Block"; blockButton.className = isBlocked ? "ok" : "cancel"; if (!isOwnProfile) { blockCell.appendChild(blockButton); blockCell.onclick = function () { if (isBlocked) { alertManager.ask("Nutzer entblocken?", function () { socketGateway.emit("unblockOtherUser", { "id": posterid }, function () { blockButton.textContent = "Unblock"; blockButton.className = "ok"; isBlocked = false; }); }); } else { alertManager.ask("Nutzer blockieren?", function () { socketGateway.emit("blockOtherUser", { "id": posterid }, function () { blockButton.textContent = "Blockieren"; blockButton.className = "cancel"; isBlocked = true; if (isFollowed) { followCell.removeChild(followButton); followButton.textContent = "Folgen"; followButton.className = "ok"; isFollowed = false; } }); }); } }; } tr2.appendChild(titleCell); tr2.appendChild(blockCell); profileTable.appendChild(tr1); profileTable.appendChild(tr2); post.miniProfileContainer.appendChild(profileTable); post.postInfoProfileInfoContainer.onmouseleave = function () { post.removeMiniUserProfile(); }; return post.miniProfileContainer; }; post.createBody = function () { post.body = document.createElement("DIV"); post.body.className = "infostream-post-body"; post.bodyText = document.createElement("DIV"); post.bodyText.className = "infostream-post-bodyText"; post.body.appendChild(post.bodyText); post.element.appendChild(post.body); post.createBodyText(); }; post.createFooter = function () { post.footer = document.createElement("DIV"); post.footer.className = "infostream-post-footer"; post.element.appendChild(post.footer); if (stocks.length > 0) { post.footer.appendChild(post.footerStocks); post.createPostStocks(); } if (cloud.length > 0) { post.footer.appendChild(post.footer_cloud); post.createPostCloud(); } if (news.length > 0) { post.footer.appendChild(post.footer_news); post.createPostNews(); } }; post.createMenu = function () { if ( args.type == 'live' ) { return; } post.menuButton = document.createElement("DIV"); post.menuButton.className = "infostream-post-menuButton"; post.menuButton.addEventListener('click', function (event) { if (post.menu.style.display == "none") { post.menu.style.display = "block"; post.menuButton.className = "infostream-post-menuButton active"; } else { post.menu.style.display = "none"; post.menuButton.className = "infostream-post-menuButton"; } }); post.menu = document.createElement("DIV"); post.menu.className = "infostream-post-menu"; post.menu.style.display = "none"; if (post.isUserLoggedIn()) { post.element.appendChild(post.menuButton); post.element.appendChild(post.menu); post.menu.addEventListener('mouseleave', function () { post.menu.style.display = "none"; post.menuButton.className = "infostream-post-menuButton"; }); post.createReplyWithMentionButton(); post.createRemoveButton(); if (post.isOwnPost()) { post.createEditButton(); } post.createAdminRemoveButton(); } if ( currentView.type != "profile" && environment === "tradingdesk" ) { //we have a cloud icon in the profile, do not need more!. var cloudButton = document.createElement("DIV"); cloudButton.title = "Cloud von " + posterName + " öffnen."; cloudButton.className = "post-cloud-button"; cloudButton.onclick = function () { if(environment === "tradingdesk"){ if (currentHome.externalAction != null) { currentHome.externalAction.fn.call(currentHome.externalAction.context, { 'type' : 'cloud-view', user_id : posterid } ) } } else if(["mobile", "messenger"].indexOf(environment) != -1){ alert("Dieser Inhalt ist in der App nicht verfügbar. Nutzen Sie das Trading-Desk"); } }; post.element.appendChild(cloudButton); } if ( false && args.wikifolio ) { var wikiButton = document.createElement("DIV"); wikiButton.textContent = "WIKIFOLIOS"; wikiButton.style.background = "#95c11f"; wikiButton.style.color = "#fff"; wikiButton.style.borderRadius = "5px"; wikiButton.style.padding = "2px 4px"; wikiButton.style.cursor = "pointer"; wikiButton.style.fontWeight = "bold"; wikiButton.style.position = "absolute"; wikiButton.style.right = "75px"; wikiButton.style.top = "3px"; wikiButton.onclick = function () { socketGateway.emit("getProfile", { "userid": posterid, 'tab' : 'wikifolio' } ); }; post.element.appendChild(wikiButton); } }; post.editPost = function (args) { args["postid"] = id; args["groupid"] = groupid; args["group_name"] = group_name; socketGateway.emit("editPost", args, function (replyArgs) { onEditPostCallback(replyArgs); }); }; post.isOwnPost = function () { return readerid === posterid; }; post.isUserLoggedIn = function () { return readerid !== undefined; }; post.createTimestampPresentation = function () { var postDate = new Date(timestamp); var now = new Date(), dateRepresentation; var time = " um " + postDate.toLocaleTimeString('de'); if (now.getDate() === postDate.getDate()) { dateRepresentation = time; } else { dateRepresentation = " am " + postDate.toLocaleDateString('de') + time; } return dateRepresentation; }; post.getId = function () { return id; }; post.ValidURL = function (str) { var urlRegex = /((?:(http|https|Http|Https|rtsp|Rtsp):\/\/(?:(?:[a-zA-Z0-9\$\-\_\.\+\!\*\'\(\)\,\;\?\&\=]|(?:\%[a-fA-F0-9]{2})){1,64}(?:\:(?:[a-zA-Z0-9\$\-\_\.\+\!\*\'\(\)\,\;\?\&\=]|(?:\%[a-fA-F0-9]{2})){1,25})?\@)?)?((?:(?:[a-zA-Z0-9][a-zA-Z0-9\-]{0,64}\.)+(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnrwyz]|l[abcikrstuvy]|(?:mil|mobi|museum|m[acdghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eouw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agkmsyz]|v[aceginu]|w[fs]|y[etu]|z[amw]))|(?:(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))(?:\:\d{1,5})?)(\/(?:(?:[a-zA-Z0-9\;\/\?\:\@\&\=\#\~\-\.\+\!\*\'\(\)\,\_])|(?:\%[a-fA-F0-9]{2}))*)?(?:\b|$)/gi; ; return urlRegex.test(str); }; post.createPostStocks = function () { post.footerStocks.style.display = 'block'; post.footerStocks.innerHTML = ""; var stocksContainer = document.createElement("DIV"); stocksContainer.className = "tags-container main"; post.footerStocks.appendChild(stocksContainer); var stocksLabel = document.createElement("DIV"); stocksLabel.className = "tag label"; stocksLabel.textContent = "Aktien: "; var i, stock, stockElement, stocksLength = stocks.length; if (stocksLength > 0) { stocksContainer.appendChild(stocksLabel); } for (i = 0; i < stocksLength; i++) { socketGateway.emit("getStockInfoISINSource", { isin: stocks[i].isin, source: stocks[i].source }, function (response) { if (response.result) { stock = response.data.name; stockElement = document.createElement("DIV"); stockElement.className = "tag"; stockElement.textContent = stock; stocksContainer.appendChild(stockElement); stockElement.onclick = function ( event ) { if ( environment === "tradingdesk"){ if ( currentHome.stockAction != null) { currentHome.stockAction.fn.call(currentHome.stockAction.context, this.isin, this.source); } } else if( ["mobile", "messenger"].indexOf(environment) != -1){ window.open( 'https://desk.traderfox.com:88/stock/' + data.id, '_blank' ); //window.location.pathname = '/charttool/isin-' + this.isin //alert("Dieser Inhalt ist in der App nicht verfügbar. Nutzen Sie das Trading-Desk"); } event.preventDefault(); }.bind({isin: this.isin, source: this.source}) } }.bind({isin: stocks[i].isin, source: stocks[i].source})); } }; post.setStocks = function( stocks_data ) { stocks = stocks_data }; post.setNews = function( news_data ) { news = news_data; }; post.setCloud = function( cloud_data ) { cloud = cloud_data; }; post.createPostNews = function () { post.footer_news.style.display = 'block'; post.footer_news.innerHTML = ""; var news_container = document.createElement("DIV"); news_container.className = "tags-container main"; post.footerStocks.appendChild(news_container); var news_label = document.createElement("DIV"); news_label.className = "tag label"; news_label.textContent = "Related News: "; var i, news_element, l = news.length; if (l > 0) { news_container.appendChild(news_label); post.footer_news.appendChild(news_container); } for (i = 0; i < l; i++) { news_element = document.createElement("DIV"); news_element.className = "tag"; news_element.textContent = news[i].title; news_element.onclick = function (event) { if(environment === "tradingdesk"){ if (currentHome.externalAction != null) { currentHome.externalAction.fn.call(currentHome.externalAction.context, { 'type' : 'news', id : this.id, source : this.source } ) } } else if(["mobile", "messenger"].indexOf(environment) != -1){ alert("Dieser Inhalt ist in der App nicht verfügbar. Nutzen Sie das Trading-Desk"); } event.preventDefault(); }.bind({id: news[i].id, source: news[i].source}) news_container.appendChild(news_element); } }; post.createPostCloud = function () { post.footer_cloud.style.display = 'block'; post.footer_cloud.innerHTML = ""; var cloud_container = document.createElement("DIV"); cloud_container.className = "tags-container main cloud"; post.footer_cloud.appendChild(cloud_container); var cloud_label = document.createElement("DIV"); cloud_label.className = "tag label"; cloud_label.textContent = ""; var i, cloud_element, cloud_icon, cloud_title, l = cloud.length; if (l > 0) { cloud_container.appendChild(cloud_label); post.footer_cloud.appendChild(cloud_container); } for (i = 0; i < l; i++) { cloud_icon = document.createElement("DIV"); cloud_icon.className = "icon"; cloud_icon.innerHTML = "" ; //height:100% cloud_title = document.createElement("DIV"); cloud_title.className = "title"; cloud_title.textContent = cloud[i].title; cloud_element = document.createElement("DIV"); cloud_element.className = "tag cloud"; cloud_element.onclick = function (event) { if(environment === "tradingdesk"){ if (currentHome.externalAction != null) { currentHome.externalAction.fn.call(currentHome.externalAction.context, { 'type' : 'cloud', id : this.id } ) } } else if(["mobile", "messenger"].indexOf(environment) != -1){ //alert("Dieser Inhalt ist in der App nicht verfügbar. Nutzen Sie das Trading-Desk"); new PictureViewer(rootElement, { "path": this.icon }); } event.preventDefault(); }.bind({id: cloud[i].id, icon: cloud[i].icon }) cloud_element.appendChild( cloud_icon ) cloud_element.appendChild( cloud_title ) cloud_container.appendChild(cloud_element); } }; return post; } /* A child of Post. These are the replies under MainPost. Has no attachments but can be edited or deleted. */ function Reply(args, element, reply_input_element) { var reply = new Post(args); reply.element = element || document.createElement("DIV"); var closeCallback; var adminCloseCallback; var hideCallback; var editCallback; var postInfoProfileInfoContainer; var isWordATag = function (word) { if (word.charAt(0) === "#") { return word.substr(1); } else { return false; } }; reply.createRemoveButton = function () { var removeButton = document.createElement("BUTTON"); removeButton.className = "infostream-removeButton"; if (reply.isOwnPost()) { removeButton.textContent = "Delete"; removeButton.className = "infostream-removeButton"; removeButton.onclick = function () { alertManager.ask("Antwort löschen?", function () { closeCallback({ "replyid": args.postid, "readerid": args.readerid }); }); } } else { removeButton.textContent = "Hide"; removeButton.className = "infostream-removeButton"; removeButton.onclick = function () { alertManager.ask("Antwort verstecken?", function () { hideCallback({ "replyid": args.postid, "readerid": args.readerid }); }); } } if (reply.isUserLoggedIn()) { reply.menu.appendChild(removeButton); } }; reply.createAdminRemoveButton = function () { if (reply.isUserLoggedIn() && currentUser.admin) { var adminRemoveButton = document.createElement("BUTTON"); adminRemoveButton.className = "infostream-removeButton"; adminRemoveButton.textContent = "!Delete as Admin!"; adminRemoveButton.className = "infostream-removeButton admin"; adminRemoveButton.onclick = function () { alertManager.ask("Antwort eines anderen Nutzers löschen?", function () { adminCloseCallback({ "replyid": args.postid, "readerid": args.readerid }); }); }; reply.menu.appendChild(adminRemoveButton); } }; reply.createEditButton = function () { var editButton = document.createElement("BUTTON"); editButton.textContent = "Edit"; editButton.className = "infostream-editButton"; editButton.onclick = function () { var editor = document.createElement("DIV"), i; reply.element.innerHTML = ""; reply.element.appendChild(editor); var replyEditor = new ReplyEditor(editor); replyEditor.init(); replyEditor.textField.value = args.text; replyEditor.onReply(reply.editReply.bind(reply)); replyEditor.resizeTextField(); }; reply.menu.appendChild(editButton); }; reply.onClose = function (callback) { closeCallback = callback; }; reply.onCloseAdmin = function (callback) { adminCloseCallback = callback; }; reply.onHide = function (callback) { hideCallback = callback; }; reply.onEdit = function (callback) { editCallback = callback; }; reply.editReply = function (text) { editCallback({ "id": args.postid, "text": text, "timestamp": args.timestamp }); }; reply.createElement = function () { reply.element.className = "infostream-reply"; reply.createTitle(); reply.createBody(); reply.createMenu(); reply.createFooter([" Bearbeitet ", " Geantwortet "]); }; reply.createBody = function () { reply.body = document.createElement("DIV"); reply.body.className = "infostream-post-body reply"; reply.bodyText = document.createElement("DIV"); reply.bodyText.className = "infostream-post-bodyText reply"; reply.body.appendChild(reply.title); //CARLOS reply.body.appendChild(reply.bodyText); reply.element.appendChild(reply.body); reply.createBodyText(); }; reply.createBodyText = function () { postInfoProfileInfoContainer = document.createElement("DIV"); var nameNode = document.createElement("SPAN"); nameNode.appendChild(document.createTextNode(reply.posterName)); nameNode.className = "infostream-post-title name reply"; nameNode.onmouseover = function () { reply.getMiniProfile(); nameNode.onmouseleave = function () { reply.stopGettingMiniProfile(); nameNode.onmouseleave = null; }; }; nameNode.onclick = function () { socketGateway.emit("getProfile", { "userid": reply.posterid }); }; var container = document.createElement('DIV'); container.className = "no_translate"; container.onclick = function( event ) { helper.interpretTextClicked( event ); } container.appendChild(nameNode); container.appendChild(postInfoProfileInfoContainer); reply.bodyText.appendChild(container); var node = document.createElement('DIV'); node.innerHTML = helper.getParsedHTML( reply.text ); container.appendChild( node ); reply.readmore = null; }; reply.createTitle = function () { reply.title = document.createElement("DIV"); reply.title.className = "infostream-post-title reply"; reply.postInfoTable = document.createElement("TABLE"); reply.postInfoProfileInfoContainer = document.createElement("DIV"); var tr1 = document.createElement("TR"); tr1.className = "poster-profile-link"; var th1 = document.createElement("TH"); th1.rowSpan = 2; var th2 = document.createElement("TH"); th2.align = "left"; var tr2 = document.createElement("TR"); // var th3 = document.createElement("TH"); var picture = document.createElement("IMG"); picture.className = "profile-picture reply"; picture.src = projectDomain + reply.picturePath; var nameNode = document.createElement("DIV"); nameNode.appendChild(document.createTextNode(reply.posterName)); nameNode.className = "infostream-post-title name reply"; tr1.onclick = function () { socketGateway.emit("getProfile", { "userid": reply.posterid }); }; // var action = reply.edited ? actionText[0] : actionText[1]; th1.appendChild(picture); // th2.appendChild(nameNode); // th3.appendChild(document.createTextNode(action + reply.createTimestampPresentation())); tr1.appendChild(th1); tr1.appendChild(th2); // tr2.appendChild(th3); reply.postInfoTable.appendChild(tr1); // table.appendChild(tr2); // reply.title.appendChild(table); reply.postInfoProfileInfoContainer.appendChild(reply.postInfoTable); reply.title.appendChild(reply.postInfoProfileInfoContainer); //reply.element.appendChild(reply.title); //CARLOS }; reply.createFooter = function (actionText) { reply.footer = document.createElement("DIV"); reply.footer.className = "infostream-post-footer reply"; reply.element.appendChild(reply.footer); var action = reply.edited ? actionText[0] : actionText[1]; var action_node = document.createElement("DIV"); action_node.className = "infostream-post-footer reply action-time"; action_node.appendChild(document.createTextNode(action + reply.createTimestampPresentation())); reply.footer.appendChild(action_node); var reply_mention_button = document.createElement("DIV"); reply_mention_button.textContent = 'Darauf antworten'; reply_mention_button.className = "infostream-post-footer reply action-time"; reply_mention_button.style.marginLeft = '10px'; reply_mention_button.style.cursor = 'pointer'; reply_mention_button.style.clear = 'initial'; reply_mention_button.style.textDecoration = 'underline'; reply_mention_button.onclick = function( event ) { if ( reply_input_element != undefined ) { var addon = '@' + reply.posterName + ' [[comment|' + args.postid + ']] '; reply_input_element.value = reply_input_element.value + addon; reply_input_element.focus(); } event.stopPropagation(); event.preventDefault(); } reply.footer.appendChild(reply_mention_button); }; reply.createMenu = function () { reply.menuButton = document.createElement("DIV"); reply.menuButton.className = "infostream-post-menuButton reply"; reply.menuButton.addEventListener('click', function (event) { if (reply.menu.style.display == "none") { reply.menu.style.display = "block"; reply.menuButton.className = "infostream-post-menuButton reply active"; } else { reply.menu.style.display = "none"; reply.menuButton.className = "infostream-post-menuButton reply"; } }) reply.menu = document.createElement("DIV"); reply.menu.className = "infostream-post-menu reply"; reply.menu.style.display = "none"; if (reply.isUserLoggedIn()) { reply.element.appendChild(reply.menuButton); reply.element.appendChild(reply.menu); reply.menu.addEventListener('mouseleave', function () { reply.menu.style.display = "none"; reply.menuButton.className = "infostream-post-menuButton reply"; }); reply.createReplyWithMentionButton(); reply.createRemoveButton(); if (reply.isOwnPost()) { reply.createEditButton(); } reply.createAdminRemoveButton(); } }; reply.createReplyWithMentionButton = function () { if ( reply.isUserLoggedIn() ) { var id_input = document.createElement("input"); id_input.style.border = 'none'; id_input.style.background = 'transparent'; id_input.style.height = '0px'; id_input.style.padding = '0px'; id_input.style.width = '50px'; id_input.style.float = 'left'; id_input.value = ' [[comment|' + args.postid + ']] '; var mentionReplyButton = document.createElement("BUTTON"); mentionReplyButton.textContent = "Kommentar-ID in Zwischenablage kopieren"; mentionReplyButton.className = "infostream-removeButton"; mentionReplyButton.onclick = function ( event ) { id_input.select(); document.execCommand("Copy"); //var position = helper.getOffset(event.target); currentHome.showUserFeedback( 'Der Kommentar-ID wurde in die Zwischenablage kopiert.', event.clientX - 100, event.clientY - 35 ) }; reply.menu.appendChild(mentionReplyButton); reply.menu.appendChild(id_input); } }; reply.getMiniProfile = function () { if (!reply.timeoutNum && currentUser.id != null) { reply.timeoutNum = setTimeout(function () { socketGateway.emit("getMiniProfile", {"userid": reply.posterid}, function (args) { if (reply.miniProfileContainer && reply.miniProfileContainer.parentNode === reply.postInfoProfileInfoContainer) { reply.postInfoProfileInfoContainer.removeChild(reply.miniProfileContainer); } reply.postInfoProfileInfoContainer.insertBefore(reply.createMiniUserProfile(args), reply.postInfoTable); reply.timeoutNum = undefined; }); }, 800); } }; return reply; } /* A child of Post. Depending on its type variable it takes a different css-class and decides if it has a header or footer. */ function RoomPost(args, text) { var highlight_text = text != undefined ? text.toLowerCase().replace(/ /g,'') : null; var post = new Post(args); var post_id = parseInt(args.id); var room_id = parseInt(args.roomid); post.element = document.createElement("DIV"); post.createElement = function () { post.element.className = "infostream-post room " + args.type; if(args.posterid === currentUser.id){ post.element.className += " mine"; } if( args.type === "first" || args.type === "firstLast" || args.show_date ){ post.createTitle(); } post.createBody(); if( true || args.type === "last" || args.type === "firstLast" || args.show_date ){ post.createFooter(); } }; post.removeFooter = function () { post.element.removeChild(post.footer); }; post.createTitle = function () { post.title = document.createElement("DIV"); post.title.className = "infostream-post-title room"; post.postInfoTable = document.createElement("TABLE"); post.postInfoProfileInfoContainer = document.createElement("DIV"); var tr1 = document.createElement("TR"); tr1.className = "poster-profile-link room"; var th1 = document.createElement("TH"); th1.rowSpan = 2; var th2 = document.createElement("TH"); th2.align = "left"; var th3 = document.createElement("TH"); th3.align = "left"; var picture = document.createElement("IMG"); picture.className = "profile-picture room"; picture.src = projectDomain + post.picturePath; var nameNode = document.createElement("DIV"); nameNode.appendChild(document.createTextNode(post.posterName)); nameNode.className = "infostream-post-title name room"; tr1.onclick = function () { socketGateway.emit("getProfile", { "userid": post.posterid }); }; th1.appendChild(picture); tr1.appendChild(th1); if(args.posterid != currentUser.id){ th2.appendChild(nameNode); tr1.appendChild(th2); tr1.appendChild(th3); } post.postInfoTable.appendChild(tr1); post.title.appendChild(post.postInfoTable); post.postInfoProfileInfoContainer.appendChild(post.postInfoTable); post.title.appendChild(post.postInfoProfileInfoContainer); //th3.appendChild(document.createTextNode(post.createTimestampPresentation())); post.element.appendChild(post.title); }; post.createFooter = function () { post.footer = document.createElement("DIV"); post.footer.className = "infostream-post-footer room"; var th3 = document.createElement("DIV"); th3.style.paddingLeft = "10px"; th3.style.paddingTop = "4px"; th3.style.fontSize = "10px"; th3.style.fontStyle = "italic"; th3.appendChild(document.createTextNode(post.createTimestampPresentation())); post.footer.appendChild(th3); if ( currentUser.admin ) { var delete_icon = document.createElement("SPAN"); delete_icon.title = "Delete user message as Admin"; delete_icon.className = "fa fa-trash"; delete_icon.style.cursor = "pointer"; delete_icon.style.marginLeft = "10px"; delete_icon.addEventListener("click", function(e){ alertManager.ask("Admin, are you sure you want to remove this message?", function () { socketGateway.emit("adminDeleteRoomPost", { "postid": post_id, "roomid" : room_id }, function(response) { if ( response.result ) { post.element.style.display = "none"; } }); }); e.stopPropagation(); e.preventDefault(); }) th3.appendChild( delete_icon ); } post.element.appendChild(post.footer); }; post.createBodyText = function () { var text_lines = post.text.split('\n'); var node, linkText, line, words, i, l = text_lines.length; var container = document.createElement('DIV'); container.className = "no_translate"; for (i = 0; i < l; i++) { //line breakers line = text_lines[i]; words = line.split(" "); var j, k = words.length; for (j = 0; j < k; j++) { if ( node && node.nodeType != 3 && ["ordermask"].indexOf(node.data) == -1 ) { //BR skippers container.appendChild(document.createElement("BR")); } var tag = this.isWordATag(words[j]); // if ( ( /[a-zA-Z]*\.[a-zA-Z]*/ ).test(words[j])) { //it is a link if ( helper.isStock(words[j])) { //it is a stock node = document.createElement('a'); helper.getStockName(words[j], function( response ) { if ( response.result ) { var data = response.data; this.node.appendChild( document.createTextNode( data.name )); this.node.className = "infostream-post-link"; this.node.onclick = function( event ){ currentHome.informExternalStock( { source : data.source, isin : data.isin } ) }.bind( data ) } }.bind( { node : node } )); } else if ( helper.isOrder(words[j])) { //it is a stock node = document.createElement('a'); helper.getStockByWKNorISIN(words[j].replace("order:", ""), function( response ) { if ( response.result ) { var data = response.data; this.node.appendChild( document.createTextNode( " Ordermaske WKN " + data.wkn + " " )); this.node.className = "infostream-post-ordermask"; this.node.onclick = function( event ){ currentHome.informExternal( { type : "order", stock_id : this.id } ) }.bind( data ) } }.bind( { node : node } )); node.data = "ordermask" } else if ( ( (words[j].toLowerCase() == "wkn" || words[j].toLowerCase() == "(wkn") ) && words[j+1] && ( words[j+1].length == 6 || words[j+1].replace(")", "").length == 6 || words[j+1].replace(",", "").length == 6 || words[j+1].replace(".", "").length == 6 ) ) { //it is a wkn, make an order link node = document.createElement('a'); var wkn = words[j+1].replace(")", ""); wkn = wkn.replace(",", ""); wkn = wkn.replace(".", ""); helper.getStockByWKNorISIN(wkn, function( response ) { this.node.appendChild( document.createTextNode( this.word1 + " " + this.word2) ); if ( response.result ) { this.node.className = "infostream-post-ordermask"; //this.node.data = "ordermask"; this.node.title = "Open ordermask"; if ( environment == "mobile" ) { this.node.href = window.location.protocol + "//" + window.location.host + "/comdirect/wkn-" + wkn; } else if ( environment == "messenger" ) { this.node.href = "https://mobile.traderfox.com/comdirect/wkn-" + wkn; this.node.target = "_blank"; } this.node.onclick = function( event ){ currentHome.informExternal( { type : "order", stock_id : this.id } ) }.bind( response.data ) } }.bind( { node : node, word1 : words[j], word2 : words[j+1] } )); node.data = "ordermask"; j++; } else if ( helper.isImage(words[j])) { //it is an image node = document.createElement('IMG'); node.title = words[j]; node.src = words[j]; node.style.cursor = "pointer"; node.onclick = function( event ) { if( environment === "tradingdesk"){ if (currentHome.externalAction != null) { currentHome.externalAction.fn.call(currentHome.externalAction.context, { 'type' : 'open-image', 'link' : this } ) } } else if(["mobile", "messenger"].indexOf(environment) != -1){ new PictureViewer(rootElement, { "path": this }); } event.preventDefault(); event.stopPropagation(); }.bind( words[j] ) } else if ( helper.isCloudLink(words[j])) { //it is an news var cloud = helper.getCloudParts(words[j]); node = document.createElement('a'); linkText = document.createTextNode("Öffnen auf dem Trading-Desk..."); node.appendChild(linkText); node.className = "infostream-post-link"; node.onclick = function( event ){ currentHome.informExternal( { 'type' : 'cloud', id : this[1] } ); }.bind( cloud ) } else if ( helper.isReplyInteralLink(words[j]) ) { node = document.createElement("a"); node.className = "infostream-post-link"; node.onclick = function () { currentHome.reply(this.replyid); }.bind({"replyid": helper.getReplyIdFromInteralLink(words[j])}); linkText = document.createTextNode(words[j]); node.appendChild(linkText); } else if ( helper.isPostInteralLink(words[j]) ) { node = document.createElement("a"); node.className = "infostream-post-link"; node.onclick = function () { currentHome.post(this.postid); }.bind({"postid": helper.getPostIdFromInteralLink(words[j])}); linkText = document.createTextNode(words[j]); node.appendChild(linkText); } else if ( helper.isNewsLink(words[j])) { //it is an news var news = helper.getNewsParts(words[j]); node = document.createElement('a'); linkText = document.createTextNode("mehr lesen..."); node.appendChild(linkText); node.className = "infostream-post-link"; node.onclick = function( event ){ currentHome.informExternal( { 'type' : 'news', id : this[1], source : this[2] } ); }.bind( news ) } else if (post.ValidURL(words[j])) { //it is a link node = document.createElement('a'); linkText = document.createTextNode(words[j]); node.appendChild(linkText); node.title = words[j]; node.className = "infostream-post-link"; node.href = words[j].indexOf('http') == -1 ? '//' + words[j] : words[j]; node.target = "_blank"; } else if (tag) { //it is a tag node = document.createElement("SPAN"); node.onclick = function () { currentHome.tag(this.boundTag); }.bind({"boundTag": tag}); node.className = "tag inline"; linkText = document.createTextNode(words[j]); node.appendChild(linkText); } else { //normal text if ( words[j].indexOf(""") != -1 ) { words[j] = helper.replaceAll( words[j], """, '"' ) } if ( words[j].indexOf(">") != -1 ) { words[j] = helper.replaceAll( words[j], ">", '>' ) } if ( words[j].indexOf("<") != -1 ) { words[j] = helper.replaceAll( words[j], "<", '<' ) } if ( words[j].indexOf("&") != -1 ) { words[j] = helper.replaceAll( words[j], "&", "&" ) } node = document.createTextNode( words[j]); } if ( highlight_text && words[j].toLowerCase().indexOf( highlight_text ) != -1 ) { container.style.border = "1px solid yellow"; container.style.borderRadius = "4px"; container.style.padding = "4px"; container.className = container.className + " scrollTo"; } container.appendChild(node); if (j != k - 1) { container.appendChild(document.createTextNode(" ")); } } if (i != l - 1) { container.appendChild(document.createElement("BR")); } } post.bodyText.appendChild(container); if (post.bodyText.offsetHeight < container.offsetHeight) { post.readmore = document.createElement('DIV'); post.readmore.className = "readmore"; post.readmore.textContent = "Mehr anzeigen..."; post.readmore.onclick = function () { if (post.bodyText.style.maxHeight != "100%") { post.bodyText.style.maxHeight = "100%"; post.readmore.textContent = "Weniger anzeigen..."; } else { post.bodyText.style.maxHeight = "75px"; post.readmore.textContent = "Mehr anzeigen..."; } } //post.body.appendChild(post.readmore); post.body.insertBefore(post.readmore, post.body.lastElementChild); } else { post.readmore = null; } }; post.createTimestampPresentation = function () { var postDate = new Date(args.timestamp); var now = new Date(), dateRepresentation; var time = postDate.toLocaleTimeString('de'); var timeSplit = time.split(":"); var timeWithoutSeconds = timeSplit[0] + ":" + timeSplit[1]; if (now.getDate() === postDate.getDate()) { dateRepresentation = timeWithoutSeconds; } else { dateRepresentation = postDate.toLocaleDateString('de') + " - " + timeWithoutSeconds; } return dateRepresentation; }; post.getId= function () { return args.id; }; return post; } /* Child of PostEditor. Supports attachments, mentions and stocks. */ function MainPostEditor(id, element, editing, stocks, news, cloud, group_id, has_live_button, with_title) { currentHome.autoPostEditor = null; var mainPostEditor = new PostEditor(element); mainPostEditor.upperMenu.className = "post-editor-upper-menu main"; var typing_hashtag = false; var search_hashtag = ''; var hashtag_result_div = document.createElement('DIV'); var preview; var tagsContainer; var stocksContainer; var news_container; var cloud_container; var postButton; var live_post_button; var is_live_posting = false; var group_id = group_id || null; var with_title = with_title || false; var title_key_down_timeout = null; var title_key_down_counter = 0; var text_key_down_timeout = null; var text_key_down_counter = 0; mainPostEditor.attachmentManager; mainPostEditor.element = element; mainPostEditor.titleField; var currentUrls = []; var currentUrl = ""; var timeoutNo; var searchTerm; var search; var onPostcallback; var supportedFileTypes = ".jpg,.gif,.png,.jpeg,.zip,.pdf"; var isStringURL = function (word) { return !word.indexOf(".", word.length - ".".length) !== -1 && re_weburl.test(word); }; var removeTags = function () { if (tagsContainer) { mainPostEditor.element.removeChild(tagsContainer); tagsContainer = undefined; } }; var removeStocks = function () { if (stocksContainer) { mainPostEditor.element.removeChild(stocksContainer); stocksContainer = undefined; } }; var removeNews = function () { if (news_container) { mainPostEditor.element.removeChild(news_container); news_container = undefined; } }; var removeCloud = function () { if (cloud_container) { mainPostEditor.element.removeChild(cloud_container); cloud_container = undefined; } }; var deactivateSearch = function () { if (search) { search.clearResults(); search = undefined; mainPostEditor.textField.onclick = undefined; } }; var activateSearch = function () { searchTerm = "@"; search = new SearchField(); mainPostEditor.textField.onclick = function () { search.clearResults(); }; }; var isCharLetter = function (char) { var regex = /^\w|[ÀÈÌÒÙàèìòùÁÉÍÓÚÝáéíóúýÂÊÎÔÛâêîôûÃÑÕãñõÄËÏÖÜäëïöüçÇßØøÅåÆæÞþÐð]$/; var result = char.match(regex); return result && result[0] === result.input; }; var searchForUsersToMention = function (event) { var pressedKey = event.key; var text = mainPostEditor.textField.value; if (search && (pressedKey === "#" || pressedKey === "@")) { deactivateSearch(); } if (search && (isCharLetter(pressedKey) || pressedKey === "Backspace")) { var results; if (pressedKey === "Backspace") { searchTerm = searchTerm.slice(0, -1); } else { searchTerm += pressedKey; } if (searchTerm === "") { deactivateSearch(); } else if (searchTerm === "@") { search.clearResults(); } else { socketGateway.emit("searchUsers", searchTerm.slice(1), function (args) { var originalText = args["originalText"]; results = search.createAndAttachResults({ "originalText": args.originalText, "users": args.users, "groups": [] }, mainPostEditor.element, function (args) { var lastTagIndex = text.lastIndexOf("@") + 1; var textBeforeCurrentTag = text.slice(0, lastTagIndex); var textRest = text.slice(lastTagIndex); var newTextRest = textRest.replace(textRest, args.name); mainPostEditor.mentionedUsers.push({"id": args.id, "name": args.name}); mainPostEditor.textField.value = textBeforeCurrentTag + newTextRest; mainPostEditor.textField.focus(); deactivateSearch(); }); }); } } if (pressedKey === "@") { activateSearch(); } }; mainPostEditor.createInputField = function () { mainPostEditor.textField = document.createElement("TEXTAREA"); mainPostEditor.textField.className = "infostream-textfield"; mainPostEditor.textField.addEventListener('keydown', function (event) { searchForUsersToMention(event); mainPostEditor.resizeTextField(); if ( is_live_posting ) { this.updatePostText(); } }.bind( this )); mainPostEditor.textField.addEventListener('paste', function (event) { if ( is_live_posting ) { this.updatePostText(); } mainPostEditor.resizeTextField(); }.bind( this )); mainPostEditor.textField.addEventListener('cut', function (event) { if ( is_live_posting ) { this.updatePostText(); } mainPostEditor.resizeTextField(); }.bind( this )); mainPostEditor.textField.addEventListener('focus', mainPostEditor.focusElement); mainPostEditor.textField.addEventListener('focusout', mainPostEditor.focusOutElement); mainPostEditor.element.onclick = function ( event ) { // mainPostEditor.textField.focus(); why???? }; if (id) { mainPostEditor.textField.placeholder = "Schreibe etwas oder ziehe eine Datei in dieses Feld..."; } else { mainPostEditor.textField.placeholder = "Sie sind nicht eingelogt"; mainPostEditor.textField.disabled = true; } mainPostEditor.textField.onkeyup = function (event) { clearTimeout(timeoutNo); var text = mainPostEditor.textField.value; var pressedKey = event.key; mainPostEditor.getTagsFromText(text); if ( pressedKey === '#' ) { typing_hashtag = true; search_hashtag = ''; mainPostEditor.element.appendChild( hashtag_result_div ); hashtag_result_div.textContent = ''; } if ( pressedKey === ' ' ) { typing_hashtag = false; search_hashtag = ''; hashtag_result_div.textContent = ''; mainPostEditor.element.removeChild( hashtag_result_div ); } if (mainPostEditor.tags.length > 0 || pressedKey === "#") { mainPostEditor.addTags(); } else if (tagsContainer) { removeTags(); } if (text !== null && text.length > 3) { timeoutNo = setTimeout(mainPostEditor.evaluateText.bind(this, text), 450); } else { currentUrl = ""; } if ( typing_hashtag && pressedKey != '#' ) { //avoid first letter if ( pressedKey == 'Backspace' ) { search_hashtag = search_hashtag.slice(0, search_hashtag.length-1); } else { search_hashtag+= pressedKey; } socketGateway.emit("searchForTags", search_hashtag , function( response ){ if ( response.term == search_hashtag ) { hashtag_result_div.textContent = ''; var i, l = response.tags.length, tag_link; for ( i = 0; i < l; i++ ) { tag_link = document.createElement('DIV'); tag_link.style.float = "left"; tag_link.style.cursor = "pointer"; tag_link.style.padding = "3px 5px"; tag_link.textContent = '#' + response.tags[i]; tag_link.onclick = function( event ) { mainPostEditor.textField.value = mainPostEditor.textField.value.replace( '#' + search_hashtag, '#' + this.tag + ' ' ); mainPostEditor.element.removeChild( hashtag_result_div ); mainPostEditor.getTagsFromText( mainPostEditor.textField.value ); mainPostEditor.addTags(); mainPostEditor.textField.focus(); event.stopPropagation(); event.preventDefault(); }.bind( { tag : response.tags[i] } ) hashtag_result_div.appendChild( tag_link ) } } }); } }; mainPostEditor.element.appendChild(mainPostEditor.textField); mainPostEditor.element.appendChild(mainPostEditor.upperMenu); }; mainPostEditor.addTags = function () { if (tagsContainer && tagsContainer.parentNode === mainPostEditor.element) { removeTags(); } tagsContainer = document.createElement("DIV"); tagsContainer.className = "tags-container"; var tagsLabel = document.createElement("DIV"); tagsLabel.className = "tag label"; tagsLabel.textContent = "Tags: "; tagsContainer.appendChild(tagsLabel); var i, tagsLength = mainPostEditor.tags.length; for (i = 0; i < tagsLength; i++) { var tag = mainPostEditor.tags[i].tag; var tagElement = document.createElement("DIV"); tagElement.className = "tag"; tagElement.textContent = tag; tagsContainer.appendChild(tagElement); } mainPostEditor.element.insertBefore(tagsContainer, mainPostEditor.attachmentManager.element); }; mainPostEditor.createStockTags = function () { if (stocksContainer && stocksContainer.parentNode === mainPostEditor.element) { mainPostEditor.element.removeChild(stocksContainer); stocksContainer = undefined; } stocksContainer = document.createElement("DIV"); stocksContainer.className = "tags-container"; var stocksLabel = document.createElement("DIV"); stocksLabel.className = "tag label"; stocksLabel.textContent = "Stocks: "; var i, remove, stock, stockElement, stocksLength = mainPostEditor.stocksManager.stocks.length; if (stocksLength > 0) { stocksContainer.appendChild(stocksLabel); } for (i = 0; i < stocksLength; i++) { socketGateway.emit("getStockInfoISINSource", { isin: mainPostEditor.stocksManager.stocks[i].isin, source: mainPostEditor.stocksManager.stocks[i].source }, function (response) { if (!response.result) { return; } stock = response.data.name; stockElement = document.createElement("DIV"); stockElement.className = "tag"; stockElement.textContent = stock; stocksContainer.appendChild(stockElement); remove = document.createElement("SPAN"); remove.textContent = "(x)"; remove.title = "remove"; stockElement.appendChild(remove); remove.onclick = function (event) { mainPostEditor.stocksManager.removeStock(this.isin, this.source); event.stopPropagation(); event.preventDefault(); }.bind({isin: this.isin, source: this.source}); stockElement.onclick = function (event) { if(environment === "tradingdesk"){ if (currentHome.stockAction != null) { currentHome.stockAction.fn.call(currentHome.stockAction.context, this.isin, this.source) } } else if(["mobile", "messenger"].indexOf(environment) != -1){ window.open( 'https://desk.traderfox.com:88/stock/' + this.id, '_blank' ); } event.preventDefault(); }.bind({isin: this.isin, source: this.source, id : response.data.id}) }.bind({ isin: mainPostEditor.stocksManager.stocks[i].isin, source: mainPostEditor.stocksManager.stocks[i].source })) } mainPostEditor.element.insertBefore(stocksContainer, mainPostEditor.attachmentManager.element); }; mainPostEditor.createNewsSection = function () { if (news_container && news_container.parentNode === mainPostEditor.element) { mainPostEditor.element.removeChild(news_container); news_container = undefined; } news_container = document.createElement("DIV"); news_container.className = "tags-container"; var stocksLabel = document.createElement("DIV"); stocksLabel.className = "tag label"; stocksLabel.textContent = "Related News: "; var news = mainPostEditor.stocksManager.news; var i, remove, stock, news_element, news_length = news.length; if (news_length > 0) { news_container.appendChild(stocksLabel); } for (i = 0; i < news_length; i++) { news_element = document.createElement("DIV"); news_element.className = "tag"; news_element.textContent = news[i].title; news_element.onclick = function (event) { if(environment === "tradingdesk"){ if (currentHome.externalAction != null) { currentHome.externalAction.fn.call(currentHome.externalAction.context, { 'type' : 'news', id : this.id, source : this.source } ) } } else if(["mobile", "messenger"].indexOf(environment) != -1){ alert("Dieser Inhalt ist in der App nicht verfügbar. Nutzen Sie das Trading-Desk"); } event.preventDefault(); }.bind({id: news[i].id, source: news[i].source}) remove = document.createElement("SPAN"); remove.textContent = "(x)"; remove.title = "remove"; remove.onclick = function (event) { mainPostEditor.stocksManager.removeNews( this.id, this.source); event.stopPropagation(); event.preventDefault(); }.bind({id: news[i].id, source: news[i].source}); news_container.appendChild(news_element); news_element.appendChild(remove); } mainPostEditor.element.insertBefore(news_container, mainPostEditor.attachmentManager.element); }; mainPostEditor.createCloudSection = function () { if (cloud_container && cloud_container.parentNode === mainPostEditor.element) { mainPostEditor.element.removeChild(cloud_container); cloud_container = undefined; } cloud_container = document.createElement("DIV"); cloud_container.className = "tags-container cloud"; var cloud_label = document.createElement("DIV"); cloud_label.className = "tag label"; cloud_label.textContent = ""; var cloud = mainPostEditor.stocksManager.cloud; var i, remove, cloud_element, cloud_icon, cloud_title, cloud_length = cloud.length; if (cloud_length > 0) { cloud_container.appendChild(cloud_label); } for (i = 0; i < cloud_length; i++) { cloud_icon = document.createElement("DIV"); cloud_icon.className = "icon"; cloud_icon.innerHTML = "" ;//height:100% cloud_title = document.createElement("DIV"); cloud_title.className = "title"; cloud_title.textContent = cloud[i].title; cloud_element = document.createElement("DIV"); cloud_element.className = "tag cloud"; cloud_element.onclick = function (event) { if(environment === "tradingdesk"){ if (currentHome.externalAction != null) { currentHome.externalAction.fn.call(currentHome.externalAction.context, { 'type' : 'cloud', id : this.id } ) } } else if(["mobile", "messenger"].indexOf(environment) != -1){ alert("Dieser Inhalt ist in der App nicht verfügbar. Nutzen Sie das Trading-Desk"); } event.preventDefault(); }.bind( { id: cloud[i].id } ) remove = document.createElement("DIV"); remove.textContent = " (x)"; remove.className = "remove"; remove.title = "remove"; remove.onclick = function (event) { mainPostEditor.stocksManager.removeCloud( this.id); event.stopPropagation(); event.preventDefault(); }.bind( { id: cloud[i].id } ); cloud_element.appendChild( cloud_icon ); cloud_element.appendChild( cloud_title ); cloud_element.appendChild( remove ); cloud_container.appendChild(cloud_element); } mainPostEditor.element.insertBefore(cloud_container, mainPostEditor.attachmentManager.element); }; mainPostEditor.createLivePostButton = function(){ if ( has_live_button && currentUser.live_post ) { live_post_button = document.createElement("DIV"); live_post_button.className = "live-post-button" ; live_post_button.innerHTML = " LIVE"; live_post_button.onclick = function ( event ) { this.handleLivePostingActivity(); event.stopPropagation(); event.preventDefault(); }.bind( this ); mainPostEditor.upperMenu.appendChild(live_post_button); } }; mainPostEditor.createPostButton = function () { postButton = document.createElement("BUTTON"); postButton.className = "make-post-button"; postButton.title = editing ? "Beitrag ändern" : "Beitrag senden"; if (!id) { postButton.disabled = true; } postButton.onclick = function () { if (mainPostEditor.textField.value.trim().length > 0 || mainPostEditor.attachmentManager.getAttachments().length > 0) { mainPostEditor.makePost(); removeTags(); removeStocks(); removeNews(); removeCloud(); mainPostEditor.stocksManager.emptyAttachments() } }; mainPostEditor.upperMenu.appendChild(postButton); }; mainPostEditor.createFileUploadButton = function () { var fileUploadContainer = document.createElement("label"); fileUploadContainer.title = "Datei hochladen"; fileUploadContainer.className = "editor-upper-menu-button upload fa fa-paperclip"; fileUploadContainer.style.fontSize = "18px"; fileUploadContainer.style.textDecoration = "none"; fileUploadContainer.style.textAlign = "right"; fileUploadContainer.style.float = "right"; fileUploadContainer.style.cursor = "pointer"; var fileUploadButton = document.createElement("INPUT"); if (!id) { fileUploadButton.disabled = true; fileUploadContainer.style.display = "none"; } fileUploadButton.type = "file"; fileUploadButton.accept = supportedFileTypes; fileUploadButton.id = "upload"; //fileUploadButton.className = "post-editor-file-upload-button"; fileUploadButton.style.display = "none"; mainPostEditor.attachmentManager.createButtonUploader(fileUploadButton); mainPostEditor.upperMenu.appendChild(fileUploadContainer); fileUploadContainer.appendChild(fileUploadButton); if ( environment == 'messenger' ) { var fileShareButton = document.createElement("div"); fileShareButton.title = "Shared Charts/Lists"; fileShareButton.className = "editor-upper-menu-button fa fa-share-alt"; fileShareButton.style.fontSize = "18px"; fileShareButton.style.textAlign = "right"; fileShareButton.style.float = "right"; fileShareButton.style.textDecoration = "none"; fileShareButton.style.cursor = "pointer"; fileShareButton.onclick = function (event) { if ( currentHome.api.showShareMenu != null ) { currentHome.api.showShareMenu(); } event.stopPropagation(); event.preventDefault(); }.bind( this ) mainPostEditor.upperMenu.appendChild(fileShareButton); } }; mainPostEditor.createStockSearchInput = function () { var search_div = document.createElement("DIV"); var resultDiv = document.createElement("DIV"); resultDiv.style.minHeight = "200px"; resultDiv.style.padding = "10px"; resultDiv.style.border = "1px solid"; resultDiv.style.position = "relative"; resultDiv.style.clear = "both"; resultDiv.style.display = "none"; var searchInput = document.createElement("INPUT"); searchInput.type = "text"; searchInput.className = "search-stock-input"; searchInput.placeholder = "Aktie zuordnen (optional)"; var timeout = null; searchInput.onkeyup = function( event ) { if ( searchInput.value.length > 0 ) { clearTimeout(timeout); timeout = setTimeout( function(){ socketGateway.emit("searchStock", searchInput.value, function (response) { resultDiv.innerText = ""; var table = document.createElement('TABLE'); table.style.width = "100%"; table.className = "table"; var removeSearch = document.createElement("SPAN"); removeSearch.className = "fa fa-window-close"; removeSearch.style.cursor = "pointer"; removeSearch.style.float = "right"; removeSearch.onclick = function(event){ event.stopPropagation(); event.preventDefault(); resultDiv.style.display="none"; searchInput.value = ""; } var removeTR = document.createElement("TR"); var removeTD = document.createElement("TD"); removeTD.colSpan = "5"; removeTD.appendChild( removeSearch ) removeTR.appendChild( removeTD ); table.appendChild( removeTR ); if ( response && response.term == searchInput.value ) { var tr, i, l = response.data.length; for( i = 0; i < l; i++ ) { tr = document.createElement('TR'); tr.style.cursor = "pointer"; tr.innerHTML = ""+response.data[i].name+""+response.data[i].source+""+response.data[i].postfix+""+response.data[i].symbol+""+response.data[i].wkn+""; tr.onclick = function( event ) { mainPostEditor.stocksManager.processData( { 'type' : 'stock', 'data' : this.id } ); resultDiv.style.display="none"; searchInput.value = ""; }.bind( response.data[i] ) table.appendChild(tr); } resultDiv.appendChild(table); } resultDiv.style.display="block"; } ) }, 400 ) } else { clearTimeout(timeout); resultDiv.style.display ="none"; } } search_div.appendChild(searchInput) search_div.appendChild(resultDiv) mainPostEditor.upperMenu.appendChild(search_div); }; mainPostEditor.createAttachmentPreview = function () { preview = document.createElement("DIV"); preview.className = "infostream-preview"; mainPostEditor.element.appendChild(preview); }; mainPostEditor.createAttachmentManager = function () { mainPostEditor.attachmentManager = new AttachmentManager(preview); mainPostEditor.attachmentManager.createDragAndDropper(mainPostEditor.textField); mainPostEditor.stocksManager = new DropManager(preview, mainPostEditor, stocks, news, cloud); mainPostEditor.stocksManager.createDragAndDropper(mainPostEditor.textField); mainPostEditor.stocksManager.onDrop = function () { mainPostEditor.createStockTags(); mainPostEditor.createCloudSection(); mainPostEditor.createNewsSection(); if ( is_live_posting ) { mainPostEditor.sendLivePostingData('live-post-data'); } } mainPostEditor.createStockTags(); mainPostEditor.createCloudSection(); mainPostEditor.createNewsSection(); mainPostEditor.attachmentManager.onAttachmentAction(function () { if ( is_live_posting ) { mainPostEditor.sendLivePostingData('live-post-data'); } }); }; mainPostEditor.evaluateText = function (text) { //var url = mainPostEditor.getURLFromText(text.split(/[\s\n]+/)); var urls = mainPostEditor.getURLsFromText(text.split(/[\s\n]+/)); var waitin_atach, url, i, l = urls.length; for ( i = 0; i < l; i++ ) { url = urls[i]; if (currentUrls.indexOf(url) == -1 && mainPostEditor.filterDomains(url)) { currentUrls.push(url); waitin_atach = mainPostEditor.attachmentManager.addWaitingPlaceholder(url); mainPostEditor.attachmentManager.onRemoveAttachment(function () { var j , k = currentUrls.length; for ( j = 0; j < k; j++ ) { currentUrls.splice(j, 1); break; } }); socketGateway.emit("analyzeUrl", url, function (data) { switch (data.status) { case 200: if (currentUrls.indexOf( data.url ) != -1 ) { if (data.type === "youtube") { mainPostEditor.attachmentManager.addYouTube(data, this.waitin_atach); } else if (data.type === "fileUrl") { mainPostEditor.attachmentManager.addFile(data, this.waitin_atach); } else if (data.type === "url") { mainPostEditor.attachmentManager.addLink(data, this.waitin_atach); } else { mainPostEditor.attachmentManager.removeAttachment( this.waitin_atach ); } if ( is_live_posting ) { mainPostEditor.sendLivePostingData('live-post-data'); } } else { mainPostEditor.attachmentManager.removeAttachment( this.waitin_atach ); } break; case 500: mainPostEditor.attachmentManager.removeAttachment( this.waitin_atach ); //mainPostEditor.attachmentManager.addErrorImage(); break; } }.bind( { waitin_atach : waitin_atach } )); socketGateway.emit("receiveScreenshot", url, function (data) { if (currentUrls.indexOf( data.url) != -1 ) { mainPostEditor.attachmentManager.setScreenshot(data.attachments[0], this.waitin_atach) } else { mainPostEditor.attachmentManager.removeAttachment( this.waitin_atach ); } }.bind( { waitin_atach : waitin_atach } )); } } /* if (currentUrl !== url && mainPostEditor.filterDomains(url)) { currentUrl = url; if (url) { var waitin_atach = mainPostEditor.attachmentManager.addWaitingPlaceholder(url); mainPostEditor.attachmentManager.onRemoveAttachment(function () { currentUrl = ""; }); socketGateway.emit("analyzeUrl", url, function (data) { switch (data.status) { case 200: if (currentUrl === data.url) { if (data.type === "youtube") { mainPostEditor.attachmentManager.addYouTube(data, waitin_atach); } else if (data.type === "fileUrl") { mainPostEditor.attachmentManager.addFile(data, waitin_atach); } else if (data.type === "url") { mainPostEditor.attachmentManager.addLink(data, waitin_atach); } if ( is_live_posting ) { mainPostEditor.sendLivePostingData(); } } break; case 500: mainPostEditor.attachmentManager.addErrorImage(); break; } }); socketGateway.emit("receiveScreenshot", url, function (data) { if (currentUrl === data.url) { mainPostEditor.attachmentManager.setScreenshot(data.attachments[0], waitin_atach) } }); } } */ }; mainPostEditor.getURLFromText = function (wordsArray) { var i, word; var wordsArrayLength = wordsArray.length; for (i = 0; i < wordsArrayLength; i++) { word = wordsArray[i]; if (word.length === 0) { continue; } else if (word.lastIndexOf("www.", 0) === 0) { wordsArray[i] = "http://" + word; return mainPostEditor.getURLFromText(wordsArray); } else if (isStringURL(word)) { return word; } } }; mainPostEditor.getURLsFromText = function (wordsArray) { var i, word, urls = []; var wordsArrayLength = wordsArray.length; for (i = 0; i < wordsArrayLength; i++) { word = wordsArray[i]; if (word.length === 0) { continue; } else if (word.lastIndexOf("www.", 0) === 0) { wordsArray[i] = "http://" + word; return mainPostEditor.getURLsFromText(wordsArray); } else if (isStringURL(word)) { //return word; urls.push( word ); } } return urls; }; mainPostEditor.filterDomains = function (url) { if (url == undefined) { return false; } var blocked = ['facebook.com']; //, 'twitter.com' var i, l = blocked.length; for (i = 0; i < l; i++) { if (url.indexOf(blocked[i]) != -1) { return false; } } return true; }; mainPostEditor.makePost = function () { var text = mainPostEditor.textField.value; var title = with_title || is_live_posting ? mainPostEditor.titleField.value : null; mainPostEditor.getTagsFromText(text); var attachments = mainPostEditor.getAttachmentsInfo(); onPostcallback({ "text": text, "title": title, "attachments": attachments, "tags": mainPostEditor.tags, "mentions": mainPostEditor.getMentionedUsers(text), "stocks": mainPostEditor.stocksManager.stocks, "news": mainPostEditor.stocksManager.news, "cloud": mainPostEditor.stocksManager.cloud }); mainPostEditor.attachmentManager.emptyPreviewWindow(); currentUrl = ""; mainPostEditor.textField.value = ""; if ( is_live_posting ) { this.handleLivePostingActivity(); mainPostEditor.titleField.value = ""; } mainPostEditor.resizeTextField(); }; mainPostEditor.getAttachmentsInfo = function () { var attachment_info = []; var attachments = mainPostEditor.attachmentManager.getAttachments(); var i, l = attachments.length; for ( i = 0; i < l; i++ ) { attachment_info.push( { "title": attachments[i].getTitle(), "path": attachments[i].getPath(), "type": attachments[i].getType(), "url": attachments[i].getUrl(), "description": attachments[i].getDescription() } ) } return attachment_info; }; mainPostEditor.onPost = function (callback) { onPostcallback = callback; }; mainPostEditor.isLivePosting = function(){ return is_live_posting; }; mainPostEditor.focusElement = function () { mainPostEditor.element.className = "infostream-input editor-focus"; //alertManager.overlay( mainPostEditor.element ); }; mainPostEditor.focusOutElement = function () { mainPostEditor.element.className = "infostream-input"; }; mainPostEditor.createtitleField = function () { mainPostEditor.titleField = document.createElement("TEXTAREA"); mainPostEditor.titleField.className = "infostream-textfield"; //infostream-titlefield mainPostEditor.titleField.placeholder = "Post title"; mainPostEditor.titleField.rows = 1; mainPostEditor.titleField.cols = 70; mainPostEditor.element.appendChild(mainPostEditor.titleField); if ( with_title ) { mainPostEditor.titleField.style.display = "block"; } else { mainPostEditor.titleField.style.display = "none"; } mainPostEditor.titleField.onkeydown = function( event ) { if ( is_live_posting ) { clearTimeout( title_key_down_timeout ); title_key_down_timeout = setTimeout( function(){ title_key_down_counter = 0; this.sendLivePostingData( 'title' ); }.bind( this ), 1000 ) title_key_down_counter++; if ( title_key_down_counter > 5 ) { title_key_down_counter = 0; this.sendLivePostingData( 'title' ); } event.stopPropagation(); } }.bind( this ) mainPostEditor.titleField.addEventListener('paste', function (event) { if ( is_live_posting ) { setTimeout( function(){ this.sendLivePostingData( 'title' ); }.bind( this ), 1 ) } }.bind( this )); mainPostEditor.titleField.addEventListener('cut', function (event) { if ( is_live_posting ) { setTimeout( function(){ this.sendLivePostingData( 'title' ); }.bind( this ), 1 ) } }.bind( this )); }; mainPostEditor.updatePostText = function(){ clearTimeout( text_key_down_timeout ); text_key_down_counter++; if ( text_key_down_counter > 5 ) { text_key_down_counter = 0; clearTimeout( text_key_down_timeout ); this.sendLivePostingData( 'text' ); } else { text_key_down_timeout = setTimeout( function(){ text_key_down_counter = 0; this.sendLivePostingData( 'text' ); }.bind( this ), 1000 ) } }; mainPostEditor.init = function () { mainPostEditor.createtitleField(); mainPostEditor.createInputField(); mainPostEditor.createPostButton(); mainPostEditor.createAttachmentPreview(); mainPostEditor.createAttachmentManager(); mainPostEditor.createFileUploadButton(); mainPostEditor.createStockSearchInput(); // mainPostEditor.createLivePostButton(); if ( currentHome.autoPost != null ) { if ( currentHome.autoPost.comment != null ) { mainPostEditor.textField.value = currentHome.autoPost.comment; } mainPostEditor.stocksManager.processData( currentHome.autoPost ); currentHome.autoPost = null; currentHome.autoPostEditor = mainPostEditor; } }; mainPostEditor.addMoreCloudInfo = function(data){ if ( data.comment != null ) { currentHome.autoPostEditor.textField.value = currentHome.autoPostEditor.textField.value + " " + data.comment; } currentHome.autoPostEditor.stocksManager.processData( data ); }; mainPostEditor.handleLivePostingActivity = function() { is_live_posting = !is_live_posting; live_post_button.innerHTML = " LIVE"; if ( is_live_posting ) { this.titleField.style.display = "block"; this.sendLivePostingData('start'); } else { this.titleField.style.display = "none"; this.sendLivePostingData('end'); } }; mainPostEditor.pauseLivePostingActivity = function() { is_live_posting = false; live_post_button.innerHTML = " LIVE"; this.titleField.style.display = "none"; }; mainPostEditor.sendLivePostingData = function(type) { var attachments = mainPostEditor.getAttachmentsInfo(); var attachment_data = { "attachments": attachments, "tags": mainPostEditor.tags, "stocks": mainPostEditor.stocksManager.stocks, "news": mainPostEditor.stocksManager.news, "cloud": mainPostEditor.stocksManager.cloud } var post_data = { type : type, group : group_id, text : mainPostEditor.textField.value, title : mainPostEditor.titleField.value, attachment_data : attachment_data }; socketGateway.emit("LivePosting", post_data , function (response) {} ); }; /* mainPostEditor.sendLivePosting = function( type ) { var data = { type : type, group : group_id, text : mainPostEditor.textField.value, title : mainPostEditor.titleField.value }; socketGateway.emit("LivePosting", data , function (response) {} ); }; */ // Regular Expression for URL validation // // Author: Diego Perini // Updated: 2010/12/05 // License: MIT // // Copyright (c) 2010-2013 Diego Perini (http://www.iport.it) // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. var re_weburl = new RegExp( "^" + // protocol identifier "(?:(?:https?|ftp)://)" + // user:pass authentication "(?:\\S+(?::\\S*)?@)?" + "(?:" + // IP address exclusion // private & local networks "(?!(?:10|127)(?:\\.\\d{1,3}){3})" + "(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" + "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" + // IP address dotted notation octets // excludes loopback network 0.0.0.0 // excludes reserved space >= 224.0.0.0 // excludes network & broacast addresses // (first & last IP address of each class) "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" + "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" + "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" + "|" + // host name "(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" + // domain name "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" + // TLD identifier "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" + // TLD may end with dot "\\.?" + ")" + // port number "(?::\\d{2,5})?" + // resource path "(?:[/?#]\\S*)?" + "$", "i" ); return mainPostEditor; } /* More of an "abstract" class. An input field supporting # tags. */ function PostEditor(element) { var postEditor = {}; postEditor.element = element; postEditor.textField; postEditor.postButton; postEditor.tags; postEditor.upperMenu = document.createElement("DIV"); postEditor.upperMenu.className = "post-editor-upper-menu"; postEditor.mentionedUsers = []; var postCallback; postEditor.createInputField = function () { postEditor.textField = document.createElement("TEXTAREA"); postEditor.textField.className = "infostream-textfield"; postEditor.textField.rows = 5; postEditor.textField.cols = 70; postEditor.element.appendChild(postEditor.textField); postEditor.element.appendChild(postEditor.upperMenu); postEditor.textField.addEventListener('keydown', postEditor.resizeTextField); }; postEditor.resizeTextField = function () { setTimeout(function () { postEditor.textField.style.cssText = 'height:auto; padding:0'; if ( postEditor.textField.value == "" ) { postEditor.textField.style.cssText = ''; } else { postEditor.textField.style.cssText = 'height:' + ( postEditor.textField.scrollHeight + 10 ) + 'px'; } }, 0); }; postEditor.createPostButton = function () { postEditor.postButton = document.createElement("INPUT"); postEditor.postButton.type = "submit"; postEditor.postButton.value = "Post >>"; postEditor.postButton.onclick = function () { if (postEditor.textField.value.trim().length > 0) { postEditor.makePost(); } }; postEditor.element.appendChild(postEditor.postButton); }; postEditor.makePost = function () { var text = postEditor.textField.value; postEditor.getTagsFromText(text); postCallback({ "text": text, "tags": postEditor.tags, "mentions": postEditor.getMentionedUsers(text), "stocks" : postEditor.stocksManager.stocks }); postEditor.textField.value = ""; }; postEditor.getMentionedUsers = function (text) { var usersToMention = []; var i, mentionedUsersLength = postEditor.mentionedUsers.length; for(i = 0; i < mentionedUsersLength; i++){ var user = postEditor.mentionedUsers[i].name; var regEx = new RegExp(user); var result = text.match(regEx); if(result){ var matchIndex = result.index; if(text.charAt(matchIndex - 1) === "@"){ usersToMention.push(postEditor.mentionedUsers[i].id); } } } postEditor.mentionedUsers = []; return usersToMention; }; postEditor.getTagsFromText = function (text) { var regEx = /#/g; var match, subText; postEditor.tags = []; while ((match = regEx.exec(text)) !== null) { subText = text.slice(match.index + 1); var tag = subText.split(/[\s#]+/)[0]; var tagObject = { "typedTag": tag, "tag": tag }; if (tag.length > 0 && !tagAlreadyExists(tagObject.tag)) { postEditor.tags.push(tagObject); } } }; var tagAlreadyExists = function (tag) { var i, arrayLength = postEditor.tags.length; for (i = 0; i < arrayLength; i++) { if (postEditor.tags[i].tag === tag) { return true; } } return false; }; postEditor.onPost = function (callback) { postCallback = callback; }; postEditor.init = function () { postEditor.createInputField(); postEditor.createPostButton(); }; return postEditor; } /* Child of PostEditor. It sports a resizing text field */ function ReplyEditor(element) { var replyEditor = new PostEditor(element); var onReplyCallback; replyEditor.onReply = function (callback) { onReplyCallback = callback; }; replyEditor.makePost = function() { var text = replyEditor.textField.value; replyEditor.getTagsFromText(text); onReplyCallback(text, replyEditor.tags); replyEditor.textField.value = ""; replyEditor.resizeTextField(); }; replyEditor.createInputField = function () { replyEditor.createEditorPicture(); replyEditor.textField = document.createElement("TEXTAREA"); replyEditor.textField.className = "reply-textfield"; replyEditor.textField.placeholder = "Schreibe einen Kommentar"; replyEditor.element.appendChild(replyEditor.textField); replyEditor.textField.addEventListener('keydown', replyEditor.resizeTextField); }; replyEditor.createEditorPicture = function () { var picture = document.createElement("IMG"); picture.className = "profile-picture reply editor"; picture.src = projectDomain + currentUser.picture; //replyEditor.picturePath replyEditor.element.appendChild(picture); }; replyEditor.createPostButton = function () { //not needed, we post by pressing enter. /* replyEditor.postButton = document.createElement("BUTTON"); replyEditor.postButton.innerHTML = "Reply"; replyEditor.postButton.className = "make-post-button"; replyEditor.postButton.onclick = function () { if(replyEditor.textField.value.trim().length > 0){ replyEditor.makePost(); } }.bind(this); replyEditor.element.appendChild(replyEditor.postButton); */ }; replyEditor.init = function () { replyEditor.createInputField(); replyEditor.createPostButton(); }; replyEditor.resizeTextField = function ( event ) { if ( event != undefined && event.keyCode == 13 && !event.shiftKey ) { //save it if(replyEditor.textField.value.trim().length > 0){ replyEditor.makePost(); } event.preventDefault(); } else { setTimeout(function(){ if ( replyEditor.textField.value == "" ) { replyEditor.textField.style.cssText = ''; } else { replyEditor.textField.style.cssText = 'height:auto; padding:0'; replyEditor.textField.style.cssText = 'height:' + ( replyEditor.textField.scrollHeight + 10 ) + 'px'; } // replyEditor.textField.style.cssText = 'height:auto; padding:0'; // replyEditor.textField.style.cssText = 'height:' + ( replyEditor.textField.scrollHeight + 10 ) + 'px'; },0); } }; return replyEditor; } /* The profile of a user. Depending on the role of the user and the profile being viewed, it presents different functionalities. It can contain different lists of posts, groups or traders, as well as settings. */ function Profile(args) { currentView.setNewView( { type : 'profile', id : parseInt(args.profileid), onChangeView : null } ) var id = parseInt(args.profileid); var username = args.username; var title = args.title || "Noch kein Titel"; var viewerid = args.readerid; var isFollowed = args.isFollowed; var isBlocked = args.isBlocked; var commentsCount = args.commentsCount; var mentionsCount = args.mentionsCount; var followedUserPostsCount = args.followedUserPostsCount; var groupsCount = args.groupsCount; var followersCount = args.followersCount; var followsCount = args.followsCount; var blocksCount = args.blocksCount; var interestedCount = args.interestedCount; var profilePicture = args.profilePicture; var permission_required = args.permission; var sharesPrivateRoomInfo = args.sharesPrivateRoomInfo; var settings = { mention_email: args.mention_email, profile_mention_email: args.mention_email, offline_chat_email: args.offline_chat_email, eod_rooms_email: args.eod_rooms_email, eod_groups_email: args.eod_groups_email, visible: args.visible } var buttons = {}; var profile = {}; profile.pictureManager; profile.element = document.createElement("DIV"); var profileHeader; var postEditor = null; var postEditorInput = document.createElement("DIV"); profile.currentScreen; var viewElement = document.createElement("DIV"); viewElement.className = "profile-info"; var moreToFetch = true; var alreadyFetching = false; var loadingContainer; var numberOfPostsShown = 10; var createUI = function () { profile.element.className = "profile"; profileHeader = document.createElement("DIV"); profileHeader.className = "profile-header"; var table = document.createElement("TABLE"); table.className = "profile-header-table"; //table.border = 1; var tr1 = document.createElement("TR"); tr1.className = "profile-header-row1"; var pictureCell = document.createElement("TD"); pictureCell.className = "profile-picture"; pictureCell.rowSpan = "3"; var nameCell = document.createElement("TD"); nameCell.colSpan = "3"; nameCell.paddingTop = "5px"; var followCell = document.createElement("TD"); loadingContainer = document.createElement("DIV"); tr1.appendChild(pictureCell); tr1.appendChild(nameCell); tr1.appendChild(followCell); var tr2 = document.createElement("TR"); tr2.className = "profile-header-row2"; var titleCell = document.createElement("TD"); titleCell.colSpan = "3"; titleCell.className = "title"; var blockCell = document.createElement("TD"); tr2.appendChild(titleCell); tr2.appendChild(blockCell); var tr3 = document.createElement("TR"); tr3.className = "profile-header-row3"; var categoriesCell_1 = document.createElement("TD"); categoriesCell_1.colSpan = "3"; categoriesCell_1.style.paddingLeft = "8px"; var banUserCell = document.createElement("TD"); banUserCell.className = "ban-user-cell"; var followersCell = document.createElement("TD"); followersCell.rowSpan = "2"; var blocksCell = document.createElement("TD"); blocksCell.rowSpan = "2"; tr3.appendChild(categoriesCell_1); tr3.appendChild(banUserCell); var tr4 = document.createElement("TR"); tr4.className = "profile-header-row4"; var lineContainer = document.createElement("TD"); lineContainer.colSpan = "5"; var line = document.createElement("DIV"); line.className = "dividing-line"; lineContainer.appendChild(line); tr4.appendChild(lineContainer); var tr5 = document.createElement("TR"); tr5.className = "profile-header-row5"; var categoriesCell_2 = document.createElement("TD"); categoriesCell_2.colSpan = "5"; tr5.appendChild(categoriesCell_2); profile.pictureManager = new ProfilePictureManager({ "element": pictureCell, "picturePath": profilePicture, "isOwnProfile": isOwnProfile() }); var h3 = document.createElement("div"); h3.className = "username"; h3.appendChild(document.createTextNode(username + " ")); nameCell.appendChild(h3); if (!isOwnProfile()) { var followUserButton = document.createElement("BUTTON"); if (isFollowed) { followUserButton.textContent = "Entfolgen"; followUserButton.className = "cancel unfollow"; } else { followUserButton.textContent = "Folgen"; followUserButton.className = "ok follow"; } followUserButton.onclick = function () { if (isFollowed) { alertManager.ask("Nutzer entfolgen?", function () { socketGateway.emit("unfollowUser", { "id": id }, function () { followUserButton.textContent = "Folgen"; followUserButton.className = "ok follow"; isFollowed = false; }); }); } else { alertManager.ask("Nutzer folgen?", function () { socketGateway.emit("followUser", { "id": id }, function (data) { if (data.result) { followUserButton.textContent = "Entfolgen"; followUserButton.className = "cancel unfollow"; isFollowed = true; } else { alert(data.error) } }); }); } }; if (viewerid && !isBlocked) { followCell.appendChild(followUserButton); } var blockButton = document.createElement("BUTTON"); if (isBlocked) { blockButton.textContent = "Unblock"; blockButton.className = "ok unblock"; } else { blockButton.textContent = "Block"; blockButton.className = "cancel block"; } blockButton.onclick = function () { if (isBlocked) { alertManager.ask("Nutzer entblocken?", function () { socketGateway.emit("unblockOtherUser", { "id": id }, function () { blockButton.textContent = "Block"; blockButton.className = "cancel block"; isBlocked = false; followCell.appendChild(followUserButton); }); }); } else { alertManager.ask("Nutzer blockieren?", function () { socketGateway.emit("blockOtherUser", { "id": id }, function () { blockButton.textContent = "Unblock"; blockButton.className = "ok unblock"; isBlocked = true; if (isFollowed) { followCell.removeChild(followUserButton); followUserButton.textContent = "Follow"; followUserButton.className = "ok"; isFollowed = false; } }); }); } }; if (viewerid) { blockCell.appendChild(blockButton); } } var titleDiv = document.createElement("INPUT"); titleDiv.className = "profile-title"; titleDiv.value = title; titleCell.appendChild(titleDiv); if (isOwnProfile()) { var resetTitleDiv = function () { okButton.style.display = "none"; cancelButton.style.display = "none"; window.getSelection().removeAllRanges(); //remove cursor from editable title div }; var okButton = document.createElement("BUTTON"); okButton.textContent = "Update title"; okButton.className = "ok changeTitle"; okButton.onmousedown = function () { socketGateway.emit("changeTitle", {"title": titleDiv.value}, function (newTitle) { titleDiv.value = newTitle; resetTitleDiv(); }); }; var cancelButton = document.createElement("BUTTON"); cancelButton.textContent = "Cancel"; cancelButton.className = "cancel changeTitle"; cancelButton.onmousedown = function () { resetTitleDiv(); }; okButton.style.display = "none"; cancelButton.style.display = "none"; titleCell.appendChild(okButton); titleCell.appendChild(cancelButton); titleDiv.onfocus = function () { okButton.style.display = "block"; cancelButton.style.display = "block"; }; titleDiv.onblur = function (event) { okButton.style.display = "none"; cancelButton.style.display = "none"; }; } var commentsButton = document.createElement("BUTTON"); commentsButton.textContent = "Beiträge (" + commentsCount + ")"; commentsButton.className = "profile-action selected"; commentsButton.onclick = function () { selectButton(commentsButton); createCommentsScreen(); profile.deactivateOnScroll(); profile.activateOnScroll('comments'); }; buttons['comments'] = commentsButton; var followedUserPostsButton = document.createElement("BUTTON"); followedUserPostsButton.textContent = "Follow (" + followedUserPostsCount + ")"; followedUserPostsButton.className = "profile-action"; followedUserPostsButton.onclick = function () { selectButton(followedUserPostsButton); createFollowedUserPostsScreen(); }; var mentionsButton = document.createElement("BUTTON"); mentionsButton.textContent = "Erwähnungen (" + mentionsCount + ")"; mentionsButton.className = "profile-action"; mentionsButton.onclick = function () { selectButton(mentionsButton); createMentionsScreen(); profile.deactivateOnScroll(); profile.activateOnScroll('comments'); }; var groupsButton = document.createElement("BUTTON"); groupsButton.textContent = "Gruppen (" + groupsCount + ")"; groupsButton.className = "profile-action"; groupsButton.onclick = function () { selectButton(groupsButton); createGroupsScreen(); }; var notificationsButton = document.createElement("BUTTON"); notificationsButton.textContent = "Notifications"; notificationsButton.className = "profile-action"; notificationsButton.onclick = function () { selectButton(notificationsButton); createNotificationsScreen(); }; buttons['notifications'] = notificationsButton; var cloudButton = document.createElement("DIV"); cloudButton.title = "Cloud von " + username + " öffnen."; cloudButton.className = "profile-action cloud-button"; cloudButton.onclick = function () { if(environment === "tradingdesk"){ if (currentHome.externalAction != null) { currentHome.externalAction.fn.call(currentHome.externalAction.context, { 'type' : 'cloud-view', user_id : id } ) } } else if(["mobile", "messenger"].indexOf(environment) != -1){ alert("Dieser Inhalt ist in der App nicht verfügbar. Nutzen Sie das Trading-Desk"); } }; var adminButton = document.createElement("BUTTON"); adminButton.textContent = "Admin Screen"; adminButton.className = "profile-action"; adminButton.onclick = function () { selectButton(adminButton); createAdminScreen(); }; var settingsButton = document.createElement("BUTTON"); settingsButton.onclick = function () { selectButton(settingsButton); createSettingsScreen(); }; var settingsIcon = document.createElement("IMG"); settingsIcon.className = "settings-icon"; settingsIcon.src = projectDomain + "/public/images/settings-cog.png"; settingsButton.textContent = "Einstellungen"; settingsButton.appendChild(settingsIcon); var followersButton = document.createElement("BUTTON"); followersButton.textContent = "Follower (" + followersCount + ")"; followersButton.className = "profile-action"; followersButton.onclick = function () { selectButton(followersButton); createFollowerScreen(); }; var followsButton = document.createElement("BUTTON"); followsButton.textContent = "Folge ich (" + followsCount + ")"; followsButton.className = "profile-action"; followsButton.onclick = function () { selectButton(followsButton); createFollowsScreen(); }; if (isOwnProfile()) { var blocksButton = document.createElement("BUTTON"); blocksButton.textContent = "Blockiert (" + blocksCount + ")"; blocksButton.className = "profile-action"; blocksButton.onclick = function () { selectButton(blocksButton); createBlockedScreen(); }; var interestedButton = document.createElement("BUTTON"); interestedButton.textContent = "Interessen (" + interestedCount + ")"; interestedButton.className = "profile-action"; interestedButton.onclick = function () { selectButton(interestedButton); createInterestedScreen(); }; } categoriesCell_1.appendChild(followersButton); categoriesCell_1.appendChild(followsButton); categoriesCell_1.appendChild(groupsButton); if (isOwnProfile()) { categoriesCell_1.appendChild(blocksButton); categoriesCell_1.appendChild(settingsButton); if(currentUser.admin){ categoriesCell_1.appendChild(adminButton); } } categoriesCell_2.appendChild(commentsButton); if(isOwnProfile()){ categoriesCell_2.appendChild(followedUserPostsButton); } categoriesCell_2.appendChild(mentionsButton); if (isOwnProfile()) { categoriesCell_2.appendChild(interestedButton); categoriesCell_2.appendChild(notificationsButton); } categoriesCell_2.appendChild(cloudButton); if (currentUser.admin && id !== currentUser.id) { var banButton = document.createElement("BUTTON"); banButton.textContent = "!Ban!"; banButton.onclick = function () { alertManager.ask("Nutzer sperren!?", function () { socketGateway.emit("banUser", { "userid": id }, function () { currentHome.reloadStream(); }); }); }; banUserCell.appendChild(banButton); } if(id !== currentUser.id){ var discussionButton = document.createElement("BUTTON"); discussionButton.textContent = "Gespräch anfangen"; if(sharesPrivateRoomInfo.sharesRoom){ discussionButton.onclick = function () { socketGateway.emit("getRoom", sharesPrivateRoomInfo.roomid, function (roomData) { currentHome.showRoom(roomData); }); }; } else{ discussionButton.onclick = function () { var membersData = [{ "userid": id, "name": username }]; alertManager.ask("Willst du ein Gespräch mit '" + username + "' anfangen?", function () { socketGateway.emit("createRoom", {"members": membersData, "name": username, "privateStatus": "Y"}, function (response) { if(response.status === "ok"){ socketGateway.emit("getRoom", response.roomData.id, function (roomData) { currentHome.showRoom(roomData); }); } else{ alertManager.inform(response.message); } }); }); }.bind(this); } var roomButton = document.createElement("BUTTON"); roomButton.textContent = "Im Raum einladen"; var userInRoom = function (room) { var members = room.members; var i = 0, userFound = false; while(i < members.length && !userFound){ var member = members[i]; if(member.userid == id && ["canceled", "blocked"].indexOf(member.status) !== -1){ userFound = true; } i++; } return userFound; }; roomButton.onclick = function () { socketGateway.emit("getUserRooms", {}, function (rooms) { var roomsChoicesContainer = document.createElement("DIV"); roomsChoicesContainer.className = "room-choices-container"; var shownRooms = []; for(var i = 0; i < rooms.length; i++){ var room = rooms[i]; if(room.private === "N" && room.adminid == currentUser.id && !userInRoom(room)){ var roomChoiceContainer = document.createElement("DIV"); roomChoiceContainer.className = "room-choice-container"; var label = document.createElement("DIV"); label.textContent = room.name; var choice = document.createElement("INPUT"); choice.type = "radio"; choice.name = "roomChoice"; choice.value = room.name; room["radio"] = choice; shownRooms.push(room); roomChoiceContainer.appendChild(choice); roomChoiceContainer.appendChild(label); roomsChoicesContainer.appendChild(roomChoiceContainer); } } if(shownRooms.length === 0){ roomsChoicesContainer.appendChild(document.createTextNode("Es gibt kein verfügbarer Raum für diesen Nutzer")); alertManager.inform(roomsChoicesContainer, function () {}, true); } else{ alertManager.scrollableAsk(roomsChoicesContainer, function () { var chosenRoomid, i, l = shownRooms.length; for (i = 0; i < l; i++) { var room = shownRooms[i]; var radio = room.radio; if (radio.checked) { chosenRoomid = room.id; break; } } socketGateway.emit("sendRoomInvite", {"roomid": chosenRoomid, "userid": id}, function () { //console.log("ok"); }); }); } }); }; if ( currentUser.admin ) { banUserCell.appendChild(discussionButton); banUserCell.appendChild(roomButton); } } table.appendChild(tr1); table.appendChild(tr2); table.appendChild(tr3); table.appendChild(tr4); table.appendChild(tr5); profileHeader.appendChild(table); profile.element.appendChild(profileHeader); profile.element.appendChild(viewElement); }; var selectButton = function (button) { var buttons = document.getElementsByClassName("profile-action selected"); var i, l = buttons.length; for (i = 0; i < l; i++) { buttons[i].className = "profile-action"; } button.className = "profile-action selected"; }; var isOwnProfile = function () { return id === viewerid; }; var userHasViewPermission = function () { return permission_required == null || currentUser["allowed_permissions"][permission_required] ; //== "Y" }; var clearViewScreen = function () { while (viewElement.firstChild) { viewElement.removeChild(viewElement.firstChild); } profile.currentScreen = undefined; }; var createMentionInput = function () { if (postEditor == null) { postEditorInput.type = "file"; postEditorInput.className = "infostream-input"; postEditor = new MainPostEditor(id, postEditorInput, false, [], [], [], null, false); postEditor.init(); postEditor.mentionedUsers.push({"id": id, "name": username}); postEditor.textField.value = '@' + username + ' '; postEditor.onPost(function (args) { args["origin"] = "profile"; socketGateway.emit("addPost", args, function (args) { //todo go to profile mentions!!! /* profile.currentScreen.addPostAtBeginning({ "postid": args.id, "posterName": username, "posterid": id, "readerid": id, "timestamp": args.timestamp, "text": args.text, "attachments": args.attachments, "tags": args.tags, "stocks": args.stocks, "edited": false, "picturePath": args.picturePath }); */ }); }); } viewElement.appendChild(postEditorInput); }; var createCommentsScreen = function () { numberOfPostsShown = 10; clearViewScreen(); profile.currentScreen = new InfoStream(username, viewerid); if (!isOwnProfile()) { createMentionInput(); } viewElement.appendChild(profile.currentScreen.element); viewElement.appendChild(loadingContainer); if (userHasViewPermission()) { //is actually always true, need for checking at Post level. fetchUserPosts(function (posts) { profile.currentScreen.buildInfoStream(posts); }); } else { helper.createAdsWindow( permsLinks[permission_required].img, permsLinks[permission_required].order ) /*var link = document.createElement('A') link.href = permsLinks[permission_required].order; link.style.width = "100%"; link.target = "_blank"; var pic = document.createElement('IMG') pic.src = permsLinks[permission_required].img; pic.style.width = "100%"; link.appendChild(pic); viewElement.appendChild(link); */ } }; var createFollowedUserPostsScreen = function () { numberOfPostsShown = 10; clearViewScreen(); profile.currentScreen = new InfoStream(username, viewerid); viewElement.appendChild(profile.currentScreen.element); viewElement.appendChild(loadingContainer); fetchFollowedUserPosts(function (posts) { profile.currentScreen.buildInfoStream(posts); }); profile.deactivateOnScroll(); profile.activateOnScroll("followedUser"); }; var createMentionsScreen = function () { numberOfPostsShown = 10; clearViewScreen(); profile.currentScreen = new InfoStream(username, viewerid); if (!isOwnProfile()) { createMentionInput(); } viewElement.appendChild(profile.currentScreen.element); viewElement.appendChild(loadingContainer); if (userHasViewPermission()) { fetchMentionStream(function (posts) { profile.currentScreen.buildInfoStream(posts); }); } else { helper.createAdsWindow( permsLinks[permission_required].img, permsLinks[permission_required].order ) /* var link = document.createElement('A') link.href = permsLinks[permission_required].order; link.style.width = "100%"; link.target = "_blank"; var pic = document.createElement('IMG') pic.src = permsLinks[permission_required].img; pic.style.width = "100%"; link.appendChild(pic); viewElement.appendChild(link); */ } }; var createGroupsScreen = function () { clearViewScreen(); profile.currentScreen = new GroupsScreen(id, viewerid); viewElement.appendChild(profile.currentScreen.element); }; var createFollowsScreen = function () { clearViewScreen(); profile.currentScreen = new FollowsScreen(id, viewerid); viewElement.appendChild(profile.currentScreen.element); }; var createFollowerScreen = function () { clearViewScreen(); profile.currentScreen = new FollowerScreen(id, viewerid); viewElement.appendChild(profile.currentScreen.element); }; var createBlockedScreen = function () { clearViewScreen(); profile.currentScreen = new BlockedTradersScreen(id, viewerid); viewElement.appendChild(profile.currentScreen.element); }; var createInterestedScreen = function () { numberOfPostsShown = 10; clearViewScreen(); profile.currentScreen = new InfoStream(username, viewerid); viewElement.appendChild(profile.currentScreen.element); fetchInterestingPosts(function (posts) { profile.currentScreen.buildInfoStream(posts); }); profile.deactivateOnScroll(); profile.activateOnScroll('interesting'); }; var createSettingsScreen = function () { clearViewScreen(); profile.currentScreen = new SettingsScreen(); viewElement.appendChild(profile.currentScreen.element); }; var createAdminScreen = function () { clearViewScreen(); profile.currentScreen = new AdminScreen(); viewElement.appendChild(profile.currentScreen.element); }; var createNotificationsScreen = function () { clearViewScreen(); profile.deactivateOnScroll(); profile.currentScreen = new NotificationsScreen(); viewElement.appendChild(profile.currentScreen.element); alreadyFetching = true; profile.currentScreen.createUI( function( data ) { alreadyFetching = false; moreToFetch = data["moreToFetch"]; } ) profile.activateOnScroll('notificationsTicker'); }; var fetchUserPosts = function (callback) { alreadyFetching = true; var loading = document.createElement("DIV"); loading.textContent = "Loading more..."; loadingContainer.className = "loading-more"; loadingContainer.appendChild(loading); socketGateway.emit("loadUserChatPosts", {"id": id, "numberOfPostsShown": numberOfPostsShown}, function (data) { moreToFetch = data["moreToFetch"]; loadingContainer.removeChild(loading); alreadyFetching = false; callback(data["posts"]); }); }; var fetchMentionStream = function (callback) { alreadyFetching = true; var loading = document.createElement("DIV"); loading.textContent = "Loading more..."; loadingContainer.className = "loading-more"; loadingContainer.appendChild(loading); socketGateway.emit("loadUserProfileMentions", { "id": id, "numberOfPostsShown": numberOfPostsShown }, function (data) { moreToFetch = data["moreToFetch"]; loadingContainer.removeChild(loading); alreadyFetching = false; callback(data["posts"]); }); }; var fetchMoreNotificationsForTicker = function() { alreadyFetching = true; profile.currentScreen.onScroll( function( data ){ alreadyFetching = false; moreToFetch = data["moreToFetch"]; } ); }; var fetchFollowedUserPosts = function (callback) { alreadyFetching = true; var loading = document.createElement("DIV"); loading.textContent = "Loading more..."; loadingContainer.className = "loading-more"; loadingContainer.appendChild(loading); socketGateway.emit("loadFollowedUserPosts", {"numberOfPostsShown": numberOfPostsShown}, function (data) { moreToFetch = data["moreToFetch"]; loadingContainer.removeChild(loading); alreadyFetching = false; callback(data["posts"]); }); }; var fetchInterestingPosts = function (callback) { alreadyFetching = true; var loading = document.createElement("DIV"); loading.textContent = "Loading more..."; loadingContainer.className = "loading-more"; loadingContainer.appendChild(loading); socketGateway.emit("loadInterestingPosts", {"numberOfPostsShown": numberOfPostsShown}, function (data) { moreToFetch = data["moreToFetch"]; loadingContainer.removeChild(loading); alreadyFetching = false; callback(data["posts"]); }); }; var getScrollDimensions = function () { var dimensions = {}; if ( profile.element.parentNode != null ) { dimensions["fullHeight"] = profile.element.parentNode.scrollHeight; dimensions["scrollTop"] = profile.element.parentNode.scrollTop; dimensions["clientHeight"] = profile.element.parentNode.clientHeight; dimensions["currentHeight"] = dimensions["scrollTop"] + dimensions["clientHeight"]; } else { dimensions = null; } return dimensions; }; profile.activateOnScroll = function (type) { profile.element.parentNode.onscroll = function ( force ) { var dimensions = getScrollDimensions(); if ( force === true || dimensions != null ) { if (force === true || dimensions["currentHeight"] >= dimensions["fullHeight"]) { if (!alreadyFetching && moreToFetch) { numberOfPostsShown += 10; if (type == 'comments') { fetchUserPosts(function (data) { profile.currentScreen.addOlderToInfoStream(data); }); } else if (type == 'interesting') { fetchInterestingPosts(function (data) { profile.currentScreen.addOlderToInfoStream(data); }); } else if(type === "followedUser"){ fetchFollowedUserPosts(function (data) { profile.currentScreen.addOlderToInfoStream(data); }) } else if (type === "notificationsTicker"){ fetchMoreNotificationsForTicker(); } } } } }; }; profile.deactivateOnScroll = function () { profile.element.parentNode.onscroll = null; }; profile.selectTab = function( tab ) { if( buttons[tab] != undefined ){ buttons[tab].click(); } }; createUI(); //createCommentsScreen(); return profile; } function PublicProfile(args) { this.postSharedElement = function(element){ if ( postEditor ){ postEditor.stocksManager.processData(element); } }; currentView.setNewView( { type : 'profile', id : parseInt(args.profileid), onChangeView : null, calls : { postSharedElement : [ this, this.postSharedElement ] } } ) var id = parseInt(args.profileid); var username = args.username; var realname = args.realname; var title = args.title || ( args.readerid == args.profileid ? "Noch kein Titel." : "" ); var viewerid = args.readerid; var isFollowed = args.isFollowed; var isBlocked = args.isBlocked; var commentsCount = args.commentsCount; var mediaCount = args.mediaCount; var mentionsCount = args.mentionsCount; var followedUserPostsCount = args.followedUserPostsCount; var groupsCount = args.groupsCount; var followersCount = args.followersCount; var followsCount = args.followsCount; var blocksCount = args.blocksCount; var interestedCount = args.interestedCount; var profilePicture = args.profilePicture; var permission_required = args.permission; var sharesPrivateRoomInfo = args.sharesPrivateRoomInfo; var streamSecret = args.secret || null;//"12345TERZ" var selected_tab = ""; var buttons = {}; var profile = {}; profile.pictureManager; profile.element = document.createElement("DIV"); var profileHeader; var postEditor = null; var postEditorInput = document.createElement("DIV"); profile.currentScreen; var viewElement = document.createElement("DIV"); viewElement.className = "profile-info"; var stream_menu_section = document.createElement("DIV") stream_menu_section.className = "groups-container"; var stream_input_section = document.createElement("DIV") var as_public_info = document.createElement("DIV"); as_public_info.style.position = "absolute"; as_public_info.style.top = "0px"; as_public_info.style.width = "100%"; as_public_info.style.background = "#FFEB3B"; as_public_info.style.color = "#454242"; as_public_info.style.textAlign = "center"; as_public_info.style.display = "none"; as_public_info.textContent = "So sieht dein öffentlich Profil aus "; var link_to_settings = document.createElement("SPAN") link_to_settings.textContent = "(Ändere es in den Einstellungen)"; link_to_settings.style.textDecoration = "underline"; link_to_settings.style.cursor = "pointer"; link_to_settings.onclick = function(e) { profile.selectTab("settings") } as_public_info.appendChild(link_to_settings); var moreToFetch = true; var alreadyFetching = false; var loadingContainer; var numberOfPostsShown = 10; var selectedStream = args.selectedStream || null; var mediaTypes = { "all" : "Alle", "image" : "Image", "link" : "Links", "youtube" : "Youtube", "cloud" : "Cloud", "zip" : "Ninja Scripts" } var mediaType = "all"; //image, zip var followTypes = { "traders" : "Traders", "posts" : "Chat" } var followType = "traders"; //traders,posts var pinnwandTypes = { "all" : "Alle", "posts" : "Posts", "comments" : "Kommentare", "mentions" : "Erwähnungen" } var pinnwandType = "posts"; var createUI = function () { if ( true || currentUser.id != null ) { createLoggedInUI() } else { createNotLoggedInUI(); } }; var createLoggedInUI = function(){ profile.element.className = "public-profile"; profileHeader = document.createElement("DIV"); profileHeader.className = "header"; profileHeader.appendChild(as_public_info); createProfileHeader(); var header_tabs = document.createElement( "DIV" ); header_tabs.className = "header-tabs"; createSubHeaderTabs( header_tabs ); var upper_links = document.createElement( "DIV" ); upper_links.className = "upper-links"; profileHeader.appendChild( upper_links ); createUpperLinks(upper_links) if ( currentUser.id == id ) { var upper_personal_links = document.createElement( "DIV" ); upper_personal_links.className = "upper-personal-links"; profileHeader.appendChild( upper_personal_links ); createPersonalLinks( upper_personal_links ); } loadingContainer = document.createElement("DIV"); profile.element.appendChild(profileHeader); profile.element.appendChild(header_tabs); profile.element.appendChild(viewElement); } var createNotLoggedInUI = function(){ currentHome.setLoggedOutStyle(); profile.element.className = "public-profile"; profileHeader = document.createElement("DIV"); profileHeader.className = "header"; createProfileHeader(); var header_tabs = document.createElement( "DIV" ); header_tabs.className = "header-tabs"; createSubHeaderTabs( header_tabs ) var upper_links = document.createElement( "DIV" ); upper_links.className = "upper-links"; profileHeader.appendChild( upper_links ); createUpperLinks(upper_links) var login_container = document.createElement('DIV'); login_container.className = "need-login"; login_container.style.cursor = "pointer"; login_container.appendChild( document.createTextNode( "Sie müssen sich einloggen, um die Beiträge von " + username + " zu lesen" ) ); login_container.onclick = function ( event ) { if( environment === "tradingdesk"){ if (currentHome.externalAction != null) { currentHome.externalAction.fn.call(currentHome.externalAction.context, { 'type' : 'login' } ) } } event.stopPropagation(); event.preventDefault(); } viewElement.appendChild( login_container ); profile.element.appendChild(profileHeader); profile.element.appendChild(header_tabs); profile.element.appendChild(viewElement); }; var createProfileHeader = function(){ var picture_container = document.createElement('DIV') picture_container.className = "picture-container"; profileHeader.appendChild( picture_container ); profile.pictureManager = new ProfilePictureManager({ "element": picture_container, "picturePath": profilePicture, "isOwnProfile": false }); var name_container = document.createElement('DIV'); name_container.className = "name-container"; name_container.appendChild( document.createTextNode( realname ) ); profileHeader.appendChild( name_container ); var nickname_container = document.createElement('DIV'); nickname_container.className = "nickname-container"; nickname_container.appendChild( document.createTextNode( '@' + username ) ); profileHeader.appendChild( nickname_container ); var title_container = document.createElement('DIV'); title_container.className = "title-container"; title_container.appendChild( document.createTextNode( title ) ); profileHeader.appendChild( title_container ); if ( currentUser.id == id ) { title_container.style.cursor = "pointer"; title_container.contentEditable = true; title_container.onkeydown = function( event ) { if ( event.keyCode == 13 ) { event.preventDefault(); event.stopPropagation(); title_container.blur(); } } title_container.onblur = function( event ){ event.stopPropagation(); event.preventDefault(); socketGateway.emit("changeTitle", {"title": title_container.textContent}, function () {} ) } var openTDSettings = function( event ) { if( environment === "tradingdesk"){ if (currentHome.externalAction != null) { currentHome.externalAction.fn.call(currentHome.externalAction.context, { 'type' : 'settings' } ) } } else if(["mobile", "messenger"].indexOf(environment) != -1){ alert("Dieser Inhalt ist in der App nicht verfügbar. Nutzen Sie das Trading-Desk"); } event.stopPropagation(); event.preventDefault(); } nickname_container.onclick = openTDSettings; name_container.onclick = openTDSettings; nickname_container.style.cursor = "pointer"; name_container.style.cursor = "pointer"; } }; var createSubHeaderTabs = function(element){ var commentsButton = document.createElement("BUTTON"); commentsButton.innerHTML = "PINNWAND
" + commentsCount + ""; commentsButton.className = "profile-action selected"; commentsButton.onclick = function () { selectButton(commentsButton); createCommentsScreen(); profile.deactivateOnScroll(); profile.activateOnScroll('comments'); }; buttons['comments'] = commentsButton; var tweetsButton = document.createElement("BUTTON"); tweetsButton.innerHTML = "CHART
TWEETS"; tweetsButton.className = "profile-action"; tweetsButton.onclick = function () { selectButton(tweetsButton); createChartTweetsScreen(); profile.deactivateOnScroll(); profile.activateOnScroll('charttweets'); }; buttons['tweets'] = tweetsButton; var groupsButton = document.createElement("BUTTON"); groupsButton.innerHTML = "GRUPPEN
" + groupsCount + ""; groupsButton.className = "profile-action"; groupsButton.onclick = function () { selectButton(groupsButton); createGroupsScreen(); }; var followersButton = document.createElement("BUTTON"); followersButton.innerHTML = "FOLLOWERS
" + followersCount + ""; followersButton.className = "profile-action"; followersButton.onclick = function () { selectButton(followersButton); createFollowerScreen(); }; var followsButton = document.createElement("BUTTON"); followsButton.innerHTML = ( currentUser.id == id ? "ICH FOLGE" : "ER FOLGT" ) + "
" + followsCount; followsButton.className = "profile-action"; followsButton.onclick = function () { selectButton(followsButton); createFollowsScreen(); }; var interestedButton = document.createElement("BUTTON"); interestedButton.innerHTML = "INTERESSIERT
" + interestedCount + ""; interestedButton.className = "profile-action"; interestedButton.onclick = function () { selectButton(interestedButton); createInterestedScreen(); }; var mediaButton = document.createElement("BUTTON"); mediaButton.innerHTML = "DATEIEN
" + mediaCount + ""; mediaButton.className = "profile-action"; mediaButton.onclick = function () { selectButton(mediaButton); createMediaScreen(); }; var streamsButton = document.createElement("BUTTON"); streamsButton.innerHTML = "PUBLISHING
STREAMS"; streamsButton.className = "profile-action"; streamsButton.onclick = function () { selectButton(streamsButton); createStreamsScreen(); }; buttons['streams'] = streamsButton; var wikiButton = document.createElement("BUTTON"); wikiButton.innerHTML = "WIKIFOLIOS
 "; wikiButton.className = "profile-action"; wikiButton.onclick = function () { selectButton(wikiButton); createWikifolioScreen(); }; buttons['wikifolio'] = wikiButton; element.appendChild( commentsButton ); element.appendChild( tweetsButton ); element.appendChild( groupsButton ); element.appendChild( followersButton ); element.appendChild( followsButton ); element.appendChild( interestedButton ); element.appendChild( mediaButton ); // element.appendChild( wikiButton ); //element.appendChild( streamsButton ); if ( currentUser.id == null ) { //deactivate buttons when not logged in. var i, buttons_to_deactivate = [groupsButton, interestedButton, followsButton, followersButton, mediaButton]; for ( i = 0; i < buttons_to_deactivate.length; i++ ) { buttons_to_deactivate[i].style.opacity = "0.4"; buttons_to_deactivate[i].style.cursor = "default"; buttons_to_deactivate[i].title = "Login needed."; buttons_to_deactivate[i].disabled = true; } } }; var createPersonalLinks = function( element ) { if ( currentUser.id == id ) { /* var streamSettingsButton = document.createElement("BUTTON"); streamSettingsButton.className = "profile-action"; streamSettingsButton.innerHTML = "Stream"; streamSettingsButton.title = "Stream Einstellungen"; streamSettingsButton.onclick = function () { selectButton(streamSettingsButton); createStreamSettingsScreen(); }; element.appendChild( streamSettingsButton ); */ var settingsButton = document.createElement("BUTTON"); settingsButton.className = "profile-action"; settingsButton.innerHTML = "Einstellungen"; settingsButton.title = "TraderFox Communication Platform Einstellungen"; settingsButton.onclick = function () { selectButton(settingsButton); createSettingsScreen(); }; element.appendChild( settingsButton ); buttons['settings'] = settingsButton; var notificationsButton = document.createElement("BUTTON"); notificationsButton.innerHTML = "Notifications"; notificationsButton.className = "profile-action"; notificationsButton.onclick = function () { selectButton(notificationsButton); createNotificationsScreen(); }; buttons['notifications'] = notificationsButton; element.appendChild( notificationsButton ); var blocksButton = document.createElement("BUTTON"); blocksButton.innerHTML = "Blockiert"; blocksButton.className = "profile-action"; blocksButton.onclick = function () { selectButton(blocksButton); createBlockedScreen(); }; element.appendChild( blocksButton ); buttons['blocked'] = blocksButton; if ( currentUser.admin ) { var adminButton = document.createElement("BUTTON"); adminButton.innerHTML = "Admin Screen"; adminButton.className = "profile-action inactive"; adminButton.onclick = function () { selectButton(adminButton); createAdminScreen(); }; element.appendChild( adminButton ); buttons['admin'] = adminButton; } } }; var hidePersonalLinks = function(){ if ( currentUser.admin && buttons['admin'] ) { buttons['admin'].style.display = "none" } if ( buttons['notifications'] ) { buttons['notifications'].style.display = "none"; } if ( buttons['settings'] ) { buttons['settings'].style.display = "none"; } if ( buttons['blocked'] ) { buttons['blocked'].style.display = "none"; } if ( currentUser.id == id ) { as_public_info.style.display = "block"; } }; var showPersonalLinks = function(){ if ( currentUser.admin && buttons['admin'] ) { buttons['admin'].style.display = "block"; } if ( buttons['notifications'] != undefined ) { buttons['notifications'].style.display = "block"; } if ( buttons['settings'] != undefined ) { buttons['settings'].style.display = "block"; } if ( buttons['blocked'] != undefined ) { buttons['blocked'].style.display = "block"; } as_public_info.style.display = "none"; }; var createUpperLinks = function( element ) { var cloudButton = document.createElement("BUTTON"); cloudButton.innerHTML = "Cloud"; cloudButton.title = "Cloud von " + username + " öffnen."; cloudButton.className = "profile-action cloud-button"; cloudButton.onclick = function () { if(environment === "tradingdesk"){ if (currentHome.externalAction != null) { currentHome.externalAction.fn.call(currentHome.externalAction.context, { 'type' : 'cloud-view', user_id : id } ) } } else if(["mobile", "messenger"].indexOf(environment) != -1){ alert("Dieser Inhalt ist in der App nicht verfügbar. Nutzen Sie das Trading-Desk"); } }; if( environment === "tradingdesk" ){ element.appendChild( cloudButton ); } if ( currentUser.id != undefined && currentUser.id != id ) { var discussionButton = document.createElement("BUTTON"); discussionButton.innerHTML = "Gespräch anfangen"; discussionButton.onclick = function () { if ( sharesPrivateRoomInfo.sharesRoom ) { socketGateway.emit("getRoom", sharesPrivateRoomInfo.roomid, function (roomData) { currentHome.showRoom(roomData); }); } else { alertManager.ask("Willst du ein Gespräch mit '" + username + "' anfangen?", function () { socketGateway.emit("createRoom", {"members": [{ "userid": id, "name": username }], "name": username, "privateStatus": "Y"}, function (response) { if(response.status === "ok"){ socketGateway.emit("getRoom", response.roomData.id, function (roomData) { currentHome.showRoom(roomData); }); } else { alertManager.inform(response.message); } }); }); } }; element.appendChild( discussionButton ); var roomButton = document.createElement("BUTTON"); roomButton.innerHTML = "Im Raum einladen"; roomButton.onclick = function () { socketGateway.emit("getUserRooms", {}, function (rooms) { var roomsChoicesContainer = document.createElement("DIV"); roomsChoicesContainer.className = "room-choices-container"; var roomChoiceContainer, label, choice; var i, l = rooms.length, shownRooms = [], room; for ( i = 0; i < l; i++ ){ room = rooms[i]; if ( room.private === "N" && room.adminid == currentUser.id && !userInRoom(room) ) { roomChoiceContainer = document.createElement("DIV"); roomChoiceContainer.className = "room-choice-container"; label = document.createElement("DIV"); label.textContent = room.name; choice = document.createElement("INPUT"); choice.type = "radio"; choice.name = "roomChoice"; choice.value = room.name; room["radio"] = choice; shownRooms.push(room); roomChoiceContainer.appendChild(choice); roomChoiceContainer.appendChild(label); roomsChoicesContainer.appendChild(roomChoiceContainer); } } if ( shownRooms.length === 0 ) { roomsChoicesContainer.appendChild(document.createTextNode("Es gibt kein verfügbarer Raum für diesen Nutzer")); alertManager.inform(roomsChoicesContainer, function () {}, true); } else { alertManager.scrollableAsk(roomsChoicesContainer, function () { var room, radio, chosenRoomid, i, l = shownRooms.length; for (i = 0; i < l; i++) { room = shownRooms[i]; radio = room.radio; if (radio.checked) { chosenRoomid = room.id; break; } } socketGateway.emit("sendRoomInvite", {"roomid": chosenRoomid, "userid": id}, function () { }); }); } }); }; element.appendChild( roomButton ); var blockButton = document.createElement("BUTTON"); blockButton.innerHTML = isBlocked ? "Unblock" : "Block"; blockButton.className = isBlocked ? "active unblock" : "inactive block"; blockButton.onclick = function () { if (isBlocked) { alertManager.ask("Nutzer entblocken?", function () { socketGateway.emit("unblockOtherUser", { "id": id }, function () { blockButton.innerHTML = "Block"; blockButton.className = "inactive block"; isBlocked = false; }); }); } else { alertManager.ask("Nutzer blockieren?", function () { socketGateway.emit("blockOtherUser", { "id": id }, function () { blockButton.innerHTML = "Unblock"; blockButton.className = "active unblock"; isBlocked = true; if (isFollowed) { isFollowed = false; } }); }); } }; element.appendChild( blockButton ); var followUserButton = document.createElement("BUTTON"); followUserButton.innerHTML = isFollowed ? "Entfolgen" : "Folgen"; followUserButton.title = "Folgen " + username + ""; followUserButton.className = isFollowed ? "inactive" : "active"; followUserButton.onclick = function () { if (isFollowed) { alertManager.ask("Nutzer entfolgen?", function () { socketGateway.emit("unfollowUser", { "id": id }, function () { followUserButton.innerHTML = "Folgen"; followUserButton.className = "active"; isFollowed = false; }); }); } else { alertManager.ask("Nutzer folgen?", function () { socketGateway.emit("followUser", { "id": id }, function (data) { if (data.result) { followUserButton.innerHTML = "Entfolgen"; followUserButton.className = "inactive"; isFollowed = true; } }); }); } }; element.appendChild( followUserButton ); if ( currentUser.admin ) { var banButton = document.createElement("BUTTON"); banButton.innerHTML = "BAN!!"; banButton.className = "inactive"; banButton.onclick = function () { alertManager.ask("Achtung: Nutzer sperren!?", function () { socketGateway.emit("banUser", { "userid": id }, function () { currentHome.reloadStream(); }); }); }; element.appendChild( banButton ); } } }; var userInRoom = function (room) { var member, members = room.members; var i = 0, userFound = false; while(i < members.length && !userFound){ member = members[i]; if(member.userid == id && ["canceled", "blocked"].indexOf(member.status) !== -1){ userFound = true; } i++; } return userFound; }; var selectButton = function (button) { var buttons = document.getElementsByClassName("profile-action selected"); var i, l = buttons.length; for (i = 0; i < l; i++) { buttons[i].className = buttons[i].className.replace('selected', ''); } button.className = button.className + " selected"; }; var isOwnProfile = function () { return id === viewerid; }; var userHasViewPermission = function () { return permission_required == null || currentUser["allowed_permissions"][permission_required] ; //== "Y" }; var clearViewScreen = function () { while (viewElement.firstChild) { viewElement.removeChild(viewElement.firstChild); } profile.currentScreen = undefined; }; var createMentionInput = function () { if (postEditor == null) { postEditorInput.type = "file"; postEditorInput.className = "infostream-input"; postEditor = new MainPostEditor(id, postEditorInput, false, [], [], [], null, false); postEditor.init(); postEditor.mentionedUsers.push({"id": id, "name": username}); postEditor.textField.value = '@' + username + ' '; postEditor.onPost(function (args) { args["origin"] = "profile"; socketGateway.emit("addPost", args, function (args) { //todo go to profile mentions!!! /* profile.currentScreen.addPostAtBeginning({ "postid": args.id, "posterName": username, "posterid": id, "readerid": id, "timestamp": args.timestamp, "text": args.text, "attachments": args.attachments, "tags": args.tags, "stocks": args.stocks, "edited": false, "picturePath": args.picturePath }); */ }); }); } viewElement.appendChild(postEditorInput); }; var createCommentsScreen = function () { //if ( currentUser.id == undefined ) { return; } numberOfPostsShown = 10; clearViewScreen(); var tabs_selector = document.createElement("DIV"); tabs_selector.className = "home-subheader"; viewElement.appendChild(tabs_selector); var key, tab; for ( key in pinnwandTypes ) { tab = document.createElement("button"); tab.textContent = pinnwandTypes[key]; tab.className = "submenu-bar-button" + ( key == pinnwandType ? " selected" : "" ); tab.onclick = function( event ){ var selected_tabs = document.getElementsByClassName("submenu-bar-button selected"); var i, l = selected_tabs.length; for (i = 0; i < l; i++) { selected_tabs[i].className = selected_tabs[i].className.replace('selected', ''); } this.tab.className += " selected"; pinnwandType = this.key; numberOfPostsShown = 10; fetchUserPinnwand(function (posts) { try { viewElement.removeChild( profile.currentScreen.element ); } catch (e) {} profile.currentScreen = new InfoStream(username, viewerid, id); viewElement.appendChild(profile.currentScreen.element); profile.currentScreen.buildInfoStream(posts); }); event.preventDefault(); event.stopPropagation(); }.bind( { tab : tab, key : key } ) tabs_selector.appendChild( tab ); } profile.currentScreen = new InfoStream(username, viewerid, id); if (!isOwnProfile() && !args.is_bot && currentUser.id ) { createMentionInput(); } viewElement.appendChild(profile.currentScreen.element); viewElement.appendChild(loadingContainer); fetchUserPinnwand(function (posts) { profile.currentScreen.buildInfoStream(posts); }); }; var createChartTweetsScreen = function () { //if ( currentUser.id == undefined ) { return; } numberOfPostsShown = 10; clearViewScreen(); profile.currentScreen = new InfoStream(username, viewerid, id); //if (!isOwnProfile() && !args.is_bot && currentUser.id ) { createMentionInput(); } viewElement.appendChild(profile.currentScreen.element); viewElement.appendChild(loadingContainer); fetchUserChartTweets(function (tweets) { profile.currentScreen.buildTweetsStream(tweets); }); }; /*var createFollowedUserPostsScreen = function () { numberOfPostsShown = 10; clearViewScreen(); profile.currentScreen = new InfoStream(username, viewerid); viewElement.appendChild(profile.currentScreen.element); viewElement.appendChild(loadingContainer); fetchFollowedUserPosts(function (posts) { profile.currentScreen.buildInfoStream(posts); }); profile.deactivateOnScroll(); profile.activateOnScroll("followedUser"); }; */ /* var createMentionsScreen = function () { numberOfPostsShown = 10; clearViewScreen(); profile.currentScreen = new InfoStream(username, viewerid); if (!isOwnProfile()) { createMentionInput(); } viewElement.appendChild(profile.currentScreen.element); viewElement.appendChild(loadingContainer); if (userHasViewPermission()) { fetchMentionStream(function (posts) { profile.currentScreen.buildInfoStream(posts); }); } else { helper.createAdsWindow( permsLinks[permission_required].img, permsLinks[permission_required].order ) } }; */ var createGroupsScreen = function () { profile.deactivateOnScroll(); if ( currentUser.id == undefined ) { return; } clearViewScreen(); profile.currentScreen = new UserGroupsScreen(id, viewerid); viewElement.appendChild(profile.currentScreen.element); }; var createFollowsScreen = function () { if ( currentUser.id == undefined ) { return; } numberOfPostsShown = 10; clearViewScreen(); var tabs_selector = document.createElement("DIV"); tabs_selector.className = "home-subheader"; viewElement.appendChild(tabs_selector); //todo create tabs selector; var key, tab; for ( key in followTypes ) { tab = document.createElement("button"); tab.textContent = followTypes[key]; tab.className = "submenu-bar-button" + ( key == followType ? " selected" : "" ); tab.onclick = function( event ){ var selected_tabs = document.getElementsByClassName("submenu-bar-button selected"); var i, l = selected_tabs.length; for (i = 0; i < l; i++) { selected_tabs[i].className = selected_tabs[i].className.replace('selected', ''); } this.tab.className += " selected"; followType = this.key; createFollowsScreen(); event.preventDefault(); event.stopPropagation(); }.bind( { tab : tab, key : key } ) tabs_selector.appendChild( tab ); } profile.deactivateOnScroll(); if ( followType == "traders" ) { profile.currentScreen = new FollowsScreen(id, viewerid); viewElement.appendChild(profile.currentScreen.element); } else if ( followType == "posts" ) { profile.currentScreen = new InfoStream(username, viewerid); viewElement.appendChild(profile.currentScreen.element); viewElement.appendChild(loadingContainer); fetchFollowedUserPosts(function (posts) { profile.currentScreen.buildInfoStream(posts); }); profile.activateOnScroll("followedUser"); } }; var createFollowerScreen = function () { profile.deactivateOnScroll(); if ( currentUser.id == undefined ) { return; } clearViewScreen(); profile.currentScreen = new FollowerScreen(id, viewerid); viewElement.appendChild(profile.currentScreen.element); }; var createBlockedScreen = function () { profile.deactivateOnScroll(); if ( currentUser.id == undefined ) { return; } clearViewScreen(); profile.currentScreen = new BlockedTradersScreen(id, viewerid); viewElement.appendChild(profile.currentScreen.element); }; var createInterestedScreen = function () { profile.deactivateOnScroll(); if ( currentUser.id == undefined ) { return; } numberOfPostsShown = 10; clearViewScreen(); profile.currentScreen = new InfoStream(username, viewerid); viewElement.appendChild(profile.currentScreen.element); fetchInterestingPosts(function (posts) { profile.currentScreen.buildInfoStream(posts); }); profile.activateOnScroll('interesting'); }; var createMediaScreen = function () { profile.deactivateOnScroll(); if ( currentUser.id == undefined ) { return; } numberOfPostsShown = 10; clearViewScreen(); var tabs_selector = document.createElement("DIV"); tabs_selector.className = "home-subheader"; viewElement.appendChild(tabs_selector); var key, tab; for ( key in mediaTypes ) { tab = document.createElement("button"); tab.textContent = mediaTypes[key]; tab.className = "submenu-bar-button" + ( key == mediaType ? " selected" : "" ); tab.onclick = function( event ){ var selected_tabs = document.getElementsByClassName("submenu-bar-button selected"); var i, l = selected_tabs.length; for (i = 0; i < l; i++) { selected_tabs[i].className = selected_tabs[i].className.replace('selected', ''); } this.tab.className += " selected"; mediaType = this.key; numberOfPostsShown = 10; fetchMediaPosts(function (posts) { try { viewElement.removeChild( profile.currentScreen.element ); } catch (e) {} profile.currentScreen = new InfoStream(username, viewerid); viewElement.appendChild(profile.currentScreen.element); profile.currentScreen.buildInfoStream(posts); }); event.preventDefault(); event.stopPropagation(); }.bind( { tab : tab, key : key } ) tabs_selector.appendChild( tab ); } profile.currentScreen = new InfoStream(username, viewerid ); viewElement.appendChild(profile.currentScreen.element); fetchMediaPosts( function (posts) { profile.currentScreen.buildInfoStream(posts); } ); profile.activateOnScroll('media'); }; var createWikifolioScreen = function () { profile.deactivateOnScroll(); clearViewScreen(); var wrapper = document.createElement("DIV"); wrapper.className = "followScreen groups-container"; var title = document.createElement("H2"); title.className = "title"; title.textContent = "Wikifolios"; var content = document.createElement("DIV"); content.className = "followScreen group-table"; wrapper.appendChild( title ); wrapper.appendChild( content ); if ( true || !currentUser.allowed_permissions['wikifolio'] ) { var promote = document.createElement("DIV"); promote.className = "group-element"; promote.innerHTML = '
Um Wikifolios im Messenger zu bewerben, benötigen Sie eine "TraderFox-Wikifolio-Lizenz" für 19€ pro Monat.
' + 'Ihre Messenger-Profil wird dann in jeden Beitrag mit einem Button "Wikifolios" erweitert
'; content.appendChild( promote ); } socketGateway.emit("getUserWikifolios", { "id": args.profileid }, function (response) { var link = "https://www.wikifolio.com/en/int/w/", wrap, url; if ( response.result ) { for ( var i = 0; i < response.data.length; i++ ) { url = link + response.data[i].data; wrap = document.createElement("DIV"); wrap.className = "group-element"; wrap.innerHTML = '
'+ url +'
'; content.appendChild( wrap ); } } }) //todo emit to get the licences viewElement.appendChild(wrapper); }; var createStreamsScreen = function () { //getUserStreams profile.deactivateOnScroll(); numberOfPostsShown = 10; clearViewScreen(); if ( currentUser.id == id ) { var info_stream = document.createElement("DIV"); info_stream.className = "groups-container"; info_stream.style.marginBottom = "5px"; info_stream.style.padding = "5px"; info_stream.innerHTML = "
Du kannst den TraderFox-Messenger nutzen, um schnell Inhalte für Webseiten etc. zu produzieren. " + "Die Streams sind zunächst privat. Nur du Kannst darin schreiben. Entscheide dann, wo du sie veröffentlichst. " + "Charts aus dem TraderFox Trading-Desk kannst du direkt in deinen Stream teilen.
"; viewElement.appendChild(info_stream); var create_stream_button = document.createElement("button"); create_stream_button.style.background = "green"; create_stream_button.style.color = "white"; create_stream_button.style.padding = "5px"; create_stream_button.style.marginLeft = "0px"; create_stream_button.style.float = "left"; create_stream_button.style.clear = "both"; create_stream_button.textContent = "Create new Stream"; create_stream_button.onclick = function(){ create_stream_menu.style.display = "block"; create_stream_button.style.display = "none"; } var create_stream_menu = document.createElement("DIV"); create_stream_menu.style.width = "100%"; create_stream_menu.style.display = "none"; create_stream_menu.style.float = "left"; var name_title = document.createElement("DIV"); name_title.style.float = "left"; name_title.style.clear = "both"; name_title.textContent = "Name: "; create_stream_menu.appendChild( name_title ); var name_input = document.createElement("INPUT") name_input.type = "text"; name_input.style.float = "left"; name_input.style.clear = "both"; name_input.style.border = "1px solid"; name_input.style.borderRadius = "4px"; name_input.style.minWidth = "250px"; create_stream_menu.appendChild( name_input ); var description_title = document.createElement("DIV"); description_title.style.float = "left"; description_title.style.clear = "both"; description_title.textContent = "Description: "; create_stream_menu.appendChild( description_title ); var description_input = document.createElement("TEXTAREA"); description_input.style.float = "left"; description_input.style.clear = "both"; description_input.style.border = "1px solid"; description_input.style.borderRadius = "4px"; description_input.style.minWidth = "250px"; create_stream_menu.appendChild( description_input ); var submit_button = document.createElement("button"); submit_button.style.background = "green"; submit_button.style.color = "white"; submit_button.style.padding = "5px"; submit_button.style.marginLeft = "0px"; submit_button.style.float = "left"; submit_button.style.clear = "both"; submit_button.textContent = "Save Stream"; submit_button.onclick = function(event){ if ( name_input.value != "" ) { create_stream_menu.style.display = "none"; create_stream_button.style.display = "block"; socketGateway.emit("createUserStream", { "name": name_input.value, "description" : description_input.value }, function (response) { if ( response.result ) { selectedStream = response.id; profile.selectTab("streams"); currentHome.api.sendEvent( { 'type' : 'notification', 'event' : 'update-streams', 'value' : '' } ) } }) } else { currentHome.showUserFeedback( 'Name can not be empty.', event.clientX, event.clientY - 35 ) } } create_stream_menu.appendChild(submit_button); info_stream.appendChild(create_stream_button); info_stream.appendChild(create_stream_menu); } var tabs_selector = document.createElement("DIV"); tabs_selector.className = "home-subheader"; viewElement.appendChild(tabs_selector); viewElement.appendChild(stream_menu_section); viewElement.appendChild(stream_input_section); socketGateway.emit("getUserStreams", { "userid": id, "secret" : streamSecret }, function (response) { if ( response.result ) { var tabs_by_stream = {}; var tab, i, l = response.data.length; for ( i = 0; i < l; i++ ) { if ( selectedStream == null ) { selectedStream = response.data[i].id; } if ( streamSecret != null && response.data[i].secret == streamSecret ) { selectedStream = response.data[i].id; } tab = document.createElement("button"); tab.textContent = response.data[i].name; tab.className = "submenu-bar-button"; tab.onclick = function( event ){ var selected_tabs = document.getElementsByClassName("submenu-bar-button selected"); var i, l = selected_tabs.length; for (i = 0; i < l; i++) { selected_tabs[i].className = selected_tabs[i].className.replace('selected', ''); } this.tab.className += " selected"; selectedStream = this.id; numberOfPostsShown = 10; fetchStreamPosts(function (posts) { try { viewElement.removeChild( profile.currentScreen.element ); } catch (e) {} profile.currentScreen = new InfoStream(username, viewerid); viewElement.appendChild(profile.currentScreen.element); createStreamMenuSection(); profile.currentScreen.buildInfoStream(posts); }); event.preventDefault(); event.stopPropagation(); }.bind( { tab : tab, id : response.data[i].id } ) tabs_selector.appendChild( tab ); tabs_by_stream[response.data[i].id] = tab; } if ( tabs_by_stream[selectedStream] != null ) { tabs_by_stream[selectedStream].click(); } } }); }; var createStreamMenuSection = function(){ stream_menu_section.textContent = ""; stream_input_section.textContent = ""; var container = document.createElement("DIV") container.className = "group-element"; container.style.border = "0"; stream_menu_section.appendChild(container); socketGateway.emit("getStream", { "streamid": selectedStream, "secret" : streamSecret }, function (response) { if ( response.result ) { var stream = response.data; var name = document.createElement("div"); name.className = "name"; name.textContent = stream.name; container.appendChild( name ); var description = document.createElement("div"); description.className = "description"; description.textContent = stream.description != null ? stream.description : ""; container.appendChild( description ); if ( stream.userid == currentUser.id ) { //todo implement stream admin setting menus var update_name = document.createElement("button"); update_name.textContent = "Speichern"; update_name.style.float = "left"; update_name.style.background = "green"; update_name.style.color = "white"; update_name.style.display = "none"; update_name.onclick = function(){ socketGateway.emit( "updateStreamName", { streamid : stream.id, value : name.textContent }, function(){} ) currentHome.api.sendEvent( { 'type' : 'notification', 'event' : 'update-streams', 'value' : '' } ) update_name.style.display = "none"; name.contentEditable = false; edit_name.style.display = "block"; } var edit_name = document.createElement("button"); edit_name.textContent = "Edit name"; edit_name.style.float = "left"; edit_name.onclick = function(){ name.contentEditable = true; update_name.style.display = "block"; name.focus() edit_name.style.display = "none"; } var update_description = document.createElement("button"); update_description.textContent = "Speichern"; update_description.style.float = "left"; update_description.style.background = "green"; update_description.style.color = "white"; update_description.style.display = "none"; update_description.onclick = function(){ socketGateway.emit( "updateStreamDescription", { streamid : stream.id, value : description.textContent }, function(){} ) update_description.style.display = "none"; description.contentEditable = false; edit_description.style.display = "block"; } var edit_description = document.createElement("button"); edit_description.textContent = "Edit description"; edit_description.style.float = "left"; edit_description.onclick = function(){ description.contentEditable = true; description.focus(); update_description.style.display = "block"; edit_description.style.display = "none"; } container.insertBefore(update_name, name.nextSibling); container.insertBefore(edit_name, update_name.nextSibling); container.insertBefore(update_description, description.nextSibling); container.insertBefore(edit_description, update_description.nextSibling); //is_public toggle var is_public_wrapper = document.createElement("DIV"); is_public_wrapper.style.marginTop = "10px"; is_public_wrapper.style.float = "left"; is_public_wrapper.style.clear = "both"; is_public_wrapper.style.width = "100%"; var tag = document.createElement("DIV"); tag.style.cursor = "default"; tag.style.float = "left"; tag.style.marginLeft = "5px"; tag.textContent = "Inhalte in den Öffentlichen Chat und in meine Profilseite mit einfließen lassen"; var check = document.createElement("input"); check.type = "checkbox"; check.style.float = "left"; check.style.marginTop = "3px"; if ( stream.is_public ) { check.checked = true; } check.onchange = function() { socketGateway.emit( "setIsPublicStream", { streamid : stream.id, is_public : check.checked }, function(){} ) } is_public_wrapper.appendChild( check ); is_public_wrapper.appendChild( tag ); container.appendChild(is_public_wrapper); var share_url_wrapper = document.createElement("DIV") share_url_wrapper.style.float = "left"; share_url_wrapper.style.clear = "both"; share_url_wrapper.style.width = "100%"; share_url_wrapper.style.marginTop = "10px"; var link = "https://messenger.traderfox.com/streams/" + stream.secret; var link_text = document.createElement("DIV"); link_text.className = "description"; link_text.style.cursor = "default"; link_text.style.float = "left"; link_text.innerHTML = "Diesen Stream per URL teilen und für andere lesbar machen "+link+""; var reset_secret = document.createElement("BUTTON") reset_secret.textContent = "Reset secret"; reset_secret.style.float = "left"; reset_secret.style.backgroundColor = "red"; reset_secret.style.color = "white"; reset_secret.style.marginTop = "0px"; reset_secret.onclick = function( event ){ //emit reset! socketGateway.emit("resetStreamSecret", { streamid : stream.id } , function () { createStreamMenuSection(); }) } share_url_wrapper.appendChild( link_text ); share_url_wrapper.appendChild( reset_secret ); container.appendChild(share_url_wrapper); var embed_url_wrapper = document.createElement("DIV") embed_url_wrapper.style.float = "left"; embed_url_wrapper.style.clear = "both"; embed_url_wrapper.style.width = "100%"; embed_url_wrapper.style.marginTop = "10px"; embed_url_wrapper.className = "description"; var embed_url = ''; var embed_text = document.createElement("DIV"); embed_text.style.cursor = "default"; embed_text.style.float = "left"; embed_text.style.marginTop = "5px"; embed_text.style.padding = "10px"; embed_text.style.border = "1px solid"; embed_text.style.borderRadius = "3px"; embed_text.style.clear = "both"; embed_text.textContent = embed_url; var embed_title = document.createElement("DIV"); embed_title.style.cursor = "default"; embed_title.style.float = "left"; embed_title.style.clear = "both"; embed_title.textContent = "Stream einbetten in Website"; embed_url_wrapper.appendChild( embed_title ); embed_url_wrapper.appendChild( embed_text ); container.appendChild(embed_url_wrapper); var input_container = document.createElement("DIV") input_container.style.border = "0"; stream_input_section.appendChild(input_container); var input_element = createStreamInput(stream.id); input_element.style.marginTop = "15px"; input_container.appendChild(input_element); } } } ) }; var createStreamInput = function(streamid){ var input = document.createElement("DIV"); input.type = "file"; input.className = "infostream-input"; postEditor = new MainPostEditor(id, input, false, [], [], [], null, true, true); postEditor.init(); postEditor.onPost( function (args) { args["streamid"] = streamid; socketGateway.emit("addStreamPost", args, function (args) { profile.currentScreen.addPostAtBeginning({ "postid": args.id, "posterName": username, "posterid": id, "readerid": id, "timestamp": args.timestamp, "text": args.text, "title": args.title, "attachments": args.attachments, "tags": args.tags, "stocks": args.stocks, "news": args.news, "cloud": args.cloud, "replies": [], "edited": false, "picturePath": args.picturePath, "nice_title" : args.nice_title }); }); } ); return input; }; var createSettingsScreen = function () { profile.deactivateOnScroll(); if ( currentUser.id == undefined ) { return; } clearViewScreen(); profile.currentScreen = new SettingsScreen(); viewElement.appendChild(profile.currentScreen.element); }; var createStreamSettingsScreen = function () { profile.deactivateOnScroll(); if ( currentUser.id == undefined ) { return; } clearViewScreen(); profile.currentScreen = new StreamSettingsScreen(); viewElement.appendChild(profile.currentScreen.element); }; var createAdminScreen = function () { profile.deactivateOnScroll(); if ( currentUser.id == undefined ) { return; } clearViewScreen(); profile.currentScreen = new AdminScreen(); viewElement.appendChild(profile.currentScreen.element); }; var createNotificationsScreen = function () { if ( currentUser.id == undefined ) { return; } clearViewScreen(); profile.deactivateOnScroll(); profile.currentScreen = new NotificationsScreen(); viewElement.appendChild(profile.currentScreen.element); alreadyFetching = true; profile.currentScreen.createUI( function( data ) { alreadyFetching = false; moreToFetch = data["moreToFetch"]; } ) profile.activateOnScroll('notificationsTicker'); }; var fetchUserPinnwand = function (callback) { alreadyFetching = true; var loading = document.createElement("DIV"); loading.textContent = "Loading more..."; loadingContainer.className = "loading-more"; loadingContainer.appendChild(loading); socketGateway.emit("loadUserPinnwand", {"id": id, "numberOfPostsShown": numberOfPostsShown, "type" : pinnwandType}, function (data) { moreToFetch = data["moreToFetch"]; loadingContainer.removeChild(loading); alreadyFetching = false; callback(data["posts"]); }); }; var fetchUserChartTweets = function (callback) { alreadyFetching = true; var loading = document.createElement("DIV"); loading.textContent = "Loading more..."; loadingContainer.className = "loading-more"; loadingContainer.appendChild(loading); socketGateway.emit("loadUserChartTweets", {"id": id, "numberOfPostsShown": numberOfPostsShown }, function (data) { moreToFetch = data["moreToFetch"]; loadingContainer.removeChild(loading); alreadyFetching = false; callback(data["chartTweets"]); }); }; var fetchMentionStream = function (callback) { alreadyFetching = true; var loading = document.createElement("DIV"); loading.textContent = "Loading more..."; loadingContainer.className = "loading-more"; loadingContainer.appendChild(loading); socketGateway.emit("loadUserProfileMentions", { "id": id, "numberOfPostsShown": numberOfPostsShown }, function (data) { moreToFetch = data["moreToFetch"]; loadingContainer.removeChild(loading); alreadyFetching = false; callback(data["posts"]); }); }; var fetchMoreNotificationsForTicker = function() { alreadyFetching = true; profile.currentScreen.onScroll( function( data ){ alreadyFetching = false; moreToFetch = data["moreToFetch"]; } ); }; var fetchFollowedUserPosts = function (callback) { alreadyFetching = true; var loading = document.createElement("DIV"); loading.textContent = "Loading more..."; loadingContainer.className = "loading-more"; loadingContainer.appendChild(loading); socketGateway.emit("loadFollowedUserPosts", {"numberOfPostsShown": numberOfPostsShown, "userid" : id }, function (data) { moreToFetch = data["moreToFetch"]; loadingContainer.removeChild(loading); alreadyFetching = false; callback(data["posts"]); }); }; var fetchInterestingPosts = function (callback) { alreadyFetching = true; var loading = document.createElement("DIV"); loading.textContent = "Loading more..."; loadingContainer.className = "loading-more"; loadingContainer.appendChild(loading); socketGateway.emit("loadUserInterestingPosts", {"numberOfPostsShown": numberOfPostsShown, "userid" : id}, function (data) { moreToFetch = data["moreToFetch"]; loadingContainer.removeChild(loading); alreadyFetching = false; callback(data["posts"]); }); }; var fetchMediaPosts = function (callback) { alreadyFetching = true; var loading = document.createElement("DIV"); loading.textContent = "Loading more..."; loadingContainer.className = "loading-more"; loadingContainer.appendChild(loading); socketGateway.emit("loadUserMediaPosts", {"numberOfPostsShown": numberOfPostsShown, "userid" : id, "type" : mediaType}, function (data) { moreToFetch = data["moreToFetch"]; loadingContainer.removeChild(loading); alreadyFetching = false; callback(data["posts"]); }); }; var fetchStreamPosts = function (callback) { alreadyFetching = true; var loading = document.createElement("DIV"); loading.textContent = "Loading more..."; loadingContainer.className = "loading-more"; loadingContainer.appendChild(loading); // secret works. need to be taken from URL. socketGateway.emit("loadUserStreamPosts", {"numberOfPostsShown": numberOfPostsShown, "userid" : id, "streamid" : selectedStream, "secret" : streamSecret }, function (data) { moreToFetch = data["moreToFetch"]; loadingContainer.removeChild(loading); alreadyFetching = false; callback(data["posts"]); }); }; var getScrollDimensions = function () { var dimensions = {}; if ( profile.element.parentNode != null ) { dimensions["fullHeight"] = profile.element.parentNode.scrollHeight; dimensions["scrollTop"] = profile.element.parentNode.scrollTop; dimensions["clientHeight"] = profile.element.parentNode.clientHeight; dimensions["currentHeight"] = dimensions["scrollTop"] + dimensions["clientHeight"]; } else { dimensions = null; } return dimensions; }; profile.activateOnScroll = function (type) { profile.element.parentNode.onscroll = function ( force ) { var dimensions = getScrollDimensions(); if ( force === true || dimensions != null ) { if ( force === true || dimensions["currentHeight"] >= dimensions["fullHeight"]) { if (!alreadyFetching && moreToFetch) { numberOfPostsShown += 10; if (type == 'comments') { fetchUserPinnwand(function (data) { profile.currentScreen.addOlderToInfoStream(data); }); } if (type == 'charttweets') { fetchUserChartTweets(function (data) { profile.currentScreen.addOlderToTweetsStream(data); }); } else if (type == 'interesting') { fetchInterestingPosts(function (data) { profile.currentScreen.addOlderToInfoStream(data); }); } else if (type == 'media') { fetchMediaPosts(function (data) { profile.currentScreen.addOlderToInfoStream(data); }); } else if(type === "followedUser"){ fetchFollowedUserPosts(function (data) { profile.currentScreen.addOlderToInfoStream(data); }) } else if (type === "notificationsTicker"){ fetchMoreNotificationsForTicker(); } } } } }; }; profile.deactivateOnScroll = function () { profile.element.parentNode.onscroll = null; }; profile.selectTab = function( tab ) { if( buttons[tab] != undefined ){ buttons[tab].click(); selected_tab = tab; } if ( ["comments", "public"].indexOf(tab) != -1 ) { hidePersonalLinks(); } else { showPersonalLinks(); } }; createUI(); //createCommentsScreen(); currentHome.api.sendEvent( { 'type' : 'url', 'event' : 'path', 'value' : '/user/' + args.name_url } ) return profile; } /* Used to be a class that was showing and changing the picture of a user. It was replaced by PictureUploader and is currently obsolete, used only to show the picture. */ function ProfilePictureManager(args) { var profilePictureManager = {}; profilePictureManager.image = document.createElement("IMG"); profilePictureManager.image.className = "img-profile-picture"; profilePictureManager.image.height = 72; profilePictureManager.image.width = 72; if(args.picturePath){ profilePictureManager.image.src = projectDomain + args.picturePath; } args.element.appendChild(profilePictureManager.image); profilePictureManager.createFileUploadButton = function () { if(args.isOwnProfile){ var fileUploadContainer = document.createElement("DIV"); fileUploadContainer.textContent = "Change"; fileUploadContainer.className = "change-image-button selected"; fileUploadContainer.style.cursor = "default"; var fileUploadButton = document.createElement("INPUT"); fileUploadButton.type = "file"; fileUploadButton.accept = ".jpg,.gif,.png,.jpeg"; fileUploadButton.id = "change-picture"; fileUploadButton.style.cssText = "opacity: 0; position: relative; width: 100%; z-index: 1; float: left;"; fileUploadButton.onchange = function (event) { var data = event.target.files; var uploader = new UploadCreator(); uploader.createFileUpload(data[0], function (fileObject) { if ( !fileObject.result ) { alertManager.inform(fileObject.message) } else { profilePictureManager.emitPicture(fileObject); } }); }; args.element.appendChild(fileUploadButton); args.element.appendChild(fileUploadContainer); } }; profilePictureManager.emitPicture = function (fileObject) { socketGateway.emit("uploadProfilePicture", fileObject); //no callback, the server emits the response and Home receives it }; return profilePictureManager; } /* Child of TradersScreen. Shows traders that have been blocked from the user. */ function BlockedTradersScreen(id, viewerid) { var blockedTraderScreen = new TradersScreen("Blocked Traders"); socketGateway.emit("loadBlockedTraders", id, function (data) { var i, dataLength = data.length; if (dataLength > 0) { blockedTraderScreen.createTableHeader(); for (i = 0; i < dataLength; i++) { blockedTraderScreen.createTrader(data[i], id, viewerid, 'blocked'); } } }); return blockedTraderScreen; } /* The settings of a user. Contains email-subscriptions and a way to change the user picture. */ function SettingsScreen() { this.element = document.createElement("DIV"); this.createUI(); this.pictureUploader; } SettingsScreen.prototype.createUI = function () { this.createCheckboxes(); if( environment === "messenger" ){ this.createMessengerSettings(); } this.createProfilePictureManager(); this.createNicknameManager(); }; SettingsScreen.prototype.createMessengerSettings = function () { var container = document.createElement("DIV"); container.className = "traderchat-settings-container"; var title = document.createElement("DIV"); title.textContent = "Traderfox Messenger default theme"; title.className = "traderchat-checkbox-title"; var selector = document.createElement("select"); selector.style.padding = "2px 2px"; selector.style.margin = "5px 10px"; var i, option, themes = ["dark", "light"] for ( i = 0; i < themes.length; i++ ) { option = document.createElement("option"); option.value = themes[i]; option.textContent = themes[i]; option.selected = themes[i] == currentUser.messenger_settings["theme"]; selector.appendChild( option ); } selector.onchange = function (event) { socketGateway.emit("updateMessengerSettings", { "key": "theme", "value": event.target.value}, function (response) { currentUser.messenger_settings["theme"] = event.target.value; currentHome.api.sendEvent( { 'type' : 'settings', 'event' : 'theme', 'value' : currentUser.messenger_settings["theme"] } ) }); event.stopPropagation(); }; container.append( title, selector ); this.element.appendChild( container ) }; SettingsScreen.prototype.createCheckboxes = function () { var checkboxSearchable = this.createCheckboxWithTitle(this.element, currentUser.visible, "Am Chat teilnehmen und für andere sichtbar sein", "Wenn diese Funktion deaktiviert ist, bedeutet das:
" + " - Sie können NICHT per privater Nachricht angeschrieben werden
" + " - Sie können über die suche NICHT gefunden werden
" + " - Sie können NICHT zu Teams eingeladen werden
" + " - Ihr Profil-Seite im Chat ist für NIEMANDEN einsehbar außer für Sie selbst
"); checkboxSearchable.onclick = function (event) { event.preventDefault(); socketGateway.emit("changeSettings", {"setting": "visible", "status": !currentUser.visible}, function (reply) { currentUser.visible = reply; event.target.checked = reply; }); }; var checkboxEmailChatMentions = this.createCheckboxWithTitle(this.element, currentUser.mention_email, "Email-Benachrichtigung, wenn mich jemand erwähnt"); checkboxEmailChatMentions.onclick = function (event){ event.preventDefault(); socketGateway.emit("changeSettings", {"setting": "mention_email", "status": !currentUser.mention_email}, function (reply) { currentUser.mention_email = reply; event.target.checked = reply; }); }; var checkboxEmailProfileMentions = this.createCheckboxWithTitle(this.element, currentUser.profile_mention_email, "Email-Benachrichtigung, wenn jemand an meine Pinnwand schreibt"); checkboxEmailProfileMentions.onclick = function (event) { event.preventDefault(); socketGateway.emit("changeSettings", {"setting": "profile_mention_email", "status": !currentUser.profile_mention_email}, function (reply) { currentUser.profile_mention_email = reply; event.target.checked = reply; }); }; var checkboxEmailOfflineChat = this.createCheckboxWithTitle(this.element, currentUser.offline_chat_email, "Email-Benachrichtigung bei neuer privater Nachricht, wenn ich offline bin"); checkboxEmailOfflineChat.onclick = function (event) { event.preventDefault(); socketGateway.emit("changeSettings", {"setting": "offline_chat_email", "status": !currentUser.offline_chat_email}, function (reply) { currentUser.offline_chat_email = reply; event.target.checked = reply; }); }; var checkboxEODRoomsEmail = this.createCheckboxWithTitle(this.element, currentUser.eod_rooms_email, "Email-Benachrichtigung am Ende des Tages über neue Nachrichten in meinen Teams"); checkboxEODRoomsEmail.onclick = function (event) { event.preventDefault(); socketGateway.emit("changeSettings", {"setting": "eod_rooms_email", "status": !currentUser.eod_rooms_email}, function (reply) { currentUser.eod_rooms_email = reply; event.target.checked = reply; }); }; var checkboxEODGroupsEmail = this.createCheckboxWithTitle(this.element, currentUser.eod_groups_email, "Email-Benachrichtigung jeden Tag um 20 Uhr über neue Nachrichten in meinen Gruppen"); checkboxEODGroupsEmail.onclick = function (event) { event.preventDefault(); socketGateway.emit("changeSettings", {"setting": "eod_groups_email", "status": !currentUser.eod_groups_email}, function (reply) { currentUser.eod_groups_email = reply; event.target.checked = reply; }); }; }; SettingsScreen.prototype.createCheckboxWithTitle = function (parent, isSelected, titleName, description) { var checkboxContainer = document.createElement("DIV"); checkboxContainer.className = "traderchat-settings-container"; var title = document.createElement("DIV"); title.textContent = titleName; title.className = "traderchat-checkbox-title"; var checkbox = document.createElement("INPUT"); checkbox.type = "checkbox"; checkbox.checked = isSelected; checkbox.style.marginTop = "5px"; checkbox.className = "traderchat-checkbox"; checkboxContainer.appendChild(checkbox); checkboxContainer.appendChild(title); if ( description ) { var description_container = document.createElement("DIV"); description_container.className = "traderchat-checkbox-title"; description_container.style.clear = "both"; description_container.style.marginLeft = "35px"; description_container.innerHTML = description; checkboxContainer.appendChild(description_container); } parent.appendChild(checkboxContainer); return checkbox; }; SettingsScreen.prototype.createProfilePictureManager = function () { this.pictureUploader = new PictureUploader({ startingPicture: projectDomain + currentUser.picture, viewport: { width: 75, height: 75 }, boundary: { width: 130, height: 130 } }); this.pictureUploader.onUploadReady(this, function (fileObject) { socketGateway.emit("uploadProfilePicture", fileObject); }); this.pictureUploader.createChangeButton(); this.pictureUploader.createCropper(); var pictureUploaderContainer = document.createElement("DIV"); pictureUploaderContainer.className = "traderchat-settings-container"; pictureUploaderContainer.style.width = "calc( 50% - 20px )"; pictureUploaderContainer.appendChild(this.pictureUploader.element); this.element.appendChild(pictureUploaderContainer); }; SettingsScreen.prototype.createNicknameManager = function () { var nicknameContainer = document.createElement("DIV"); nicknameContainer.className = "traderchat-settings-container"; nicknameContainer.style.float = "right"; nicknameContainer.style.padding = "10px 5px"; nicknameContainer.style.width = "calc( 50% - 20px )"; var title = document.createElement("DIV"); title.textContent = "Name ändern"; title.className = "change-image-button selected"; title.style.fontSize = "13px"; title.style.float = "left"; title.style.clear = "both"; title.onclick = function( event ){ event.stopPropagation(); event.preventDefault(); nickname.focus(); } var nickname = document.createElement("DIV"); nickname.textContent = currentUser.username; nickname.style.cursor = "pointer"; nickname.style.fontSize = "15px"; nickname.style.marginLeft = "11px"; nickname.style.float = "left"; nickname.style.clear = "both"; nickname.style.width = "100%"; nickname.contentEditable = true; var updateNickname = document.createElement("button"); updateNickname.innerText = "Speichern"; updateNickname.style.float = "right"; updateNickname.style.padding = "2px 4px"; updateNickname.style.marginTop = "0px"; updateNickname.onclick = function( event ) { socketGateway.emit("changeNickname", nickname.textContent, function( response ) { if ( response.result ) { notif.style.color = "green"; notif.textContent = "Correctly updated. Reload the messenger to display the new nickname."; currentUser.username = nickname.textContent; currentHome.api.sendEvent( { 'type' : 'notification', 'event' : 'update-user', 'value' : 'nickname-changed' } ); } else { notif.textContent = response.message; notif.style.color = "red"; } notif.style.display = "block"; setTimeout( function(){ notif.style.display = "none"; }, 8000 ) } ); event.stopPropagation(); event.preventDefault(); } var notif = document.createElement("DIV"); notif.style.fontSize = "11px"; notif.style.float = "left"; notif.style.clear = "both"; notif.style.margin = "10px 11px"; notif.style.display = "none"; var disclaimer = document.createElement("DIV"); disclaimer.innerHTML = "Ihr Nickname kann nur einmal geändert werden. Überlegen Sie sich den Namen gut. Danach können die TraderFox-Admins eine weitere Änderung freigeben.
" + "Wir begrüßen es, wenn Sie unter Ihrem richtigen Namen auftreten."; disclaimer.style.fontSize = "11px"; disclaimer.style.marginLeft = "11px"; disclaimer.style.float = "left"; disclaimer.style.clear = "both"; nicknameContainer.appendChild( title ); nicknameContainer.appendChild( nickname ); nicknameContainer.appendChild( updateNickname ); nicknameContainer.appendChild( notif ); nicknameContainer.appendChild( disclaimer ); this.element.appendChild(nicknameContainer); }; /* The settings of a user. Contains email-subscriptions and a way to change the user picture. */ function NotificationsScreen() { this.element = document.createElement("DIV"); this.element.className = 'notification-ticker'; this.notificationCenter = new NotificationCenter(); this.amount = 50; this.start = 0; this.added = 0; } NotificationsScreen.prototype.onScroll = function ( callback ) { this.start+= this.amount; this.createUI( callback ); }; NotificationsScreen.prototype.createUI = function ( callback ) { // this.element.textContent = "Hallo not"; socketGateway.emit("getNotificationsTicker", { start : this.start, amount : this.amount }, function (data) { var i, l = data.length, type, row, date, added = 0; for (i = 0; i < l; i++) { type = data[i].type; if ( type == 'room-message' && data[i-1] != undefined) { if ( data[i-1].type == 'room-message' && data[i-1].roomid == data[i].roomid ) { continue; } } row = this.notificationCenter.createNotificationRow( { type : type, data : data[i] } ); date = row.getElementsByClassName('date')[0]; date.textContent = helper.timestampToBeauty(data[i].timestamp); this.element.appendChild( row); this.added++; } if ( this.added < 50 && data.length > 0 ) { //Returned something but we do not get the minimum of 50 so we load more while there is some data returned. this.onScroll(callback) } else { if ( callback != undefined ) { callback( { 'moreToFetch' : true } ); } } socketGateway.emit("markAllNotificationsSaw", function(){}); }.bind( this )); }; /* A screen containing three views for rooms, one with every room, one with the 1-1 ones, and one with the *-* ones. It also contains a room creator. */ function RoomsScreen(header, callback, type) { this.element = document.createElement("DIV"); this.element.className = "rooms-screen"; this.containerRooms; this.type = type || 'teams'; this.header = header; this.header.style.height = "50px"; this.roomCreatorContainer; this.roomNameLabel; this.roomName; this.detailsContainer; this.roomMembersDisplay; this.roomMembersInput; this.search; this.searchTerm; this.privateButton; this.roomsButton; this.pending_button; this.roomMembersList = []; this.rooms = []; this.buttons = {}; this.createUI(callback); currentView.setNewView( { type : 'rooms', id : this.type, onChangeView : null } ) } RoomsScreen.prototype.createTeam = function () { this.createRoomButton.click(); }; RoomsScreen.prototype.createUI = function (callback) { this.createRoomsViewToolbar(); this.createRoomAndDiscussionCreators(); this.getUserRooms(function () { this.createRoomList(this.type, callback); this.selectButton(this.buttons[this.type]); }.bind(this)); }; RoomsScreen.prototype.createRoomAndDiscussionCreators = function () { this.detailsContainer = document.createElement("DIV"); this.detailsContainer.className = "details-container"; this.createRoomCreator(); this.createDiscussionCreator(); }; RoomsScreen.prototype.updatePendingCounter = function() { var pending = 0; var i, l = this.rooms.length; for ( i = 0; i < l; i++ ) { if ( this.rooms[i].my_status == "pending" ){ pending++ } } if ( pending == 0 ) { this.pending_button.textContent = "Einladungen"; } else { this.pending_button.textContent = "Einladungen (" + pending + ")"; } }; RoomsScreen.prototype.getUserRooms = function (callback) { socketGateway.emit("getUserRooms", {}, function (rooms) { this.rooms = rooms; callback(); this.updatePendingCounter(); }.bind(this)); }; RoomsScreen.prototype.createRoomsViewToolbar = function () { /*var allButton = document.createElement("BUTTON"); allButton.textContent = "Alle"; allButton.className = "submenu-bar-button selected"; allButton.onclick = function () { this.createRoomList("all"); this.selectButton(allButton); }.bind(this); */ this.privateButton = document.createElement("BUTTON"); this.privateButton.textContent = "Private Nachrichten"; this.privateButton.className = "submenu-bar-button"; this.privateButton.onclick = function () { this.createRoomList("private"); this.selectButton(this.privateButton); }.bind(this); this.roomsButton = document.createElement("BUTTON"); this.roomsButton.textContent = "Teams"; this.roomsButton.className = "submenu-bar-button"; this.roomsButton.onclick = function () { this.createRoomList("teams"); this.selectButton(this.roomsButton); }.bind(this); this.pending_button = document.createElement("BUTTON"); this.pending_button.textContent = "Einladungen"; this.pending_button.className = "submenu-bar-button"; this.pending_button.onclick = function () { this.createRoomList("pending"); this.selectButton( this.pending_button); }.bind(this); this.buttons = { 'private' : this.privateButton, 'teams' : this.roomsButton, 'pending' : this.pending_button } //this.header.appendChild(allButton); this.header.appendChild(this.privateButton); this.header.appendChild(this.roomsButton); this.header.appendChild( this.pending_button); }; RoomsScreen.prototype.selectButton = function (button) { this.deselectButtons(button.className); button.className += " selected"; }; RoomsScreen.prototype.updateSubheaderVisibility = function (type) { if ( type == 'teams' ) { this.createDiscussionButton.style.display = "none"; this.createRoomButton.style.display = "block"; this.privateButton.style.display = "none"; this.roomsButton.style.display = "block"; } else if ( type == 'private' ) { this.createRoomButton.style.display = "none"; this.createDiscussionButton.style.display = "block"; this.roomsButton.style.display = "none"; this.privateButton.style.display = "block"; } else { this.createRoomButton.style.display = "none"; this.createDiscussionButton.style.display = "none"; //this.privateButton.style.display = "block"; //this.roomsButton.style.display = "block"; } }; RoomsScreen.prototype.deselectButtons = function (className) { var buttons = document.getElementsByClassName(className + " selected"); var i, l = buttons.length; for (i = 0; i < l; i++) { if (buttons[i]) { buttons[i].className = buttons[i].className.replace("selected", ""); } } }; RoomsScreen.prototype.createRoomList = function (type, callback) { //this.type = type; this.updateSubheaderVisibility(type); this.getUserRooms( function(){ if(this.containerRooms){ this.element.removeChild(this.containerRooms); } this.containerRooms = document.createElement("DIV"); this.containerRooms.className = "room-list-container"; if ( type == 'pending' ) { var pendings_container = document.createElement("DIV"); var cancelled_container = document.createElement("DIV"); cancelled_container.style.display = 'none'; cancelled_container.style.backgroundColor = '#c15d5d'; var toggle_cancelled = document.createElement("BUTTON"); toggle_cancelled.textContent = "Abgelehnte Einladungen anzeigen"; toggle_cancelled.style.marginTop = "20px"; toggle_cancelled.style.backgroundColor = '#c15d5d'; toggle_cancelled.onclick = function( event ){ if ( cancelled_container.style.display == 'none' ) { cancelled_container.style.display = 'block'; toggle_cancelled.textContent = 'Abgelehnte Einladungen verbergen' } else { cancelled_container.style.display = 'none'; toggle_cancelled.textContent = 'Abgelehnte Einladungen anzeigen' } event.preventDefault(); event.stopPropagation(); } this.containerRooms.appendChild( pendings_container); this.containerRooms.appendChild( toggle_cancelled); this.containerRooms.appendChild( cancelled_container); } var i; for (i = 0; i < this.rooms.length; i++) { var roomData = this.rooms[i]; this.setMyStatusInRoom( roomData ); var roomElement = this.createRoomElement(roomData); if ( roomData.my_status == "joined" ) { if( type === "private" && roomData.private === "Y" ){ this.containerRooms.appendChild(roomElement); } else if( type === "teams" && roomData.private === "N" ){ this.containerRooms.appendChild(roomElement); }/* else if(type === "all" ){ this.containerRooms.appendChild(roomElement); }*/ } else if( type === "pending" && ["pending", "canceled"].indexOf(roomData.my_status) != -1 ){ if ( this.type == 'teams' && roomData.private == 'Y' ) { continue; } if ( this.type == 'private' && roomData.private == 'N' ) { continue; } if ( roomData.my_status == "pending" ) { pendings_container.appendChild(roomElement); } else if ( roomData.my_status == "canceled" ) { cancelled_container.appendChild(roomElement); } } } this.element.appendChild(this.containerRooms); if ( callback ) { callback(); } }.bind( this ) ) }; RoomsScreen.prototype.setMyStatusInRoom = function ( roomData ) { var members = roomData.members; var i, l = members.length; for ( i = 0; i < l; i++ ) { if ( members[i].userid == currentUser.id ) { //me roomData.my_status = members[i].status; return; } } roomData.my_status = 'blocked'; }; RoomsScreen.prototype.createRoomCreator = function () { this.createRoomButton = document.createElement("BUTTON"); this.createRoomButton.className = "submenu-bar-button"; this.createRoomButton.id = "submenu-bar-button-id"; this.createRoomButton.style.height = "20px"; this.createRoomButton.style.top = "10px"; this.createRoomButton.textContent = "+ Team"; this.header.appendChild(this.createRoomButton); this.createRoomButton.onclick = function () { if( this.containerRooms ) { this.element.removeChild(this.containerRooms); } this.selectButton(this.createRoomButton); this.containerRooms = document.createElement("DIV"); this.containerRooms.className = "room-list-container"; this.roomNameLabel = document.createElement("DIV"); this.roomNameLabel.className = "room-name-label"; this.roomNameLabel.textContent = "Team-Namen bestimmen"; this.roomName = document.createElement("INPUT"); this.roomName.className = "room-name-input"; this.roomMembersLabel = document.createElement("DIV"); this.roomMembersLabel.className = "room-members-label"; this.roomMembersLabel.textContent = "Teilnehmer hinzufügen"; this.roomMembersInput = document.createElement("INPUT"); this.roomMembersInput.className = "room-members-container"; this.roomMembersInput.onkeydown = function (event) { this.searchForUsers(event); }.bind(this); this.containerRooms.appendChild(this.roomNameLabel); this.containerRooms.appendChild(this.roomName); this.containerRooms.appendChild(this.roomMembersLabel); this.containerRooms.appendChild(this.roomMembersInput); this.roomMembersDisplay = document.createElement("DIV"); this.roomMembersDisplay.className = "room-members-display"; this.containerRooms.appendChild(this.roomMembersDisplay); var acceptRoomButton = document.createElement("BUTTON"); acceptRoomButton.className = "ok roomCreator"; acceptRoomButton.textContent = "Team erzeugen"; acceptRoomButton.onclick = function () { var i, l = this.roomMembersList.length, membersData = [], membersString = l === 0 ? "-" : ""; for (i = 0; i < l; i++) { membersData[i] = { "userid": this.roomMembersList[i].id, "memberName": this.roomMembersList[i].name }; membersString += this.roomMembersList[i].name; if(i < l - 1){ membersString += ", "; } } if(this.roomName.value.length === 0){ alertManager.inform("Bitte gib den Team einen Namen", function () { this.roomName.focus(); }.bind(this)); } else{ alertManager.ask("Ausgewählte Mitglieder: " + membersString + ". Fortfahren?", function () { socketGateway.emit("createRoom", {"members": membersData, "name": this.roomName.value, "privateStatus": "N"}, function (response) { if (response.status === "ok") { this.roomName.value = ""; this.rooms.unshift(response.roomData); currentHome.room({ roomid : response.roomData.id, 'type' : 'teams' }) currentHome.api.sendEvent( { 'type' : 'notification', 'event' : 'update-teams', 'value' : 'join' } ) } else if (response.status === "roomExists") { var roomid = response.roomid; var roomData = this.getRoomFromId(roomid); currentHome.room( {roomid : roomid, 'type' : 'teams'} ); socketGateway.emit("openRoom", roomid, function (userStatus) { roomData["userStatus"] = userStatus; currentHome.showRoom(roomData); }); } else { alertManager.inform(response.message); } }.bind(this)); }.bind(this)); } }.bind(this); this.containerRooms.appendChild(acceptRoomButton); this.roomCreatorContainer = document.createElement("DIV"); this.containerRooms.appendChild(this.roomCreatorContainer); this.element.appendChild(this.containerRooms); }.bind(this); }; RoomsScreen.prototype.createDiscussionCreator = function () { this.createDiscussionButton = document.createElement("BUTTON"); this.createDiscussionButton.className = "submenu-bar-button"; this.createDiscussionButton.id = "submenu-bar-button-id"; this.createDiscussionButton.style.height = "20px"; this.createDiscussionButton.style.top = "10px"; this.createDiscussionButton.textContent = "+ Private Nachricht"; this.header.appendChild(this.createDiscussionButton); this.createDiscussionButton.onclick = function () { if(this.containerRooms) { this.element.removeChild(this.containerRooms); } this.containerRooms = document.createElement("DIV"); this.containerRooms.className = "room-list-container"; this.selectButton(this.createDiscussionButton); this.discussionMembersLabel = document.createElement("DIV"); this.discussionMembersLabel.className = "room-members-label"; this.discussionMembersLabel.textContent = "Teilnehmer hinzufügen"; this.discussionMembersInput = document.createElement("INPUT"); this.discussionMembersInput.className = "room-members-container"; this.discussionMembersInput.onkeydown = function (event) { this.searchForUsers(event, true); }.bind(this); this.containerRooms.appendChild(this.discussionMembersLabel); this.containerRooms.appendChild(this.discussionMembersInput); this.roomCreatorContainer = document.createElement("DIV"); this.containerRooms.appendChild(this.roomCreatorContainer); this.element.appendChild(this.containerRooms); }.bind(this); }; RoomsScreen.prototype.createRoomElement = function (roomData) { var i, membersArray = roomData.members, l = membersArray.length; var roomElement = document.createElement("DIV"); roomElement.className = "room-list-room-element"; roomElement.onclick = function () { socketGateway.emit("openRoom", roomData.id, function (userStatus) { roomData["userStatus"] = userStatus; currentHome.showRoom(roomData); }); }; var roomPicture = document.createElement("IMG"); if( roomData.private === "Y" ) { roomPicture.className = "room-picture private"; for (i = 0; i < l; i++) { if ( currentUser.id != membersArray[i].userid) { //picture of the other user in the chat roomPicture.src = projectDomain + membersArray[i].picture; roomData.name = membersArray[i].memberName; break; } } } else { if ( roomData.adminid == currentUser.id ) { roomPicture.className = "room-picture non-private"; roomPicture.src = projectDomain + "/public/images/room-owner.png"; } else { roomPicture.className = "room-picture non-private"; roomPicture.src = projectDomain + "/public/images/room.png"; } } roomElement.appendChild(roomPicture); var wordsContainer = document.createElement("DIV"); wordsContainer.className = "room-list-words-container"; var roomName = document.createElement("DIV"); roomName.className = "room-list-room-name"; roomName.textContent = roomData.name; wordsContainer.appendChild(roomName); var messagePreview = document.createElement("DIV"); messagePreview.className = "room-list-message-preview"; var previewText = roomData.lastMessage ? roomData.lastMessage.text.slice(0, 40) : "Keine Nachrichten"; messagePreview.textContent = previewText.length >= 45 ? previewText + "..." : previewText; wordsContainer.appendChild(messagePreview); if ( roomData.lastMessage ) { messagePreview.textContent = messagePreview.textContent + " - " + helper.timestampToBeauty( roomData.lastMessage.timestamp ); } var message_count = document.createElement("SPAN"); message_count.style.color = "#CE0C2F"; message_count.style.marginLeft = "5px"; if ( roomData.new_messages == 1 ) { message_count.textContent = " (1 new message)"; } else if ( roomData.new_messages > 1 ) { message_count.textContent = " (" +roomData.new_messages + " new messages)"; } messagePreview.appendChild(message_count); /*var messageTime = document.createElement("DIV"); messageTime.className = "room-list-room-last-activity"; wordsContainer.appendChild(messageTime); */ roomElement.appendChild(wordsContainer); if ( ["canceled", "pending"].indexOf( roomData.my_status ) != -1 ) { //add extra accept; var accept_button = document.createElement("BUTTON"); accept_button.className = "pending-join"; accept_button.textContent = "Beitreten"; accept_button.onclick = function( event ) { currentHome.room({roomid : roomData.id, 'type' : ( roomData.private == 'N' ? 'teams' : 'private' ) }); event.stopPropagation(); event.preventDefault(); } roomElement.appendChild(accept_button); } /*if (roomData.private === "N") { var roomMembers = document.createElement("DIV"); roomMembers.className = "room-list-room-members"; var maximumShownMemberIcons = 3; var numberOfMembersOverLimit = 0; for (i = 0; i < l; i++) { if( ["joined", "pending"].indexOf(membersArray[i].status) !== -1){ if(i < maximumShownMemberIcons){ var roomMember = document.createElement("DIV"); roomMember.className = "room-list-room-member"; var roomMemberPicture = document.createElement("IMG"); roomMemberPicture.className = "room-list-room-member-picture"; roomMemberPicture.src = projectDomain + membersArray[i].picture; roomMemberPicture.title = membersArray[i].memberName; var roomMemberName = document.createElement("DIV"); roomMemberName.textContent = membersArray[i].memberName; roomMemberName.className = "room-list-room-member-name"; roomMember.appendChild(roomMemberPicture); roomMembers.appendChild(roomMember); } else{ numberOfMembersOverLimit++; } } } if(numberOfMembersOverLimit > 0){ var moreMembers = document.createElement("DIV"); moreMembers.className = "rooms-more-members"; moreMembers.appendChild(document.createTextNode("+" + numberOfMembersOverLimit)); roomMembers.appendChild(moreMembers); } roomMembers.onclick = function (event) { event.stopPropagation(); this.createMembersPopUp( membersArray ); }.bind( this ); roomElement.appendChild(roomMembers); } */ return roomElement; }; RoomsScreen.prototype.createMembersPopUp = function(membersArray) { var membersList = document.createElement("DIV"); var i, l = membersArray.length; for (i = 0; i < l; i++) { if(["joined", "pending"].indexOf(membersArray[i].status) !== -1){ var roomMember = document.createElement("DIV"); roomMember.className = "room-list-room-member"; /*roomMember.onclick = function () { currentHome.userByChatId(this.userid); }.bind({"userid": membersArray[i].userid});*/ var roomMemberPicture = document.createElement("IMG"); roomMemberPicture.className = "room-list-room-member-picture"; roomMemberPicture.src = projectDomain + membersArray[i].picture; roomMemberPicture.title = membersArray[i].memberName; var roomMemberName = document.createElement("DIV"); roomMemberName.textContent = membersArray[i].memberName; roomMemberName.className = "room-list-room-member-name"; roomMember.appendChild(roomMemberPicture); roomMember.appendChild(roomMemberName); membersList.appendChild(roomMember); } } alertManager.scrollableInform(membersList, function () {}); }; RoomsScreen.prototype.searchForUsers = function (event, isPrivate) { var deactivateSearch = function () { if (this.search) { this.search.clearResults(); this.search = undefined; if(this.roomMembersInput){ this.roomMembersInput.onclick = null; } if(this.discussionMembersInput){ this.discussionMembersInput.onclick = null; } } }.bind(this); var activateSearch = function () { this.searchTerm = ""; this.search = new SearchField(); if(this.roomMembersInput){ this.roomMembersInput.onclick = function () { this.search.clearResults(); }.bind(this); } else if(this.discussionMembersInput){ this.discussionMembersInput.onclick = function () { this.search.clearResults(); }.bind(this); } }.bind(this); var isCharLetter = function (char) { var regex = /^\w|[ÀÈÌÒÙàèìòùÁÉÍÓÚÝáéíóúýÂÊÎÔÛâêîôûÃÑÕãñõÄËÏÖÜäëïöüçÇßØøÅåÆæÞþÐð]$/; var result = char.match(regex); return result && result[0] === result.input; }; var pressedKey = event.key; if (this.search && (pressedKey === " ")) { deactivateSearch(); } if (!this.search && isCharLetter(pressedKey)) { activateSearch(); } if (this.search && (isCharLetter(pressedKey) || pressedKey === "Backspace")) { var results; if (pressedKey === "Backspace") { this.searchTerm = this.searchTerm.slice(0, -1); } else { this.searchTerm += pressedKey; } if (this.searchTerm === "") { deactivateSearch(); } else if (this.searchTerm === ",") { this.search.clearResults(); } else { socketGateway.emit("searchUsers", this.searchTerm, function (args) { var originalText = args["originalText"]; results = this.search.createAndAttachResults({ "originalText": args.originalText, "users": args.users, "groups": [], "usersFilter": [currentUser.id] }, this.roomCreatorContainer, function (args) { if (isPrivate) { if(!this.memberAlreadyChosen(args)){ alertManager.ask("Willst du ein Gespräch mit '" + args.name + "' anfangen?", function () { var membersData = [{ "userid": args.id, "memberName": args.name }]; socketGateway.emit("createRoom", {"members": membersData, "name": args.name, "privateStatus": "Y"}, function (response) { if (response.status === "ok") { this.rooms.unshift(response.roomData); this.discussionMembersInput.value = ""; currentHome.room({roomid : response.roomData.id, 'type' : 'private'}); currentHome.api.sendEvent( { 'type' : 'notification', 'event' : 'update-private', 'value' : 'join' } ) } else if (response.status === "roomExists") { var roomid = response.roomid; var roomData = this.getRoomFromId(roomid); currentHome.room( {roomid : roomid, 'type' : 'private'}, function(){} ); socketGateway.emit("openRoom", roomid, function (userStatus) { roomData["userStatus"] = userStatus; currentHome.showRoom(roomData); }); } else { alertManager.inform(response.message); } }.bind(this)); }.bind(this)); } } else { var memberElement = this.createChosenMemberElement(args); if (memberElement) { this.roomMembersDisplay.appendChild(memberElement); } } if(this.roomMembersInput){ this.roomMembersInput.value = ""; this.roomMembersInput.focus(); } deactivateSearch(); }.bind(this)); }.bind(this)); } } }; RoomsScreen.prototype.createChosenMemberElement = function (memberData) { if (!this.memberAlreadyChosen(memberData)) { var element = document.createElement("DIV"); element.className = "room-creator-member"; element.textContent = memberData.name; var removeButton = document.createElement("BUTTON"); removeButton.textContent = "x"; removeButton.className = "room-creator-remove-member-button"; removeButton.onclick = function () { this.roomMembersDisplay.removeChild(element); var i; for (i = 0; i < this.roomMembersList.length; i++) { if (this.roomMembersList[i].element === element) { this.roomMembersList.splice(i); } } if (this.roomMembersList.length === 1) { this.detachRoomNameElements(); } }.bind(this); memberData.element = element; this.roomMembersList.push(memberData); element.appendChild(removeButton); return element; } }; RoomsScreen.prototype.memberAlreadyChosen = function (memberData) { var i; for (i = 0; i < this.roomMembersList.length; i++) { if (this.roomMembersList[i].id === memberData.id) { return true; } } return false; }; RoomsScreen.prototype.getRoomFromId = function (roomid) { var i = 0, found = false; while (i < this.rooms.length && !found) { var room = this.rooms[i]; if (room.id === roomid) { found = true; } i++; } return room; }; /* A room of users. Contains a header and options for users to manage theirs or other users' (in case the current user is the creator of the room) room status. It also contains the RoomInfoStream and a text field to write new messages. */ function Room(args) { socketGateway.emit("setRoomNotificationsAsRead", { "roomid": args.id }, function() { }); this.roomData = args; this.name = args.name; this.id = args.id; this.adminid = args.adminid; this.adminName = args.adminName; this.isCurrentAdmin = this.adminid === currentUser.id; this.members = args.members; this.writers = args.writers; this.promoted = args.promoted; this.files_page = 0; this.settings = args.settings || {}; if ( this.settings["sound"] == undefined ) { this.settings["sound"] = true; } //compatibility if ( this.settings["autoscroll"] == undefined ) { this.settings["autoscroll"] = true; } //compatibility this.members_by_id = {}; var i, l = this.members.length; for ( i = 0; i < l; i++ ) { this.members_by_id[this.members[i].userid] = this.members[i]; } this.userStatus = args.userStatus; this.private = args.private; this.element = document.createElement("DIV"); this.element.className = "room"; this.element.id = "room"; this.titleContainer = document.createElement("DIV"); this.titleContainer.className = "title-container-room"; this.element.appendChild(this.titleContainer); this.input_feedback_timeout = null; this.input_feedback = document.createElement("DIV"); this.input_feedback.style.display = "none"; this.input_feedback.textContent = "Nachricht wurde gesendet."; this.input_feedback.className = "input-feedback"; this.onCloseCallback; this.startingNumberShown = numberOfRoomMessagesShown + 10; this.numberOfMessagesShown = this.startingNumberShown; this.moreToFetch = true; this.alreadyFetching = false; this.infoStreamContainer = document.createElement("DIV"); this.infoStreamContainer.className = this.private === "N" ? "room-infostream-container" : "room-infostream-container private"; this.room_members_pane = document.createElement("DIV"); this.room_members_pane.className = "room-infostream-container "; this.room_members_pane.style.display = "none"; this.room_settings_pane = document.createElement("DIV"); this.room_settings_pane.className = "room-infostream-container "; this.room_settings_pane.style.display = "none"; this.room_files_pane = document.createElement("DIV"); this.room_files_pane.className = "room-infostream-container "; this.room_files_pane.style.display = "none"; this.room_files_pane.style.height = "calc( 100% - 50px )"; this.room_search_pane = document.createElement("DIV"); this.room_search_pane.className = "room-infostream-container "; this.room_search_pane.style.display = "none"; this.room_search_pane.style.paddingTop = "10px"; this.room_search_pane.style.height = "calc( 100% - 50px )"; this.infoStream = null; this.moreToFetch; this.alreadyFetching = false; this.createTitle(); this.element.appendChild(this.infoStreamContainer); this.element.appendChild(this.room_settings_pane); this.element.appendChild(this.room_files_pane); this.element.appendChild(this.room_members_pane); this.element.appendChild(this.room_search_pane); this.checkUserStatus(); if ( this.writers == null || this.writers.length == 0 || this.writers.indexOf( currentUser.id ) != -1 ) { this.createTextInput(); } else { this.infoStreamContainer.style.height = "calc( 100% - 50px )"; this.room_files_pane.style.height = "calc( 100% - 50px )"; } this.onOtherUserMessage = function(data) { var messageData = data.messageData; if ( messageData.posterid == 0 ) { if ( messageData.systemType == 'changeName' ) { this.name = messageData.name; this.createTitle(); } } if ( this.id === messageData.roomid && this.infoStream != null ) { messageData.remove_last_time = this.infoStream.postInShortTime(messageData); let dim = this.getScrollDimensions(); let at_bottom = Math.abs( dim.currentHeight - dim.fullHeight) < 100; this.infoStream.addPostAtEnd(messageData); setTimeout( ()=>{ if ( at_bottom && this.settings["autoscroll"] ) { let dimensions = this.getScrollDimensions(); this.infoStreamContainer.scrollTop = dimensions["fullHeight"] - dimensions["clientHeight"]; } }, 1000 ) if ( this.settings["sound"] ) { new Audio(projectDomain + '/public/audio/beep.mp3').play(); } } }.bind( this ) socketGateway.subscribe("newRoomMessage", this.onOtherUserMessage, this); currentView.setNewView( { type : 'room', id : this.id, onChangeView : function(){ socketGateway.unsubscribe("newRoomMessage", this ); }.bind(this), calls : { takeSharedElement : [ this, this.takeSharedElement ], postSharedElement : [ this, this.postSharedElement ] } } ) } Room.prototype.postSharedElement = function( element ) { this.handleDroppedData( element ) }; Room.prototype.takeSharedElement = function( element ) { this.handleDroppedDataInFiles( element ); }; Room.prototype.createTitle = function () { this.titleContainer.innerHTML = ""; var title = document.createElement("DIV"); title.className = "title-room"; var name_span = document.createElement("DIV"); name_span.className = "title-room"; name_span.textContent = this.name; if (this.isCurrentAdmin && this.private === "N") { name_span.contentEditable = true; name_span.onkeydown = function( event ){ if ( event.keyCode == 13 ) { var name = name_span.textContent; socketGateway.emit("changeRoomName", { id : this.id, name : name }, function ( response ) { } ); event.stopPropagation(); event.preventDefault(); } }.bind( this ) } var name_count = document.createElement("DIV"); name_count.style.clear = "both"; name_count.className = "title-counter"; name_count.textContent = ' (' + this.members.length + ' Mitglieder)'; this.titleContainer.appendChild(name_span); //this.titleContainer.appendChild(name_count); var i, l = this.members.length; if ( this.private == 'Y' ) { for (i = 0; i < l; i++) { if ( this.members[i].userid != this.adminid ){ if ( this.members[i].status == 'pending' ) { title.textContent = this.name + ' (Einladung noch unbeantwortet)'; } break; } } } this.createOptionsButton(this.titleContainer); }; Room.prototype.createOptionsButton = function (parent) { var submenu = document.createElement("DIV"); submenu.className = "room-collapsable-submenu"; submenu.style.display = "none"; var menu_button = document.createElement("DIV"); menu_button.className = "fa fa-bars room-title-button"; menu_button.title = "Menu"; menu_button.onclick = function( event ) { submenu.style.display = submenu.style.display == "none" ? "block" : "none"; event.stopPropagation(); event.preventDefault(); } parent.appendChild( menu_button ); parent.appendChild( submenu ); var setActiveButton = function(){ if ( this.room_files_pane.style.display == "none" ) { filesButton.className = filesButton.className.replace( "active", "" ); this.hideInputs(); } else { chatButton.className = chatButton.className.replace( "active", "" ); if ( filesButton.className.indexOf( "active" ) == -1 ) { filesButton.className = filesButton.className + " active"; } } if ( this.room_settings_pane.style.display == "none" ) { optionsButton.className = optionsButton.className.replace( "active", "" ); this.hideInputs(); } else { chatButton.className = chatButton.className.replace( "active", "" ); if ( optionsButton.className.indexOf( "active" ) == -1 ) { optionsButton.className = optionsButton.className + " active"; } } if ( this.room_members_pane.style.display == "none" ) { membersButton.className = membersButton.className.replace( "active", "" ); this.hideInputs(); } else { chatButton.className = chatButton.className.replace( "active", "" ); if ( membersButton.className.indexOf( "active" ) == -1 ) { membersButton.className = membersButton.className + " active"; } } if ( this.room_search_pane.style.display == "none" ) { searchButton.className = searchButton.className.replace( "active", "" ); this.hideInputs(); } else { chatButton.className = chatButton.className.replace( "active", "" ); if ( searchButton.className.indexOf( "active" ) == -1 ) { searchButton.className = searchButton.className + " active"; } } if ( this.room_files_pane.style.display == "none" && this.room_settings_pane.style.display == "none" && this.room_members_pane.style.display == "none" && this.room_search_pane.style.display == "none" ) { this.showInputs(); if ( chatButton.className.indexOf( "active" ) == -1 ) { chatButton.className = chatButton.className + " active"; } } }.bind( this ) var optionsButton = document.createElement("DIV"); optionsButton.className = "fa fa-cog room-title-button"; optionsButton.title = "Einstellungen"; optionsButton.onclick = function (event) { this.room_settings_pane.style.display = this.room_settings_pane.style.display == "none" ? "block" : "none"; this.room_files_pane.style.display = "none"; this.room_members_pane.style.display = "none"; this.room_search_pane.style.display = "none"; this.infoStreamContainer.style.display = "none"; if ( this.room_settings_pane.style.display == "none" ) { this.infoStreamContainer.style.display = "block"; } else { this.infoStreamContainer.style.display = "none"; } setActiveButton(); }.bind(this); var soundButton = document.createElement("DIV"); soundButton.className = "fa fa-bell" + (this.settings["sound"] ? "" : "-slash") + " room-title-button"; soundButton.title = "Ton bei Nachricht " + (this.settings["sound"] ? "aktiviert!" : "deaktiviert!"); soundButton.onclick = function (event) { this.settings["sound"] = !this.settings["sound"]; soundButton.className = "fa fa-bell" + (this.settings["sound"] ? "" : "-slash") + " room-title-button"; soundButton.title = "Ton bei Nachricht " + (this.settings["sound"] ? "aktiviert!" : "deaktiviert!"); socketGateway.emit("setUserRoomSettings", { "roomid": this.id, "settings": this.settings }, function () {}); }.bind(this); var chatButton = document.createElement("DIV"); chatButton.className = "fa fa-comments room-title-button active"; chatButton.title = "Unterhaltung"; chatButton.onclick = function (event) { this.room_settings_pane.style.display = "none"; this.room_files_pane.style.display = "none"; this.room_members_pane.style.display = "none"; this.room_search_pane.style.display = "none"; this.infoStreamContainer.style.display = "block"; setActiveButton(); }.bind(this); var searchButton = document.createElement("DIV"); searchButton.className = "fa fa-search room-title-button"; searchButton.title = "Suchen"; searchButton.onclick = function (event) { this.room_search_pane.style.display = this.room_search_pane.style.display == "none" ? "block" : "none"; this.room_files_pane.style.display = "none"; this.room_settings_pane.style.display = "none"; this.room_members_pane.style.display = "none"; if ( this.room_search_pane.style.display == 'block' ) { this.infoStreamContainer.style.display = "none"; this.buildRoomSearch(); } else { this.infoStreamContainer.style.display = "block"; } setActiveButton(); }.bind(this); var filesButton = document.createElement("DIV"); filesButton.className = "fa fa fa-copy room-title-button"; filesButton.title = "Dateien"; filesButton.onclick = function (event) { this.room_files_pane.style.display = this.room_files_pane.style.display == "none" ? "block" : "none"; this.room_settings_pane.style.display = "none"; this.room_members_pane.style.display = "none"; this.room_search_pane.style.display = "none"; if ( this.room_files_pane.style.display == 'block' ) { this.infoStreamContainer.style.display = "none"; this.buildRoomFilesTable(); } else { this.infoStreamContainer.style.display = "block"; } setActiveButton(); }.bind(this); filesButton.onmouseup = function(event){ this.checkDroppedDataInFiles() }.bind( this ) filesButton.ontouchend = function(event){ this.checkDroppedDataInFiles(); }.bind( this ) submenu.appendChild(optionsButton); submenu.appendChild(filesButton); submenu.appendChild(searchButton); var membersButton = document.createElement("DIV"); membersButton.className = "fa fa fa-users room-title-button"; membersButton.title = "Members"; membersButton.onclick = function (event) { this.room_members_pane.style.display = this.room_members_pane.style.display == "none" ? "block" : "none"; this.room_settings_pane.style.display = "none"; this.room_files_pane.style.display = "none"; this.room_search_pane.style.display = "none"; if ( this.room_members_pane.style.display == 'block' ) { this.infoStreamContainer.style.display = "none"; this.buildMembersPane(); } else { this.infoStreamContainer.style.display = "block"; } setActiveButton(); }.bind(this); if ( this.private == 'N' && ( !this.promoted || this.isCurrentAdmin ) ) { submenu.appendChild(membersButton); } submenu.appendChild(chatButton); submenu.appendChild(soundButton); this.createRoomSettingsPane(); }; Room.prototype.buildMembersPane = function(){ this.room_members_pane.innerText = ""; if ( this.private == 'N' && ( !this.promoted || this.isCurrentAdmin ) ) { if ( this.isCurrentAdmin ) { //invite people this.room_members_pane.appendChild(this.createInviteMemberOption()); } this.room_members_pane.appendChild(this.createMembersOption()); } }; Room.prototype.buildRoomSearch = function(){ this.room_search_pane.innerText = ""; var searchTimeout = null; var search_area = document.createElement("div"); search_area.style.float = "left"; search_area.style.clear = "both"; search_area.style.height = "calc( 100% - 80px )"; search_area.style.marginTop = "30px"; search_area.style.overflow = "auto"; var search_nav = document.createElement("div"); search_nav.style.float = "left"; var search_title = document.createElement("div"); search_title.textContent = "Search term: "; search_title.style.float = "left"; search_title.style.marginRight = "5px"; search_title.style.fontSize = "1rem"; search_title.style.padding = "4px 2px"; //todo create search input var search_input = document.createElement("input"); search_input.type = "text"; search_input.placeholder = "Search term"; search_input.style.padding = "4px"; search_input.style.borderRadius = "4px"; search_input.style.float = "left"; search_input.style.width = "calc( 100% - 16rem )"; search_input.style.border = "1px solid #bebebf"; search_input.onkeyup = function(event) { clearTimeout( searchTimeout ); if ( search_input.value.length < 3 ) { search_area.textContent = "Min. 3 letters."; return; } search_area.textContent = "Search term: " + search_input.value; searchTimeout = setTimeout( function(){ search_nav.textContent = ""; search_nav.innerHTML = ""; socketGateway.emit("searchTextInRoom", { 'roomid' : this.id, 'text' : search_input.value }, function (response) { if ( response.result && response.text == search_input.value ) { if ( response.data.length > 0 ) { var s_index = response.data.length - 1; var prev = document.createElement("span") prev.className = "fa fa-arrow-left"; prev.title = "Previous"; prev.style.fontSize = "1.2rem"; prev.style.margin = "5px"; prev.style.cursor = "pointer"; prev.style.float = "left"; prev.onclick = function( event ) { s_index = s_index - 1 >= 0 ? s_index - 1 : response.data.length - 1; this.renderMessageFromIndex(response.data[s_index], search_area, response.text); showHideNav(s_index); }.bind( this ) var next = document.createElement("span"); next.className = "fa fa-arrow-right"; next.title = "Next"; next.style.fontSize = "1.2rem"; next.style.margin = "5px"; next.style.cursor = "pointer"; next.style.float = "left"; next.onclick = function( event ) { s_index = s_index + 1 >= response.data.length ? 0 : s_index + 1; this.renderMessageFromIndex(response.data[s_index], search_area, response.text); showHideNav(s_index); }.bind( this ) search_nav.appendChild( prev ); search_nav.appendChild( next ); var showHideNav = function(s_index){ if ( s_index == 0 ) { prev.style.display = "none"; next.style.display = "block"; } else if ( s_index == response.data.length - 1 ) { prev.style.display = "block"; next.style.display = "none"; } else { prev.style.display = "block"; next.style.display = "block"; } } this.renderMessageFromIndex(response.data[s_index], search_area, response.text); showHideNav(s_index); } else { search_area.innerHTML = "No match found."; } } }.bind( this )) }.bind(this), 1000 ) }.bind( this ) this.room_search_pane.appendChild( search_title ); this.room_search_pane.appendChild( search_input ); this.room_search_pane.appendChild( search_nav ); this.room_search_pane.appendChild( search_area ); }; Room.prototype.renderMessageFromIndex = function(index, area, text){ area.innerHTML = ""; socketGateway.emit("getMessageByIndexRange", { 'roomid' : this.id, 'index' : index, 'range' :10 }, function (response) { if ( response.result ) { var i, l = response.messages.length; for ( i = 0; i < l; i++ ) { response.messages[i].show_date = true; var post = new RoomPost(response.messages[i], text); post.createElement(); area.appendChild(post.element); } setTimeout( function(){ var element = area.getElementsByClassName("scrollTo")[0]; if ( element && element.scrollIntoView) { element.scrollIntoView(false); } }, 500 ) } } ) } Room.prototype.buildRoomFilesTable = function(){ this.room_files_pane.innerText = "Getting files."; socketGateway.emit("getRoomFiles", { roomid : this.id, 'page' : this.files_page }, function (response) { if ( response.result ) { this.room_files_pane.innerText = ""; if ( response.data.length > 0 ) { var table = document.createElement('TABLE'); table.className = "zebra"; table.style.width = "100%"; table.style.height = "100%"; this.room_files_pane.appendChild( table ); var tr, td_text, td_image, td_author, td_date, td_cloud, i, l = response.data.length; for ( i = 0; i < l; i++ ) { tr = document.createElement('TR'); td_date = document.createElement('TD'); td_date.textContent = helper.createTimestampPresentation(response.data[i].timestamp); td_date.className = "pl-10"; td_cloud = document.createElement('TD'); td_cloud.className = "pl-10"; td_image = document.createElement('TD'); td_image.className = "pl-10"; td_text = document.createElement('TD'); td_text.className = "pl-10"; this.createFileTextEntry( response.data[i].text, td_image, td_cloud, td_text ); td_author = document.createElement('TD') td_author.textContent = this.members_by_id[response.data[i].posterid] != undefined ? this.members_by_id[response.data[i].posterid].memberName : ""; td_author.className = "pl-10"; tr.appendChild( td_date ); tr.appendChild( td_author ); tr.appendChild( td_image ); tr.appendChild( td_text ); tr.appendChild( td_cloud ); table.appendChild( tr ); } socketGateway.emit("getSharedFilesPagination", { roomid : this.id }, function (pages) { if ( pages.result ) { var tr = document.createElement('TR'); var td = document.createElement('TD'); td.style.textAlign = 'center'; td.style.padding = '10px'; td.colSpan = 5; var num; tr.appendChild( td ) table.appendChild( tr ); var start = this.files_page - 10 >= 0 ? ( this.files_page - 10 ) : 0; var end = this.files_page + 10 > pages.data ? pages.data : this.files_page + 10; for ( i = start; i < end; i++ ) { num = document.createElement("span") num.style.marginLeft = "5px"; num.style.fontSize = "1rem"; num.style.cursor = "pointer"; num.innerText = i + 1; if ( i == this.files_page ) { num.style.textDecoration = "underline"; num.style.fontWeight = "bold"; } num.onclick = function(){ this.that.files_page = this.num; this.that.buildRoomFilesTable(); }.bind( { that : this, num : i } ) td.appendChild(num); } } }.bind( this )) //look for members by userid inside response.data; //paint table. } else { this.room_files_pane.innerText = "No shared files."; } } else { this.room_files_pane.innerHTML = ""; } }.bind(this)); }; Room.prototype.createFileTextEntry = function( text, imagetd, cloudtd, texttd ) { var text_lines = text.split('\n'); var node, linkText, line, words, i, l = text_lines.length; var container = document.createElement('DIV'); container.className = "no_translate"; for (i = 0; i < l; i++) { //line breakers line = text_lines[i]; words = line.split(" "); var j, k = words.length; for (j = 0; j < k; j++) { if ( helper.isImage(words[j])) { //it is an image node = document.createElement('IMG'); node.style.maxWidth = "20rem"; node.style.maxHeight = "5rem"; node.style.cursor = "pointer"; node.title = words[j]; node.src = words[j]; node.onclick = function( event ) { if( environment === "tradingdesk"){ if (currentHome.externalAction != null) { currentHome.externalAction.fn.call(currentHome.externalAction.context, { 'type' : 'open-image', 'link' : this } ) } } else if(["mobile", "messenger"].indexOf(environment) != -1){ new PictureViewer(rootElement, { "path": this }); } event.preventDefault(); event.stopPropagation(); }.bind( words[j] ) imagetd.appendChild(node); } else if ( helper.isCloudLink(words[j])) { //it is an news var cloud = helper.getCloudParts(words[j]); node = document.createElement('a'); linkText = document.createTextNode("Cloud item öffnen..."); node.appendChild(linkText); node.className = "infostream-post-link"; node.onclick = function( event ){ currentHome.informExternal( { 'type' : 'cloud', id : this[1] } ); }.bind( cloud ) cloudtd.appendChild( node ) } else if ( helper.isValidURL(words[j])) { //it is a link node = document.createElement('a'); linkText = document.createTextNode(words[j]); node.appendChild(linkText); node.title = words[j]; node.className = "infostream-post-link"; node.href = words[j].indexOf('http') == -1 ? '//' + words[j] : words[j]; node.target = "_blank"; cloudtd.appendChild(node) } else { //normal text node = document.createTextNode(words[j]); texttd.appendChild(node); texttd.appendChild(document.createTextNode(" ")); } } } return container } Room.prototype.createRoomSettingsPane = function(){ this.room_settings_pane.innerHTML = ""; if ( this.private === "N" && !this.promoted ) { this.room_settings_pane.appendChild( this.createTeamsSettings() ) } else { this.room_settings_pane.appendChild( this.createTeamsSettings(["autoscroll"]) ) } if ( this.private === "N" && this.isCurrentAdmin ) { this.room_settings_pane.appendChild( this.createTeamsInvitationURL() ) } this.room_settings_pane.appendChild( this.createLeaveOption() ) }; Room.prototype.createTeamsSettings = function(keys){ var settings_container = document.createElement("DIV"); var settings = { 'inform_when_offline' : { 'title' : 'Über neue Nachrichten in diesem Team per Email informieren, wenn ich offline bin.', 'description' : '', 'default' : false, 'type' : 'checkbox' }, 'autoscroll' : { 'title' : 'Autoscroll', 'description' : '', 'default' : true, 'type' : 'checkbox' } } var key; for ( key in settings ) { if ( keys != undefined && keys.indexOf(key) == -1 ) { continue; } var checkboxContainer = document.createElement("DIV"); checkboxContainer.className = "traderchat-settings-container"; if ( settings[key]['type'] == 'checkbox' ) { var title = document.createElement("DIV"); title.textContent = settings[key]['title']; title.className = "traderchat-checkbox-title"; var checkbox = document.createElement("INPUT"); checkbox.type = "checkbox"; checkbox.checked = this.settings[key] != undefined ? this.settings[key] : settings[key]['default']; checkbox.style.marginTop = "5px"; checkbox.className = "traderchat-checkbox"; checkbox.onclick = function (event){ event.stopPropagation(); var sdata = {} sdata[this.key] = event.target.checked; socketGateway.emit("setUserRoomSettings", { "roomid": this.that.id, "settings": sdata }, function () {}); this.that.settings[this.key] = event.target.checked }.bind( { key : key, that : this } ); checkboxContainer.appendChild(checkbox); checkboxContainer.appendChild(title); if ( settings[key]['description'] != "" ) { var description_container = document.createElement("DIV"); description_container.className = "traderchat-checkbox-title"; description_container.style.clear = "both"; description_container.style.marginLeft = "35px"; description_container.innerHTML = settings[key]['description']; checkboxContainer.appendChild(description_container); } } settings_container.appendChild( checkboxContainer ) } return settings_container; }; Room.prototype.createLeaveOption = function(){ var leaveRoomButton = document.createElement("BUTTON"); var type = this.private == 'Y' ? 'Private Raum' : 'Team'; leaveRoomButton.textContent = type + ( this.isCurrentAdmin ? " löschen" : " verlassen" ); leaveRoomButton.className = "room-menu-option delete"; leaveRoomButton.onclick = function () { var text = this.isCurrentAdmin ? "Diese Aktion wird diesen Raum löschen. Fortfahren?" : "Diese Aktion wird dich aus diesem Raum entfernen. Fortfahren?"; alertManager.ask(text, function () { socketGateway.emit("leaveRoom", this.id, function () { var event_type = this.private == 'N' ? 'update-teams' : 'update-private'; currentHome.api.sendEvent( { 'type' : 'notification', 'event' : event_type, 'value' : 'leave' } ) this.onCloseCallback(); }.bind(this)); }.bind(this)); }.bind(this); return leaveRoomButton; }; Room.prototype.createTeamsInvitationURL = function(){ var settings_container = document.createElement("DIV"); settings_container.className = "traderchat-settings-container"; var title = document.createElement("DIV"); title.textContent = "Mitglieder einladen mit Security-Token URL:"; title.className = "traderchat-checkbox-title"; var token_url = document.createElement("DIV"); token_url.textContent = "No token created yet."; token_url.style.clear = "both"; token_url.style.marginLeft = "20px"; token_url.style.fontSize = "16px"; token_url.className = "traderchat-checkbox-title"; var generate_token_button = document.createElement("BUTTON"); generate_token_button.textContent = "Generate new token" generate_token_button.className = "room-menu-option delete"; generate_token_button.style.float = "left"; generate_token_button.onclick = function () { socketGateway.emit("setRoomToken", { "roomid": this.id }, function (response) { if ( response.result ) { token_url.textContent = "https://messenger.traderfox.com/joinTeam?team=" + response.token; } } ) }.bind(this); settings_container.appendChild( title ); settings_container.appendChild( token_url ); settings_container.appendChild( generate_token_button ); socketGateway.emit("getRoomToken", { "roomid": this.id }, function (response) { if ( response.result ) { if ( response.token != null ) { token_url.textContent = "https://messenger.traderfox.com/joinTeam?team=" + response.token; } else { token_url.textContent = "No token created yet."; } } }.bind( this ) ); return settings_container; }; Room.prototype.createMembersOption = function(){ var banMemberFromRoomButton = document.createElement("BUTTON"); banMemberFromRoomButton.textContent = this.isCurrentAdmin ? "Teilnehmer" : "Teilnehmer"; banMemberFromRoomButton.className = "room-menu-option block"; var membersList = document.createElement("TABLE"); membersList.className = "block-users"; var i, l = this.members.length, member, member_row, member_name, member_image, member_status, member_role, memeber_block, memeber_accept; for ( i = 0; i < l; i++) { member = this.members[i]; member_row = document.createElement("TR"); membersList.appendChild( member_row ); member_image = document.createElement("TD"); member_image.style.textAlign = "left"; member_image.innerHTML = ""; member_image.style.width = "64px"; member_image.style.height = "64px"; member_image.className = "room-remove-member-element"; member_row.appendChild( member_image ) member_name = document.createElement("TD"); member_name.style.textAlign = "left"; member_name.textContent = member.memberName; member_row.appendChild( member_name ) if ( this.isCurrentAdmin ) { member_status = document.createElement("TD"); member_status.style.textAlign = "left"; if ( member.status == 'joined' ) { member_status.textContent = 'Mitglied' } else if ( member.status == 'pending' ) { member_status.textContent = 'Einladung noch unbeantwortet' } else if ( member.status == 'waitingAdmin' ) { memeber_accept = document.createElement("TD"); memeber_accept.style.textDecoration = 'underline'; memeber_accept.textContent = 'Accept user'; memeber_accept.style.color = 'red'; memeber_accept.onclick = function( event ){ event.stopPropagation(); socketGateway.emit("acceptTeamMember", { "roomid": this.that.id, "userid": this.member.userid }, function () { this.button.textContent = 'Mitglied'; this.button.style.textDecoration = "none"; memeber_accept.style.color = 'inherit'; }.bind(this)); }.bind( { that : this, member : member, button : memeber_accept } ) member_status.appendChild( memeber_accept ) } member_row.appendChild( member_status ) } member_role = document.createElement("TD"); member_role.style.textAlign = "left"; member_role.textContent = member.userid == this.adminid ? 'Eigentümer (kann Mitglieder einladen, ausladen und das Team schließen)' : 'Trader'; member_row.appendChild( member_role ) if ( this.isCurrentAdmin ) { memeber_block = document.createElement("TD"); memeber_block.style.textDecoration = 'underline'; memeber_block.textContent = 'Blockieren'; memeber_block.onclick = function( event ){ event.stopPropagation(); alertManager.ask("Das wird den Nutzer '" + this.member.memberName + "' vom Raum entfernen. Fortfahren?", function () { socketGateway.emit("blockMember", { "roomid": this.that.id, "userid": this.member.userid }, function () { var removeCandidate for (var j = 0; j < this.that.members.length; j++) { removeCandidate = this.that.members[j]; if (removeCandidate.userid === this.member.userid) { this.that.members.splice(j, 1); } } this.that.roomData.members = this.that.members; this.that.createTitle(); }.bind(this)); }.bind(this)); }.bind( { that : this, member : member } ) member_row.appendChild( memeber_block ) } } banMemberFromRoomButton.appendChild( membersList ); return banMemberFromRoomButton; }; Room.prototype.createInviteMemberOption = function(){ var inviteMoreMembersButton = document.createElement("BUTTON"); inviteMoreMembersButton.textContent = "Mitglieder hinzufügen"; inviteMoreMembersButton.className = "room-menu-option"; var moreMembersFinder = document.createElement("DIV"); moreMembersFinder.onclick = function (event) { event.stopPropagation(); }; var textContainer = document.createElement("DIV"); textContainer.textContent = "Suchen Sie für Trader:"; moreMembersFinder.appendChild(textContainer); var inputField = document.createElement("INPUT"); inputField.style.width = "200px"; inputField.onkeydown = function (event) { this.searchForUsers(moreMembersFinder, inputField, event, function (args) { socketGateway.emit("sendRoomInvite", {"roomid": this.id, "userid": args.id}, function ( members ) { this.members = members; this.roomData.memebers = members; //AX, why two times? this.createTitle(); }.bind( this )); }.bind(this)); }.bind(this); moreMembersFinder.appendChild(inputField); inviteMoreMembersButton.appendChild( moreMembersFinder ) return inviteMoreMembersButton; }; Room.prototype.checkUserStatus = function () { switch (this.userStatus) { case "joined": this.createMessages(); break; case "waitingAdmin": this.infoStreamContainer.textContent = "Waiting for Admin response." break; case "pending": case "canceled": var roomid = this.id; alertManager.ask("Möchtest du diesen Raum beitreten?", function () { socketGateway.emit("joinRoom", roomid, function () { var event_type = this.private == 'N' ? 'update-teams' : 'update-private'; currentHome.api.sendEvent( { 'type' : 'notification', 'event' : event_type, 'value' : 'join' } ) this.createMessages(); }.bind(this)); }.bind(this), function () { socketGateway.emit("cancelRoomInvite", roomid, function () { var event_type = this.private == 'N' ? 'update-teams' : 'update-private'; currentHome.api.sendEvent( { 'type' : 'notification', 'event' : event_type, 'value' : 'leave' } ) this.onCloseCallback(); }.bind(this)); }.bind(this)); break; } }; Room.prototype.createMessages = function () { this.infoStream = new RoomInfoStream(); this.infoStreamContainer.appendChild(this.infoStream.element); this.fetchMessages( function (posts) { this.infoStream.buildInfoStream(posts); setTimeout( function(){ this.activateOnScroll(); }.bind(this), 300 ) }.bind(this)); }; Room.prototype.fetchMessages = function (callback) { this.alreadyFetching = true; var loading = document.createElement("DIV"); loading.textContent = "Loading more..."; //loadingContainer.className = "loading-more"; //loadingContainer.appendChild(loading); var beforeDimensions; if (this.infoStreamContainer) { beforeDimensions = this.getScrollDimensions(); } socketGateway.emit("loadRoomMessages", { "roomid": this.id, "numberOfPostsShown": this.numberOfMessagesShown, "startingNumberShown": this.startingNumberShown }, function (data) { this.moreToFetch = data["moreToFetch"]; //loadingContainer.removeChild(loading); this.alreadyFetching = false; var messages = data["messages"]; var minutes = ( 1000 * 60 * 5 ); var i, l = messages.length, date, date_previous = null; for ( i = 0; i < l; i++ ) { if ( messages[i-1] != undefined && date_previous == null ) { date_previous = new Date( messages[i-1].timestamp ) } date = new Date( messages[i].timestamp ); if ( Math.abs(date - date_previous) > minutes ) { date_previous = date; messages[i].show_date = true; } } callback(messages); if (beforeDimensions) { var afterDimensions = this.getScrollDimensions(); this.infoStreamContainer.scrollTop = afterDimensions.fullHeight - beforeDimensions.fullHeight; } }.bind(this)); }; Room.prototype.showInputs = function(){ if ( this.textInput ) { this.textInput.style.display = "block"; } if ( this.uploadButton ) { this.uploadButton.style.display = "block"; } if ( this.sendButton ) { this.sendButton.style.display = "block"; } if ( this.shareButton ) { this.shareButton.style.display = "block"; } }; Room.prototype.hideInputs = function(){ if ( this.textInput ) { this.textInput.style.display = "none"; } if ( this.uploadButton ) { this.uploadButton.style.display = "none"; } if ( this.sendButton ) { this.sendButton.style.display = "none"; } if ( this.shareButton ) { this.shareButton.style.display = "none"; } }; Room.prototype.createTextInput = function () { this.textInput = document.createElement("TEXTAREA"); this.textInput.rows = 3; this.textInput.placeholder = "Eine neue Nachricht eingeben"; this.textInput.className = "room infostream-textfield"; this.uploadButton = document.createElement("DIV"); this.uploadButton.className = "upload-in-room-button"; this.uploadIcon = document.createElement("DIV"); this.uploadIcon.className = "fa fa-paperclip"; this.uploadIcon.style.right = "0.5rem"; this.uploadIcon.style.position = "absolute"; this.uploadInput = document.createElement("INPUT"); this.uploadInput.type = "file"; this.uploadInput.style.position = "absolute"; this.uploadInput.style.opacity = "0"; this.uploadInput.style.right = "0.5rem"; this.uploadInput.style.width = "100%"; this.uploadInput.style.height = "100%"; this.uploadInput.style.cursor = "pointer"; this.uploadInput.onchange = function (event) { event.stopPropagation(); event.preventDefault(); helper.uploadFile( event.target.files, function(data){ if (data.response === "ok") { this.textInput.value += " https://traderchat.traderfox.com" + data.path + " "; } }.bind( this ) ) }.bind( this ); this.uploadButton.appendChild(this.uploadIcon); this.uploadButton.appendChild(this.uploadInput); this.sendButton = document.createElement("DIV"); this.sendButton.className = "fa fa-paper-plane send-in-room-button"; this.sendButton.onclick = function (event) { this.resizeTextField(event, true); }.bind( this ) this.shareButton = document.createElement("DIV"); this.shareButton.className = "fa fa-share-alt share-in-room-button"; this.shareButton.onclick = function (event) { if ( currentHome.api.showShareMenu != null ) { currentHome.api.showShareMenu(); } event.stopPropagation(); event.preventDefault(); }.bind( this ) this.element.appendChild(this.input_feedback); this.element.appendChild(this.textInput); this.element.appendChild(this.uploadButton); if ( environment === 'messenger' && currentHome.api.showShareMenu != null ) { this.element.appendChild(this.shareButton); } this.element.appendChild(this.sendButton); this.textInput.onkeydown = function (event) { this.resizeTextField(event); }.bind(this); this.textInput.onmouseup = function (event) { this.checkDroppedData(event); }.bind(this); this.textInput.ontouchend = function (event) { this.checkDroppedData(event); }.bind(this); this.textInput.ondrop = function (event) { event.stopPropagation(); event.preventDefault(); helper.uploadFile( event.dataTransfer.files, function(data){ if (data.response === "ok") { this.textInput.value += "https://traderchat.traderfox.com" + data.path; } }.bind( this ) ) }.bind( this ); this.textInput.onpaste = function( event ) { var items = event.clipboardData.items; var i, l = items.length; for ( i = 0; i < l; i++ ) { if ( items[i]['kind'] == 'file' && items[i]['type'] == 'image/png' ) { helper.uploadFile( [items[i].getAsFile()], function(data){ if (data.response === "ok") { this.textInput.value += "https://traderchat.traderfox.com" + data.path; } }.bind( this ) ) } } }.bind(this) if ( currentHome.autoPost != null ) { this.handleDroppedData(currentHome.autoPost); currentHome.autoPost = null; } }; Room.prototype.checkDroppedDataInFiles = function(event){ if ( this.writers != null && this.writers.length != 0 && this.writers.indexOf( currentUser.id ) == -1 ) { return; } if ( currentHome.dropData != null ) { var drop_data = currentHome.dropData; currentHome.resetDropData(); this.handleDroppedDataInFiles( drop_data ); } }; Room.prototype.checkDroppedData = function(event){ if ( this.writers != null && this.writers.length != 0 && this.writers.indexOf( currentUser.id ) == -1 ) { return; } if ( currentHome.dropData != null ) { var drop_data = currentHome.dropData; currentHome.resetDropData(); this.handleDroppedData( drop_data ); } //event.preventDefault(); }; Room.prototype.handleDroppedDataInFiles = function( data ) { if ( this.writers != null && this.writers.length != 0 && this.writers.indexOf( currentUser.id ) == -1 ) { return; } var text = ""; if ( data.type == 'cloud' ) { text = helper.now() + ' ' + currentUser.username + ' hat einen neuen Datei mit dem Team geteilt cloud||' + data.cloud_id; } if ( text != "" ) { socketGateway.emit("createMessage", {"roomid": this.id, "text": text }, function (data) { if (data.status === "ok") { data.remove_last_time = this.infoStream.postInShortTime(data); this.infoStream.addPostAtEnd(data); var dimensions = this.getScrollDimensions(); this.infoStreamContainer.scrollTop = dimensions["fullHeight"] - dimensions["clientHeight"]; this.textInput.enabled = true; this.buildRoomFilesTable(); } else { this.textInput.value = data.message; this.textInput.enabled = false; } }.bind(this)); } }; Room.prototype.handleDroppedData = function( data ) { if ( this.writers != null && this.writers.length != 0 && this.writers.indexOf( currentUser.id ) == -1 ) { return; } if ( data.type == 'stock' ) { this.textInput.value += ' stock||' + data.data + ' '; } else if ( data.type == 'chart' ) { this.textInput.value += ' ' + data.url + ' '; } else if ( data.type == 'news' ) { this.textInput.value += ' ' + data.title + ' news||' + data.id + '||' + data.source + ' '; } else if ( data.type == 'cloud' ) { this.textInput.value += ' ' + (data.icon != null ? data.icon : "") + ' ' + data.title + ' cloud||' + data.cloud_id; } }; Room.prototype.getScrollDimensions = function () { var dimensions = {}; dimensions["fullHeight"] = this.infoStreamContainer.scrollHeight; dimensions["scrollTop"] = this.infoStreamContainer.scrollTop; dimensions["clientHeight"] = this.infoStreamContainer.clientHeight; dimensions["currentHeight"] = dimensions["scrollTop"] + dimensions["clientHeight"]; return dimensions; }; Room.prototype.activateOnScroll = function () { var dimensions; this.infoStreamContainer.onscroll = function ( force ) { dimensions = this.getScrollDimensions(); if ( force === true || dimensions["scrollTop"] === 0) { if (!this.alreadyFetching && this.moreToFetch) { this.numberOfMessagesShown += this.startingNumberShown; this.fetchMessages(function (data) { this.infoStream.addOlderBefore(data); if (this.infoStreamLoadedCallback) { this.infoStreamLoadedCallback(); } }.bind(this)); } } }.bind(this); dimensions = this.getScrollDimensions(); this.infoStreamContainer.scrollTop = dimensions["fullHeight"] - dimensions["clientHeight"]; }; Room.prototype.deactivateOnScroll = function () { this.element.onscroll = null; }; Room.prototype.onClose = function (callback) { this.onCloseCallback = callback; }; Room.prototype.searchForUsers = function (parent, inputField, event, selectNameCallback) { var deactivateSearch = function () { if (this.search) { this.search.clearResults(); this.search = undefined; inputField.onclick = undefined; } }.bind(this); var activateSearch = function () { this.searchTerm = ""; this.search = new SearchField(); inputField.onclick = function () { this.search.clearResults(); }.bind(this); }.bind(this); var isCharLetter = function (char) { var regex = /^\w|[ÀÈÌÒÙàèìòùÁÉÍÓÚÝáéíóúýÂÊÎÔÛâêîôûÃÑÕãñõÄËÏÖÜäëïöüçÇßØøÅåÆæÞþÐð]$/; var result = char.match(regex); return result && result[0] === result.input; }; var pressedKey = event.key; if (this.search && (pressedKey === " ")) { deactivateSearch(); } if (!this.search && isCharLetter(pressedKey)) { activateSearch(); } if (this.search && (isCharLetter(pressedKey) || pressedKey === "Backspace")) { var results; if (pressedKey === "Backspace") { this.searchTerm = this.searchTerm.slice(0, -1); } else { this.searchTerm += pressedKey; } if (this.searchTerm === "") { deactivateSearch(); } else if (this.searchTerm === ",") { this.search.clearResults(); } else { socketGateway.emit("searchUsers", this.searchTerm, function (args) { var originalText = args["originalText"]; results = this.search.createAndAttachResults({ "originalText": args.originalText, "users": args.users, "groups": [], "usersFilter": this.createUsersFilter() }, parent, function (args) { selectNameCallback(args); inputField.value = ""; inputField.focus(); deactivateSearch(); }.bind(this)); }.bind(this)); } } }; Room.prototype.createUsersFilter = function () { var filter = [], i, member; for (i = 0; i < this.members.length; i++) { member = this.members[i]; filter.push(member.userid); } filter.push(this.adminid); return filter; }; Room.prototype.resizeTextField = function (event, send) { if ( (event != undefined && event.keyCode == 13 && !event.shiftKey ) || send) { //save it event.preventDefault(); var message_text = this.textInput.value; if ( message_text != "" ) { this.textInput.enabled = false; this.textInput.value = ""; /*user feedback*/ this.input_feedback.style.display = "block"; clearTimeout( this.input_feedback_timeout ); this.input_feedback_timeout = setTimeout( function(){ this.input_feedback.style.display = "none"; }.bind(this), 1000 ) socketGateway.emit("createMessage", {"roomid": this.id, "text": message_text }, function (data) { if (data.status === "ok") { data.remove_last_time = this.infoStream.postInShortTime(data); this.infoStream.addPostAtEnd(data); var dimensions = this.getScrollDimensions(); this.infoStreamContainer.scrollTop = dimensions["fullHeight"] - dimensions["clientHeight"]; this.textInput.enabled = true; } }.bind(this)); } } }; /* Child of InfoStream. In this case there is a bigger difference to other children of InfoStream, since the posts are being arranged in another way, bottom-to-top. In this class the posts are given a different type depending on their location and surrounding posts. */ function RoomInfoStream() { var infoStream = new InfoStream(); var posts = infoStream.getPosts(); infoStream.addPostAtEnd = function (args) { assignTypeToRoomMessage(args); var post = new RoomPost(args); post.createElement(); infoStream.createNewPostListeners(post); infoStream.element.appendChild(post.element); infoStream.setPost(post); }; infoStream.addPostAtBeginning = function (args) { var post = new RoomPost(args); post.createElement(); infoStream.createNewPostListeners(post); infoStream.element.insertBefore(post.element, infoStream.element.firstChild); infoStream.setPost(post); }; infoStream.addOlderBefore = function (data) { var i, l = data.length; for (i = 0; i < l; i++) { var post = data[i]; if (!(post.postid in posts)) { post["type"] = infoStream.determineRoomMessageType(post, i, data); post["readerid"] = currentUser.id; infoStream.addPostAtBeginning(post); } } }; infoStream.postInShortTime = function( new_post ) { return false; var last_post = this.getLastPost(); if ( last_post != undefined ) { var date = new Date( new_post.timestamp ); var prev_date = new Date( last_post.timestamp ); return Math.abs(prev_date - date ) < ( 1 * 60 * 1000 ) } else { return false; } }; function assignTypeToRoomMessage(message) { var keys = Object.keys(posts); if(keys.length > 0){ var lastMessageid = Math.max.apply(null, keys); var lastPost = posts[lastMessageid]; var lastPostPosterName = lastPost.posterName; var lastPostType = lastPost.element.className; if ( message.userid == 0 ) { message.type = "system"; lastPost.element.className = "infostream-post room first system"; } else if( message.posterName === lastPostPosterName){ if(lastPostType === "infostream-post room firstLast"){ lastPost.element.className = "infostream-post room first"; } else if(lastPostType === "infostream-post room firstLast mine"){ lastPost.element.className = "infostream-post room first mine"; } else if(lastPostType === "infostream-post room last"){ lastPost.element.className = "infostream-post room middle"; } else if(lastPostType === "infostream-post room last mine"){ lastPost.element.className = "infostream-post room middle mine"; } if ( message.remove_last_time ) { lastPost.removeFooter(); } message.type = "last"; } else { message.type = "firstLast"; } } else{ message.type = "firstLast" } } return infoStream; } /* A screen containing two TagsScreens, a MentionScreen or a RepliedPostsChatScreen. Shows buttons on the subheader for each of these screens */ function TopicsScreen(header) { currentView.setNewView( { type : 'topics', id : 'all', onChangeView : null } ) var topicsScreen = {}; var currentScreen; var screenViewer = document.createElement("DIV"); topicsScreen.element = document.createElement("DIV"); topicsScreen.openTag = function (tag) { currentScreen.openTag(tag); }; topicsScreen.openStock = function (stock) { stocksButton.click(); //render stocks tab currentScreen.openStock(stock); }; var selectButton = function (button) { deselectButtons(); button.className = "submenu-bar-button selected"; }; var deselectButtons = function () { var buttons = document.getElementsByClassName("submenu-bar-button selected"); var i, l = buttons.length; for (i = 0; i < l; i++) { buttons[i].className = "submenu-bar-button"; } }; var latestTagsButton = document.createElement("BUTTON"); latestTagsButton.textContent = "Aktuelle Tags"; latestTagsButton.className = "submenu-bar-button"; latestTagsButton.onclick = function () { currentScreen.close(function () { currentScreen = new TagsScreen(screenViewer); socketGateway.emit("getLatestTags", {}, function (tagsArray) { currentScreen.createTags(tagsArray); }); selectButton(latestTagsButton); }); }; var hotTagsButton = document.createElement("BUTTON"); hotTagsButton.textContent = "Hottest Tags"; hotTagsButton.className = "submenu-bar-button"; hotTagsButton.onclick = function () { currentScreen.close(function () { currentScreen = new TagsScreen(screenViewer); socketGateway.emit("getHottestTags", {}, function (tagsArray) { currentScreen.createTags(tagsArray); }); selectButton(hotTagsButton); }); }; var stocksButton = document.createElement("BUTTON"); stocksButton.textContent = "Aktien"; stocksButton.className = "submenu-bar-button selected"; stocksButton.onclick = function () { currentScreen.close( function () { // currentScreen = new TagsScreen(screenViewer); // socketGateway.emit("getStocksInPosts", {}, function (stocksArray) { // currentScreen.createStocks(stocksArray); //}); topicsScreen.openStocksOverview(); }); }; header.appendChild(stocksButton); header.appendChild(latestTagsButton); header.appendChild(hotTagsButton); /*var mentionedButton = document.createElement("BUTTON"); mentionedButton.textContent = "Erwähnungen"; mentionedButton.className = "submenu-bar-button"; mentionedButton.onclick = function () { currentScreen.close(function () { currentScreen = new MentionScreen(screenViewer); currentScreen.createUI(); currentScreen.activateOnScroll(topicsScreen.element.parentNode); }); selectButton(mentionedButton); }; header.appendChild(mentionedButton); var repliedPostsButton = document.createElement("BUTTON"); repliedPostsButton.textContent = "Antworten"; repliedPostsButton.className = "submenu-bar-button"; repliedPostsButton.onclick = function () { currentScreen.close(function () { currentScreen = new RepliedPostsChatScreen(screenViewer); currentScreen.createUI(); currentScreen.activateOnScroll(topicsScreen.element.parentNode); }); selectButton(repliedPostsButton); }; header.appendChild(repliedPostsButton); */ topicsScreen.openStocksOverview = function(){ currentScreen = new OverviewScreen(currentUser.id, currentUser.username); currentScreen.createUI(); screenViewer.appendChild(currentScreen.element); currentScreen.activateOnScroll(topicsScreen.element.parentNode); selectButton(stocksButton); } topicsScreen.openTagsScreen = function(tag){ currentScreen.close(function () { currentScreen = new TagsScreen(screenViewer); socketGateway.emit("getLatestTags", {}, function (tagsArray) { currentScreen.createTags(tagsArray); if ( tag ) { currentScreen.openTag(tag); } }); selectButton(latestTagsButton); }); } currentScreen = new TagsScreen(screenViewer); /*socketGateway.emit("getLatestTags", {}, function (tagsArray) { currentScreen.createTags(tagsArray, TagsChatScreen); });*/ topicsScreen.element.appendChild(screenViewer); return topicsScreen; } /* A screen containing a list of tags. */ function TagsScreen(parent) { var tagsScreen = {}; tagsScreen.element = document.createElement("DIV"); var tagsContainer = document.createElement("DIV"); tagsContainer.className = "tags-container topics"; var chatScreen; var chatScreenElement = document.createElement("DIV"); tagsScreen.createTags = function (tags) { tagsContainer.textContent = ''; var i, tagsLength = tags.length; for (i = 0; i < tagsLength; i++) { var tagElement = document.createElement("DIV"); tagElement.className = "tag topics"; var opacityStep = 0.5 / tagsLength; tagElement.style.opacity = 1 - (i * opacityStep); var tag = tags[i]; tagElement.textContent = tag; tagElement.onclick = function () { if (chatScreen) { chatScreen.close(); } chatScreen = new TagsChatScreen(chatScreenElement, {"tags": [this.tagToSend]}); chatScreen.createUI(); chatScreen.activateOnScroll(parent.parentNode.parentNode); var children = tagsContainer.childNodes; var i, l = children.length; for (i = 0; i < l; i++) { children[i].className = "tag topics"; } this.tagElement.className = "tag topics selected"; }.bind({"tagToSend": tag, "tagElement": tagElement}); tagsContainer.appendChild(tagElement); } tagsScreen.element.appendChild(tagsContainer); tagsScreen.element.appendChild(chatScreenElement); }; tagsScreen.createStocks = function (stocks) { tagsContainer.textContent = ''; var i, tagsLength = stocks.length, opacityStep = 0.5 / tagsLength, stock, tagElement; for (i = 0; i < tagsLength; i++) { stock = stocks[i]; tagElement = document.createElement("DIV"); tagElement.className = "tag topics"; tagElement.style.opacity = 1 - (i * opacityStep); tagElement.textContent = stock.name; tagElement.onclick = function () { if (chatScreen) { chatScreen.close(); } chatScreen = new TagsChatScreen(chatScreenElement, {"stock": this.tagToSend}); chatScreen.createUI(); chatScreen.activateOnScroll(parent.parentNode.parentNode); var children = tagsContainer.childNodes; var i, l = children.length; for (i = 0; i < l; i++) { children[i].className = "tag topics"; } this.tagElement.className = "tag topics selected"; }.bind({ "tagToSend": { isin : stock.isin, source : stock.source }, "tagElement": tagElement}); tagsContainer.appendChild(tagElement); } tagsScreen.element.appendChild(tagsContainer); tagsScreen.element.appendChild(chatScreenElement); }; tagsScreen.openStock = function (stock) { if (chatScreen) { chatScreen.close(); } chatScreen = new TagsChatScreen(chatScreenElement, {"stock": stock}); chatScreen.createUI(); chatScreen.activateOnScroll(parent.parentNode.parentNode); var children = tagsContainer.childNodes; var i, l = children.length; for (i = 0; i < l; i++) { children[i].className = "tag topics"; } }; tagsScreen.openTag = function (tag) { if (chatScreen) { chatScreen.close(); } chatScreen = new TagsChatScreen(chatScreenElement, {"tags": [tag]}); chatScreen.createUI(); chatScreen.activateOnScroll(parent.parentNode.parentNode); var children = tagsContainer.childNodes; var i, l = children.length; for (i = 0; i < l; i++) { children[i].className = "tag topics"; } }; tagsScreen.close = function (onCloseCallback) { parent.removeChild(tagsScreen.element); onCloseCallback(); }; parent.appendChild(tagsScreen.element); return tagsScreen; } /* Child of ChatScreen. Contains no post editor but an infostream of posts the current user replied to. */ function RepliedPostsChatScreen(parent) { var repliedPostsChatScreen = new ChatScreen( currentUser.id, currentUser.username); repliedPostsChatScreen.fetchInfoStream = function (callback) { repliedPostsChatScreen.alreadyFetching = true; repliedPostsChatScreen.loading = document.createElement("DIV"); repliedPostsChatScreen.loading.textContent = "Loading more..."; repliedPostsChatScreen.loadingContainer.appendChild(repliedPostsChatScreen.loading); repliedPostsChatScreen.loadingContainer.className = "loading-more"; socketGateway.emit("loadRepliedPosts", { "numberOfPostsShown": repliedPostsChatScreen.numberOfPostsShown }, function (data) { repliedPostsChatScreen.moreToFetch = data["moreToFetch"]; repliedPostsChatScreen.loadingContainer.removeChild(repliedPostsChatScreen.loading); repliedPostsChatScreen.alreadyFetching = false; callback(data["posts"]); }); }; repliedPostsChatScreen.close = function (onCloseCallback) { parent.removeChild(repliedPostsChatScreen.element); onCloseCallback(); }; repliedPostsChatScreen.createUI = function () { repliedPostsChatScreen.output = document.createElement("DIV"); repliedPostsChatScreen.output.className = "infostream-output replies"; repliedPostsChatScreen.newPostsInfo = document.createElement("DIV"); repliedPostsChatScreen.newPostsInfo.className = "infostream-newPosts"; repliedPostsChatScreen.output.appendChild(repliedPostsChatScreen.newPostsInfo); repliedPostsChatScreen.element.appendChild(repliedPostsChatScreen.output); repliedPostsChatScreen.infoStream = new InfoStream(currentUser.username, currentUser.id); repliedPostsChatScreen.loadInfoStream(); }; parent.appendChild(repliedPostsChatScreen.element); return repliedPostsChatScreen; } /* Child of ChatScreen. Contains no post editor but an infostream of posts related to a given tag. */ function TagsChatScreen(parent, args) { var tagsChatScreen = new ChatScreen(currentUser.id, currentUser.username); tagsChatScreen.fetchInfoStream = function (callback) { tagsChatScreen.alreadyFetching = true; tagsChatScreen.loading = document.createElement("DIV"); tagsChatScreen.loading.textContent = "Loading more..."; tagsChatScreen.loadingContainer.appendChild(tagsChatScreen.loading); tagsChatScreen.loadingContainer.className = "loading-more"; if ( args.tags != undefined ) { socketGateway.emit("getPostsFromTags", { "numberOfPostsShown": tagsChatScreen.numberOfPostsShown, "tags": args.tags }, function (data) { tagsChatScreen.moreToFetch = data["moreToFetch"]; tagsChatScreen.loadingContainer.removeChild(tagsChatScreen.loading); tagsChatScreen.alreadyFetching = false; callback(data["posts"]); }); } else if ( args.stock != undefined ) { socketGateway.emit("getPostsFromStockISIN", { "numberOfPostsShown": tagsChatScreen.numberOfPostsShown, "isin": args.stock.isin }, function (data) { tagsChatScreen.moreToFetch = data["moreToFetch"]; tagsChatScreen.loadingContainer.removeChild(tagsChatScreen.loading); tagsChatScreen.alreadyFetching = false; callback(data["posts"]); }); } }; tagsChatScreen.createUI = function () { tagsChatScreen.output = document.createElement("DIV"); tagsChatScreen.output.className = "infostream-output tags"; tagsChatScreen.newPostsInfo = document.createElement("DIV"); tagsChatScreen.newPostsInfo.className = "infostream-newPosts"; tagsChatScreen.output.appendChild(tagsChatScreen.newPostsInfo); tagsChatScreen.element.appendChild(tagsChatScreen.output); tagsChatScreen.infoStream = new InfoStream(currentUser.username, currentUser.id); tagsChatScreen.loadInfoStream(); }; tagsChatScreen.close = function (onCloseCallback) { parent.removeChild(tagsChatScreen.element); if(onCloseCallback){ onCloseCallback(); } }; parent.appendChild(tagsChatScreen.element); return tagsChatScreen; } /* Child of ChatScreen. Contains no post editor but an infostream of posts the current user was mentioned in. */ function MentionScreen(parent) { var mentionScreen = new ChatScreen(currentUser.id, currentUser.username); mentionScreen.fetchInfoStream = function (callback) { mentionScreen.alreadyFetching = true; mentionScreen.loading = document.createElement("DIV"); mentionScreen.loading.textContent = "Loading more..."; mentionScreen.loadingContainer.appendChild(mentionScreen.loading); mentionScreen.loadingContainer.className = "loading-more"; socketGateway.emit("getPostsWithMentions", { "numberOfPostsShown": mentionScreen.numberOfPostsShown }, function (data) { mentionScreen.moreToFetch = data["moreToFetch"]; mentionScreen.loadingContainer.removeChild(mentionScreen.loading); mentionScreen.alreadyFetching = false; callback(data["posts"]); }); }; mentionScreen.createUI = function () { mentionScreen.output = document.createElement("DIV"); mentionScreen.output.className = "infostream-output tags"; mentionScreen.newPostsInfo = document.createElement("DIV"); mentionScreen.newPostsInfo.className = "infostream-newPosts"; mentionScreen.output.appendChild(mentionScreen.newPostsInfo); mentionScreen.element.appendChild(mentionScreen.output); mentionScreen.infoStream = new InfoStream(currentUser.username, currentUser.id); mentionScreen.loadInfoStream(); }; mentionScreen.close = function (onCloseCallback) { parent.removeChild(mentionScreen.element); if(onCloseCallback){ onCloseCallback(); } }; parent.appendChild(mentionScreen.element); return mentionScreen; } /* A screen containing the main infostream and the post editor */ function MarketPlaceScreen () { var mpScreen = {}; var types_nicer = { 'user' : "Personen", "bot" : "Bots", "group" : "Gruppen" } mpScreen.element = document.createElement("DIV"); mpScreen.element.style.height = "100%"; mpScreen.output; mpScreen.tabs; mpScreen.render; mpScreen.loadingContainer = document.createElement("DIV"); mpScreen.loading; var types_sections = {}; var selected_type = ""; var selectType = function( type ) { if ( selected_type == type ) { return; } for ( var key in types_sections ) { if ( key == type ) { types_sections[key]["element"].style.display = "block"; types_sections[key]["menu"].className += " selected"; } else { types_sections[key]["element"].style.display = "none"; types_sections[key]["menu"].className = types_sections[key]["menu"].className.replace(" selected", ""); } } selected_type = type; }; var createMarketProduct = function( product ) { var element = document.createElement("div"); element.className = "market-product"; var image = document.createElement("img"); image.src = projectDomainProd + product.picture; image.style.float = "left"; image.style.borderRadius = "5px"; image.style.width = "100px"; image.style.height = "100px"; var text = document.createElement("div"); text.style.float = "left"; text.style.fontSize = "14px"; text.style.marginLeft = "10px"; text.style.width = "calc( 100% - 160px )"; text.style.height = "150px"; text.style.overflow = "auto"; var title = document.createElement("div"); title.className = "market-product-title"; title.style.float = "left"; title.textContent = product.title; title.onclick = function(event) { if ( product.user_id != null ) { currentHome.userByChatId(product.user_id); } else if ( product.group_id != null ) { currentHome.group(product.group_id); } } var description = document.createElement("div"); description.style.float = "left"; description.style.clear = "both"; description.textContent = product.description; var description = document.createElement("div"); description.style.float = "left"; description.style.clear = "both"; description.textContent = product.description; text.appendChild( title ); text.appendChild( description ); if ( currentUser.id != null ) { var follow_link = document.createElement("div"); follow_link.className = "market-product-button " + (product.following ? "unfollow" : "follow"); follow_link.textContent = product.following ? "Entfolgen" : "Folgen"; follow_link.onclick = function(event) { if ( product.user_id != null ) { if (product.following) { alertManager.ask("Nutzer entfolgen?", function () { socketGateway.emit("unfollowUser", { "id": product.user_id }, function () { follow_link.textContent = "Folgen"; follow_link.className = follow_link.className.replace( "unfollow", "follow" ); product.following = false; }); }); } else { //todo check for user permission needed here if ( product.permission == null || currentUser.allowed_permissions[product.permission] ) { alertManager.ask("Nutzer folgen?", function () { socketGateway.emit("followUser", { "id": product.user_id }, function (data) { if (data.result) { follow_link.className = follow_link.className.replace( "follow", "unfollow" ); follow_link.innerHTML = "Entfolgen"; product.following = true; } }); }); } else { helper.createAdsWindow( permsLinks[product.permission].img, permsLinks[product.permission].order ) } } } else if ( product.group_id != null ) { currentHome.group(product.group_id); } } text.appendChild( follow_link ); } element.appendChild( image ); element.appendChild( text ); if ( types_sections[product.type] == undefined ) { types_sections[product.type] = {}; types_sections[product.type]["element"] = document.createElement("div"); types_sections[product.type]["element"].style.display = "none"; types_sections[product.type]["element"].style.clear = "both"; types_sections[product.type]["element"].style.width = "100%"; types_sections[product.type]["menu"] = document.createElement("button"); types_sections[product.type]["menu"].onclick = function(event){ selectType( product.type ); } types_sections[product.type]["menu"].className = "submenu-bar-button"; types_sections[product.type]["menu"].style.fontSize = "15px"; types_sections[product.type]["menu"].textContent = types_nicer[product.type] != undefined ? types_nicer[product.type] : product.type; mpScreen.render.appendChild( types_sections[product.type]["element"] ); mpScreen.tabs.appendChild( types_sections[product.type]["menu"] ); } types_sections[product.type]["element"].appendChild( element ); }; var getMarketPlace = function(){ socketGateway.emit("getMarketPlace", {}, function (response) { if( response.result ) { var market = response.data; if ( market.length > 0 ) { mpScreen.output.textContent = ""; mpScreen.tabs = document.createElement("div"); mpScreen.tabs.className = "home-subheader"; mpScreen.render = document.createElement("div"); mpScreen.render.style.float = "left"; mpScreen.render.style.width = "100%"; mpScreen.render.style.padding = "10px"; mpScreen.render.style.marginTop = "30px"; mpScreen.output.appendChild(mpScreen.tabs); mpScreen.output.appendChild(mpScreen.render); for ( var i = 0; i < market.length; i++ ) { createMarketProduct( market[i] ) } selectType("user"); } else { mpScreen.output.textContent = "No active marketplace service." } } else { mpScreen.output.textContent = "Loading Marketplace failed. Please try again." } }); } ////////////////////////////////////////////////////////////////////////////////////////////////////// // PUBLIC ////////////////////////////////////////////////////////////////////////////////////////////////////// mpScreen.createUI = function () { mpScreen.output = document.createElement("DIV"); mpScreen.output.textContent = "";// "Loading marketplace"; mpScreen.output.className = "infostream-output"; mpScreen.output.style.padding = "10px"; mpScreen.output.style.height = "100%"; //todo create a header with options Personen, Gruppen, Bots //todo create a render area for every option in header mpScreen.element.appendChild(mpScreen.output); getMarketPlace(); }; return mpScreen; } function Home(element) { currentView = new viewManager(); premiumTeams = { 616 : 'trader-chat', 617 : 'trader-chat', 967 : 'index_trader' } permsLinks = { "login": { "img": "#", "order": "#", "abo" : "Login" }, "dpa-afx": { "img": "https://desk.traderfox.com/img/dpa-ads.PNG", "order": "https://traderfox.de/order-services/", "abo" : "TraderFox News-Terminal" }, "trader-chat": { "img": projectDomain + "/public/images/complete-hinweis.png", "order": "https://traderfox.de/bestellung/?step=0", "abo" : "TraderFox Complete" }, "portfolio-builder": { "img": "https://traderfox.de/img/ninjatrading_de.png", "order": "https://ninjacademy.traderfox.de/system-trading-room", "abo" : "System-Trading-Room" }, "software": { "img": projectDomain + "/public/images/premium-hinweis.png", "order": "https://traderfox.de/bestellung/?step=0", "abo" : "TraderFox Börsensoftware" }, "live-trading": { "img": projectDomain + "/public/images/complete-hinweis.png", "order": "https://traderfox.de/bestellung/?step=0", "abo" : "TraderFox Complete" }, "permission_ninja": { "img": "https://traderfox.de/img/ninjatrading_de.png", "order": "https://ninjacademy.traderfox.de/", "abo" : "TraderFox Börsensoftware" }, "system-trading-room": { "img": "https://traderfox.de/img/ninjatrading_de.png", "order": "https://ninjacademy.traderfox.de/system-trading-room", "abo" : "System-Trading-Room" }, "chatrooms": { "img": projectDomain + "/public/images/complete-hinweis.png", "order": "https://traderfox.de/bestellung/?step=0", "abo" : "TraderFox Complete" }, "strategy_neo_darvas": { "img": projectDomain + "/public/images/traderfox-strategy.PNG", "order": "https://traderfox.de/produkte/strategien/", "abo" : "Traderfox Strategien" }, "strategy_shortterm": { "img": projectDomain + "/public/images/traderfox-strategy.PNG", "order": "https://traderfox.de/produkte/strategien/", "abo" : "Traderfox Strategien" }, "strategien_select": { "img": projectDomain + "/public/images/traderfox-strategy.PNG", "order": "https://traderfox.de/produkte/strategien/", "abo" : "Traderfox Strategien" }, "index_trader": { "img": projectDomain + "/public/images/traderfox-strategy.PNG", "order": "https://traderfox.de/produkte/strategien/", "abo" : "Index Trader" } }; var home = {} var live_counter = 0; var live_counter_interval = null; var load_more_button = document.createElement('DIV'); load_more_button.className = "load-more-main-button"; load_more_button.textContent = "mehr..."; load_more_button.onclick = function( event ) { if ( viewElement.onscroll != null ) { viewElement.onscroll(true); } event.preventDefault(); event.stopPropagation(); } var id, username, timestamp, picturePath; var latestPostTimestamp = timestamp ? timestamp : new Date().toISOString(); var actionQueue = []; var apiQueue = []; /* how to write an action in the queue { "function": , "context": , "args": , "callback": } */ var chatLoaded = false; var can_reconnect = true; var header; var buttons_container = document.createElement('DIV'); buttons_container.className = "head-buttons-container"; var buttons_scroll_wrapper = document.createElement('DIV'); buttons_scroll_wrapper.className = "head-buttons-wrapper"; buttons_container.appendChild( buttons_scroll_wrapper ); var subheader; var chatButton; var chatCounter = 0; var streamButton; var streamCounter = 0; var groupCounter = 0; var groupsButton; var liveContentButton; var followedTradersButton; var topicsButton; var roomsButton; var teamsButton; var searchField; var viewElement; var notificationCenter = new NotificationCenter(); eventManager = new ChatEventManager(); //declaration in builder var onReadyCallback; eventManager.onChatReady(this, function () { chatLoaded = true; performActionsInQueue(); performActionsInAPIQueue(); }); notificationCenter.onClick(function () { //clearScreen(); //createUI(); deselectButtons(); }); var fetchingInfoStream = false; var profileViewer; var groupViewer; var groupInfoViewer; var roomViewer; var currentScreen; var currentScreenType; var offlineButtonCallback; var returnButton; var isUserLoggedIn = function () { return id !== undefined; }; /*socketGateway.subscribe("livePosting", function (args) { if ( args.type == 'start' ) { live_counter++; home.setLiveCounter(live_counter) } else if ( args.type == 'end' ) { live_counter--; home.setLiveCounter(live_counter) } //todo inform subscribers if ( home.subscribers['livePosting'] != undefined ) { var i, l = home.subscribers['livePosting'].length; for ( i = 0; i < l; i++ ) { home.subscribers['livePosting'][i].fn.call( home.subscribers['livePosting'][i].ctx, args ) } } }); */ socketGateway.subscribe("getProfile", function (args) { home.getProfile(args); }); home.showUserFeedback = function( message, x, y ) { notificationCenter.showUserFeedback( message, x, y ) }; home.subscribers = {}; home.subscribe = function( type, fn, ctx ) { if ( home.subscribers[type] == undefined ) { home.subscribers[type] = []; } home.subscribers[type].push( { fn : fn, ctx : ctx } ); } home.unsubscribe = function( type, fn, ctx ) { if ( home.subscribers[type] != undefined ) { var i, l = home.subscribers[type].length; for ( i = 0; i < l; i++ ) { if ( home.subscribers[type][i].fn == fn && home.subscribers[type][i].ctx == ctx ) { home.subscribers[type].splice( i, 1 ); } } } } home.getProfile = function (args) { load_more_button.style.display = "block"; home.autoPostEditor = null; clearReturnButton(); returnButton = document.createElement("BUTTON"); returnButton.className = "return"; returnButton.textContent = "<"; returnButton.title = "Return"; returnButton.onclick = function () { profileViewer.deactivateOnScroll(); profileViewer.element.parentNode.scrollTop = 0; clearProfileViewer(); clearReturnButton(); if (currentScreen) { viewElement.appendChild(currentScreen.element); } }; if (profileViewer) { clearProfileViewer(); } else if (groupViewer) { clearGroupViewer(); } else if (groupInfoViewer) { clearGroupInfoViewer(); } else if(roomViewer){ clearRoomViewer(); } //header.insertBefore(returnButton, chatButton); clearViewScreen(); clearSubheader(); profileViewer = new PublicProfile(args); viewElement.appendChild(profileViewer.element); //profileViewer.activateOnScroll('comments'); if ( args.tab != undefined ) { profileViewer.selectTab( args.tab ); } else { profileViewer.selectTab( 'comments' ); } deselectButtons(); }; var showBanNotification = function () { var banElement = document.createElement("DIV"); var banTitle = document.createElement("H2"); banTitle.textContent = "Sie wurden für den Chat gesperrt"; var banText = document.createElement("DIV"); banText.appendChild(document.createTextNode("Um die Sperre aufzuheben, schreiben Sie bitte an ")); var email = document.createElement("A"); email.href = "mailto:info@traderfox.de"; email.textContent = "info@traderfox.de"; banText.appendChild(email); banText.appendChild(document.createTextNode(" mit Betreff \"Sperrung aufheben\". Entschuldigen Sie sich in dieser Email und versprechen Sie, in Zukunft die Chat-Regeln einzuhalten")); banElement.appendChild(banTitle); banElement.appendChild(banText); alertManager.inform(banElement, function () { }, true); }; socketGateway.subscribe("logoutUser", function () { home.logout(); showBanNotification(); }); socketGateway.subscribe("openGroup", function (args) { openGroup(args); }); socketGateway.subscribe("getGroupInfo", function (args) { getGroupInfo(args); }); socketGateway.subscribe("roomInvitation", function (args) { notificationCenter.addNotification("room-invite", args); currentHome.api.sendEvent( { 'type' : 'notification', 'event' : 'update-rooms', 'value' : '' } ) }); socketGateway.subscribe("room-member-waiting", function (args) { notificationCenter.addNotification("room-member-waiting", args); currentHome.api.sendEvent( { 'type' : 'notification', 'event' : 'update-rooms', 'value' : '' } ) }); var getGroupInfo = function (args) { selectButton(groupsButton); clearReturnButton(); returnButton = document.createElement("BUTTON"); returnButton.className = "return"; returnButton.textContent = "<"; returnButton.title = "Return"; returnButton.onclick = function () { closeGroupInfoViewer(); }; if (groupInfoViewer) { clearGroupInfoViewer(); } else { if (groupViewer) { clearGroupViewer(); } else if (profileViewer) { clearProfileViewer(); } // header.insertBefore(returnButton, chatButton); } args["userid"] = id; clearViewScreen(); clearSubheader(); groupInfoViewer = new GroupInfo(args); groupInfoViewer.onLeave(function () { home.group(args.id); currentHome.api.sendEvent( { 'type' : 'notification', 'event' : 'update-groups', 'value' : 'leave' } ); /* if (currentScreen.groups) { currentScreen.convertMyGroupToOtherGroup(args.id); } closeGroupInfoViewer(); */ }); groupInfoViewer.onJoin(function () { home.group(args.id); currentHome.api.sendEvent( { 'type' : 'notification', 'event' : 'update-groups', 'value' : 'join' } ); /*if (currentScreen.groups) { currentScreen.convertOtherGroupToMyGroup(args.id); } closeGroupInfoViewer(); */ }); viewElement.appendChild(groupInfoViewer.element); viewElement.scrollTop = 0; load_more_button.style.display = "none"; home.autoPostEditor = null; }; var height; socketGateway.subscribe("addContactPost", function (args) { if (args.isMentioned) { notificationCenter.addNotification('mentioned-post', args); } else { notificationCenter.addNotification('contact-post', args); } if (currentScreenType === "ChatScreen") { if (!height) { height = viewElement["scrollHeight"]; } var sh = viewElement["scrollHeight"], st = viewElement["scrollTop"]; if (st > 0 && sh >= height) { currentScreen.infoStream.addPostAtBeginning({ "postid": args.id, "posterName": args.username, "posterid": args.posterid, "readerid": id, "timestamp": args.timestamp, "text": args.text, "attachments": args.attachments, "tags": args.tags, "stocks": args.stocks, "news": args.news, "cloud": args.cloud, "edited": false, "likeStatus": false, "picturePath": args.picturePath, "nice_title" : args.nice_title, "wikifolio" : args.wikifolio }); viewElement["scrollTop"] = st + sh - height; } else { currentScreen.createLoadButton(function () { notificationCenter.resetCounter(); }); } height = sh; } }, home); socketGateway.subscribe("addGroupMemberPost", function (args) { if ( args.origin == "stream" ) { // console.log( 'about stream, do nothing.' ) // console.log( args ) } else { notificationCenter.addNotification('group-post', args); if ( currentView.type == 'groups' && currentView.id == args.groupid ){ } else { //here update Gruppen in menubar groupCounter++; groupsButton.textContent = "Gruppen (" + groupCounter + ")"; currentHome.api.sendEvent( { 'type' : 'notification', 'event' : 'new-group-post', 'value' : args.groupid } ) } //inform anyone who wants to be informed abut new posts; if ( home.subscribers['newMemberPost'] != undefined ) { var i, l = home.subscribers['newMemberPost'].length; for ( i = 0; i < l; i++ ) { home.subscribers['newMemberPost'][i].fn.call( home.subscribers['newMemberPost'][i].ctx, args ) } } } }, home); socketGateway.subscribe("newOtherUserReply", function (args) { notificationCenter.addNotification("reply", args); }); socketGateway.subscribe("adminDeletePost", function (args) { switch (currentScreenType) { case "ChatScreen": currentScreen.infoStream.deletePost(args.postid); break; case "GroupsScreen": if (groupViewer) { groupViewer.chatScreen.infoStream.deletePost(args.postid); } break; } }); socketGateway.subscribe("adminDeleteReply", function (args) { var post; switch (currentScreenType) { case "ChatScreen": post = currentScreen.infoStream.getPost(args.postid); post.removeReply(args.replyid); break; case "GroupsScreen": if (groupViewer) { post = groupViewer.chatScreen.infoStream.getPost(args.postid); post.removeReply(args.replyid); } break; } }); socketGateway.subscribe("roomMessage", function (args) { notificationCenter.addNotification("room-message", args); currentHome.api.sendEvent( { 'type' : 'notification', 'event' : 'new-room-message', 'value' : args.roomid } ) /* if roomMessage for currently open room show it else show notification */ }); var openGroup = function (args) { load_more_button.style.display = "block"; selectButton(groupsButton); var closeGroupViewer = function () { clearGroupViewer(); clearReturnButton(); if (currentScreen) { viewElement.appendChild(currentScreen.element); } }; var leaveGroup = function (groupid) { home.group(groupid); currentHome.api.sendEvent( { 'type' : 'notification', 'event' : 'update-groups', 'value' : 'leave' } ); /*if (currentScreen.groups) { currentScreen.convertMyGroupToOtherGroup(groupid); } closeGroupViewer(); */ }; clearReturnButton(); returnButton = document.createElement("BUTTON"); returnButton.className = "return"; returnButton.textContent = "<"; returnButton.title = "Return"; returnButton.onclick = function (event) { closeGroupViewer(); }; if (groupViewer) { clearGroupViewer(); } else { if (profileViewer) { clearProfileViewer(); } else if (groupInfoViewer) { clearGroupInfoViewer(); } } //header.insertBefore(returnButton, chatButton); clearViewScreen(); clearSubheader(); groupViewer = new Group({ "groupid": args.groupid, "groupName": args.groupName, "userid": id, "username": username, "latestPostTimestamp": latestPostTimestamp, "membersCount": args.membersCount, "picture": args.picturePath, "isAdmin": args.adminid !== undefined ? args.adminid === id : args.isAdmin, "description": args.description, "writers": args.writers }); groupViewer.onLeave(leaveGroup); viewElement.appendChild(groupViewer.element); groupViewer.chatScreen.activateOnScroll(viewElement); }; var showPost = function (post, closeCallback) { var element = document.createElement("DIV"); element.className = "element-blocker"; element.onclick = function (event) { event.stopPropagation(); event.preventDefault(); close(); }; var postContainer = document.createElement("DIV"); postContainer.className = "popup-post"; var closeButton = document.createElement("BUTTON"); closeButton.className = "pop-up-container close"; closeButton.onclick = function (event) { event.stopPropagation(); event.preventDefault(); close(); }; post.createElement(); post.element.onclick = function (event) { event.stopPropagation(); }; var postWithScrollbarContainer = document.createElement("DIV"); postWithScrollbarContainer.className = "pop-up-container"; postContainer.appendChild(post.element); postWithScrollbarContainer.appendChild(postContainer); postWithScrollbarContainer.appendChild(closeButton); element.appendChild(postWithScrollbarContainer); var close = function () { home.element.removeChild(element); if (closeCallback) { closeCallback(post); } }; home.element.appendChild(element); post.initialize(); return element; }; var clearSubheader = function () { if (subheader && subheader.parentNode === header) { header.removeChild(subheader); subheader = undefined; viewElement.className = "home-viewer"; } }; var performActionsInQueue = function () { //only the last action is being performed var lastIndex = actionQueue.length - 1; if (lastIndex >= 0) { var action = actionQueue[lastIndex]; var func = action["function"]; var context = action["context"]; var args = action["args"]; var callback = action["callback"]; func.call(context, args, callback); actionQueue = []; } }; var performActionsInAPIQueue = function () { if ( apiQueue.length > 0 ) { var action = apiQueue[0]; var func = action["function"]; var context = action["context"]; var args = action["args"]; var callback = action["callback"]; func.call(context, args, callback); apiQueue.shift(); if ( apiQueue.length > 0 ) { performActionsInAPIQueue(); } } }; var createChatScreen = function () { if( environment === "tradingdesk" ){ if (currentHome.externalAction != null) { currentHome.externalAction.fn.call(currentHome.externalAction.context, { 'type' : 'group', id : null } ) } } if (!isUserLoggedIn()) { latestPostTimestamp = new Date().toISOString(); } if (currentScreen ) { if ( currentScreen.removeListeners ) { currentScreen.removeListeners(); } if (currentScreen.deactivateOnScroll) { currentScreen.deactivateOnScroll(viewElement); } } clearReturnButton(); currentScreen = new ChatScreen(id, username, latestPostTimestamp); currentScreen.createUI(); currentScreenType = "ChatScreen"; currentScreen.onInfoStream(function () { fetchingInfoStream = false; }); currentScreen.onNewPost(function (newTimestamp, posterid, username) { latestPostTimestamp = newTimestamp; if (id !== posterid) { notificationCenter.increment(); } }); }; var createOverviewScreen = function () { if (currentScreen ) { if ( currentScreen.removeListeners ) { currentScreen.removeListeners(); } if (currentScreen.deactivateOnScroll) { currentScreen.deactivateOnScroll(viewElement); } } clearReturnButton(); currentScreen = new OverviewScreen(id, username); currentScreen.createUI(); currentScreenType = "OverviewScreen"; }; var loadChat = function () { if ( currentUser.id == null ) { return; } if (!fetchingInfoStream) { fetchingInfoStream = true; setTimeout(function () { fetchingInfoStream = false; }, 15000); clearViewScreen(); createChatScreen(); clearSubheader(); viewElement.appendChild(currentScreen.element); currentScreen.activateOnScroll(viewElement); selectButton(chatButton); load_more_button.style.display = "block"; } }; var openOverview = function () { clearViewScreen(); createOverviewScreen(); clearSubheader(); viewElement.appendChild(currentScreen.element); currentScreen.activateOnScroll(viewElement); }; var openMyStream = function () { loadStream(); }; var openMarketPlace = function () { load_more_button.style.display = "none"; if (currentScreen ) { clearViewScreen(); if ( currentScreen.removeListeners ) { currentScreen.removeListeners(); } if (currentScreen.deactivateOnScroll) { currentScreen.deactivateOnScroll(viewElement); } } currentScreen = new MarketPlaceScreen(); currentScreen.createUI(); currentScreenType = "MarketPlaceScreen"; viewElement.appendChild(currentScreen.element); }; var loadLive = function(){ /* clearViewScreen(); clearReturnButton(); clearSubheader(); if (currentScreen.deactivateOnScroll) { currentScreen.deactivateOnScroll(viewElement); } currentScreenType = "LiveContent"; currentScreen = new LiveScreen(); viewElement.appendChild(currentScreen.element); selectButton(liveContentButton); load_more_button.style.display = "none"; home.autoPostEditor = null; */ }; var loadStream = function () { if (!fetchingInfoStream) { fetchingInfoStream = true; setTimeout(function () { fetchingInfoStream = false; }, 15000); clearViewScreen(); createStreamScreen(); clearSubheader(); viewElement.appendChild(currentScreen.element); currentScreen.activateOnScroll(viewElement); selectButton(streamButton); } load_more_button.style.display = "block"; home.autoPostEditor = null; }; var createStreamScreen = function() { currentView.setNewView( { type : 'stream', id : 'main', onChangeView : null } ) if (!isUserLoggedIn()) { latestPostTimestamp = new Date().toISOString(); } if (currentScreen ) { if ( currentScreen.removeListeners ) { currentScreen.removeListeners(); } if (currentScreen.deactivateOnScroll) { currentScreen.deactivateOnScroll(viewElement); } } clearReturnButton(); //todo create a Stream screen currentScreen = new StreamScreen(id, username); currentScreen.createUI(); currentScreenType = "StreamScreen"; currentScreen.onInfoStream(function () { fetchingInfoStream = false; }); currentScreen.onNewPost(function (newTimestamp, posterid, username) {}); }; var createRulesElement = function (textPartsArray) { var bulletMode = false; var bulletUL; /*var rulesContainer = document.createElement("DIV"); rulesContainer.className = "rules-container"; rulesContainer.style.cssText = "height: 100%;position: absolute;overflow-y: scroll;width: 100%;"; */ var rulesElement = document.createElement("DIV"); rulesElement.className = "rules-element"; rulesElement.style.cssText = "height: 100%; position: absolute; overflow-y: scroll;"; var rulesText = document.createElement("DIV"); rulesText.className = "rules-text"; for (var i = 0; i < textPartsArray.length; i++) { var textPart = textPartsArray[i]; var type = textPart.type; var text = textPart.line_text; var element; switch (type) { case "bullet": if (!bulletMode) { activateBulletMode(); } element = document.createElement("LI"); element.textContent = text; break; case "title": if (bulletMode) { deactivateBulletModeAndAttach(); } element = document.createElement("H3"); element.textContent = text; break; case "normal": if (bulletMode) { deactivateBulletModeAndAttach(); } element = document.createElement("DIV"); element.textContent = text; break; case "break": if (bulletMode) { deactivateBulletModeAndAttach(); } element = document.createElement("BR"); break; } if(bulletMode){ bulletUL.appendChild(element); } else{ rulesText.appendChild(element); } } rulesElement.appendChild(rulesText); function deactivateBulletModeAndAttach() { bulletMode = false; rulesText.appendChild(bulletUL); } function activateBulletMode() { bulletMode = true; bulletUL = document.createElement("UL"); } //rulesContainer.appendChild(rulesElement); return rulesElement; }; var createUI = function () { createChatScreen(); header = document.createElement("DIV"); header.className = "home-header"; viewElement = document.createElement("DIV"); viewElement.className = "home-viewer"; searchField = new SearchField(header); var rulesButton = document.createElement("BUTTON"); rulesButton.className = "rules-button"; rulesButton.textContent = "Regeln"; rulesButton.onclick = function () { socketGateway.emit("getRules", {}, function (rulesArray) { alertManager.scrollableInform(createRulesElement(rulesArray), function () { }, true); }); }; header.appendChild(rulesButton); createMenu(); // header.appendChild(buttons_container); socketGateway.unsubscribe("timeline|update", home); socketGateway.subscribe("timeline|update", function ( data ) { if ( data.in_stream ) { // streamCounter++; // streamButton.innerHTML = "Stream •"; //(" + streamCounter + ")"; // currentHome.api.sendEvent( { 'type' : 'notification', 'event' : 'new-stream-message', 'value' : data } ); } if ( data.origin != 'stream' ) { chatCounter++; chatButton.textContent = "Chat (" + chatCounter + ")"; if ( data.type == "reply" && data.groupid != undefined ) { //inform anyone who wants to be informed about new replies in posts. Used by the auto update module. if ( home.subscribers['newMemberPost'] != undefined ) { var i, l = home.subscribers['newMemberPost'].length; for ( i = 0; i < l; i++ ) { home.subscribers['newMemberPost'][i].fn.call( home.subscribers['newMemberPost'][i].ctx, data ) } } } if ( data.type == 'group-post' ) { currentHome.api.sendEvent( { 'type' : 'notification', 'event' : 'new-group-message', 'value' : data } ); } else { currentHome.api.sendEvent( { 'type' : 'notification', 'event' : 'new-message', 'value' : data } ); } } }, home); if (isUserLoggedIn()) { chatCounter = 0; chatButton = document.createElement("BUTTON"); chatButton.className = "chat menu-bar-button selected"; chatButton.textContent = "Chat"; chatButton.onclick = function () { chatCounter = 0; chatButton.textContent = "Chat"; loadChat(); }; var ic = document.createElement("BUTTON"); ic.className = " menu-bar-button fa fa-comment"; ic.style.paddingRight = "0px"; ic.style.paddingLeft = "8px"; buttons_scroll_wrapper.appendChild(ic); buttons_scroll_wrapper.appendChild(chatButton); /* streamCounter = 0; streamButton = document.createElement("BUTTON"); streamButton.className = "stream menu-bar-button"; streamButton.textContent = "Stream"; streamButton.onclick = function () { streamCounter = 0; streamButton.textContent = "Stream"; loadStream(); }; buttons_scroll_wrapper.appendChild(streamButton); */ groupCounter = 0; groupsButton = document.createElement("BUTTON"); groupsButton.className = "groups menu-bar-button"; groupsButton.textContent = "Gruppen"; groupsButton.onclick = function () { openGroups(); }; var ic = document.createElement("BUTTON"); ic.className = " menu-bar-button fa fa-users"; ic.style.paddingRight = "0px"; ic.style.paddingLeft = "8px"; buttons_scroll_wrapper.appendChild(ic); buttons_scroll_wrapper.appendChild(groupsButton); /* liveContentButton = document.createElement("BUTTON"); liveContentButton.className = "live menu-bar-button"; liveContentButton.textContent = "Live"; liveContentButton.onclick = function () { loadLive(); }; //buttons_scroll_wrapper.appendChild(liveContentButton); socketGateway.emit( 'getNumberOfLivePostings', {} ,function( data ){ home.setLiveCounter( data ); } ); setInterval( function(){ //request to sync counter in case of lost session or fake client. socketGateway.emit( 'getNumberOfLivePostings', {} ,function( data ){ home.setLiveCounter( data ); } ); }, 7 * 1000 ) */ /* followedTradersButton = document.createElement("BUTTON"); followedTradersButton.className = "following menu-bar-button"; followedTradersButton.textContent = "Folge ich"; followedTradersButton.onclick = function () { clearViewScreen(); clearReturnButton(); clearSubheader(); if (currentScreen.deactivateOnScroll) { currentScreen.deactivateOnScroll(viewElement); } currentScreenType = "FollowsScreen"; currentScreen = new FollowsScreen(id, id); viewElement.appendChild(currentScreen.element); selectButton(followedTradersButton); }; header.appendChild(followedTradersButton); */ roomsButton = document.createElement("BUTTON"); roomsButton.className = "rooms menu-bar-button"; roomsButton.textContent = "Nachrichten"; roomsButton.onclick = function () { showRooms(function(){}, 'private' ); }; var ic = document.createElement("BUTTON"); ic.className = " menu-bar-button fa fa-envelope"; ic.style.paddingRight = "0px"; ic.style.paddingLeft = "8px"; buttons_scroll_wrapper.appendChild(ic); buttons_scroll_wrapper.appendChild(roomsButton); teamsButton = document.createElement("BUTTON"); teamsButton.className = "rooms menu-bar-button"; teamsButton.textContent = "Teams"; teamsButton.onclick = function () { showRooms(function(){}, 'teams' ); }; var ic = document.createElement("BUTTON"); ic.className = " menu-bar-button fa fa-comments"; ic.style.paddingRight = "0px"; ic.style.paddingLeft = "8px"; buttons_scroll_wrapper.appendChild(ic); buttons_scroll_wrapper.appendChild(teamsButton); topicsButton = document.createElement("BUTTON"); topicsButton.className = "topics menu-bar-button"; topicsButton.textContent = "Aktien im Gespräch"; topicsButton.onclick = function () { showTopics(); }; var ic = document.createElement("BUTTON"); ic.className = " menu-bar-button fa fa-thumbs-up"; ic.style.paddingRight = "0px"; ic.style.paddingLeft = "8px"; buttons_scroll_wrapper.appendChild(ic); buttons_scroll_wrapper.appendChild(topicsButton); } home.element.appendChild(header); home.element.appendChild(buttons_container); viewElement.appendChild(currentScreen.element); home.element.appendChild(viewElement); currentScreen.activateOnScroll(viewElement); home.element.appendChild( load_more_button ); socketGateway.emit("getNotifications", id, function (data) { var i, l = data.length, type; for (i = 0; i < l; i++) { type = data[i].type; notificationCenter.addNotification(type, data[i]); } }); home.element.appendChild(notificationCenter.user_feedback_element); }; function openGroups( callback ){ groupCounter = 0; groupsButton.textContent = "Gruppen"; clearViewScreen(); clearReturnButton(); clearSubheader(); currentScreenType = "GroupsScreen"; if (currentScreen.deactivateOnScroll) { currentScreen.deactivateOnScroll(viewElement); } subheader = document.createElement("DIV"); subheader.className = "home-subheader"; currentScreen = new GroupsScreen(id, id, subheader, callback); viewElement.appendChild(subheader); viewElement.appendChild(currentScreen.element); selectButton(groupsButton); load_more_button.style.display = "none"; home.autoPostEditor = null; } var selectButton = function (button) { deselectButtons(); if ( button ) { button.className += " selected"; } }; var deselectButtons = function () { var buttons = document.getElementsByClassName("menu-bar-button selected"); for (var i = 0; i < buttons.length; i++) { buttons[i].className = buttons[i].className.replace("selected", ""); } }; var clearRoomViewer = function () { viewElement.removeChild(roomViewer.element); roomViewer = undefined; }; var clearProfileViewer = function () { if(profileViewer.element.parentNode === viewElement){ viewElement.removeChild(profileViewer.element); profileViewer = undefined; } }; var clearGroupViewer = function () { viewElement.removeChild(groupViewer.element); groupViewer = undefined; }; var clearGroupInfoViewer = function () { viewElement.removeChild(groupInfoViewer.element); groupInfoViewer = undefined; }; var closeGroupInfoViewer = function () { clearGroupInfoViewer(); clearReturnButton(); if (currentScreen) { viewElement.appendChild(currentScreen.element); } }; var clearReturnButton = function () { /*if (returnButton) { header.removeChild(returnButton); returnButton = undefined; } */ }; var clearViewScreen = function () { if (currentScreen && currentScreen.removeListeners) { currentScreen.removeListeners(); } while (viewElement && viewElement.firstChild) { viewElement.removeChild(viewElement.firstChild); } groupViewer = undefined; profileViewer = undefined; groupInfoViewer = undefined; roomViewer = undefined; if ( searchField != undefined ) { searchField.stopAndRemoveSearch(); } }; var clearScreen = function () { while (home.element.firstChild) { home.element.removeChild(home.element.firstChild); } }; var createMenu = function () { var dropdownName, dropdownPicture; var dropDownMenuCapsule = document.createElement("DIV"); dropDownMenuCapsule.className = "home-dropdown-capsule"; var dropdownButton = document.createElement("DIV"); dropdownButton.className = "home-dropdown-button"; socketGateway.unsubscribe("uploadProfilePicture", home); socketGateway.subscribe("uploadProfilePicture", function (args) { if (args.response === "ok") { profileViewer.pictureManager.image.src = projectDomain + args.path; dropdownPicture.src = projectDomain + args.path; currentUser.picture = args.path; if (profileViewer.currentScreen.pictureUploader) { profileViewer.currentScreen.pictureUploader.createCropper(projectDomain + currentUser.picture); } // if (currentScreen.loadInfoStream) { // currentScreen.loadInfoStream(); // } } else { alertManager.inform() } }, home); socketGateway.unsubscribe("uploadGroupPicture", home); socketGateway.subscribe("uploadGroupPicture", function (args) { var picturePath = projectDomain + args.path; var group = currentScreen.groups[args.groupid]; group.groupPictureElement.src = picturePath; group.picturePath = picturePath; if (groupInfoViewer.pictureManager) { groupInfoViewer.pictureManager.createCropper(picturePath) } }, home); if (isUserLoggedIn()) { dropdownName = document.createElement("DIV"); dropdownName.className = "profile-button"; dropdownPicture = document.createElement("IMG"); dropdownPicture.title = username; dropdownPicture.className = "home-profile-picture"; if (picturePath) { dropdownPicture.src = projectDomain + picturePath; } dropdownPicture.height = 25; dropdownPicture.width = 25; // dropdownButton.appendChild(dropdownName); dropdownButton.appendChild(dropdownPicture); dropdownButton.onclick = function () { deselectButtons(); socketGateway.emit("getProfile", { "userid": id }); }; var logoutOption = document.createElement("DIV"); logoutOption.textContent = ""; logoutOption.title = "Logout"; logoutOption.className = "menubar-button logout"; logoutOption.onclick = function () { home.logout(); }; //dropDownMenuCapsule.appendChild(logoutOption); dropDownMenuCapsule.appendChild(notificationCenter.element); dropDownMenuCapsule.appendChild(dropdownButton); //dropDownMenuCapsule.appendChild(menu); } else { var loginOption = document.createElement("DIV"); loginOption.textContent = ""; loginOption.title = "Login"; loginOption.className = "menubar-button login"; loginOption.onclick = function () { var loginScreen = document.createElement("DIV"); loginScreen.className = "login-formular"; var emailLabel = document.createElement("DIV"); emailLabel.appendChild(document.createTextNode("Email")); var email = document.createElement("INPUT"); var passwordLabel = document.createElement("DIV"); passwordLabel.appendChild(document.createTextNode("Password")); var password = document.createElement("INPUT"); password.type = "password"; password.onkeydown = function (event) { if (event.key === "Enter") { home.login(email.value, password.value); } }; var submitButton = document.createElement("BUTTON"); submitButton.textContent = "Login"; submitButton.className = "ok"; submitButton.onclick = function () { home.login(email.value, password.value); }; var cancelButton = document.createElement("BUTTON"); cancelButton.textContent = "Cancel"; cancelButton.className = "cancel"; cancelButton.onclick = function () { dropDownMenuCapsule.removeChild(loginScreen); loginScreen = undefined; dropDownMenuCapsule.appendChild(loginOption); }; loginScreen.appendChild(emailLabel); loginScreen.appendChild(email); loginScreen.appendChild(passwordLabel); loginScreen.appendChild(password); loginScreen.appendChild(submitButton); loginScreen.appendChild(cancelButton); dropDownMenuCapsule.removeChild(loginOption); dropDownMenuCapsule.appendChild(loginScreen); }; // dropDownMenuCapsule.appendChild(loginOption); } header.appendChild(dropDownMenuCapsule); }; var assignUserData = function (replyArgs) { id = replyArgs.id; username = replyArgs.name; timestamp = replyArgs.latestPostTimestamp; latestPostTimestamp = timestamp ? timestamp : new Date().toISOString(); picturePath = replyArgs.picture; //Global. currentUser = { id: id, username: username, picture: picturePath, allowed_permissions: replyArgs.allowed_permissions, // "Y" or "N", admin: replyArgs.admin === "Y", mention_email: replyArgs.mention_email === "Y", profile_mention_email: replyArgs.profile_mention_email === "Y", offline_chat_email: replyArgs.offline_chat_email === "Y", eod_rooms_email: replyArgs.eod_rooms_email === "Y", eod_groups_email: replyArgs.eod_groups_email === "Y", live_post: replyArgs.live_post === "Y", visible: replyArgs.visible === "Y", group_settings : replyArgs.group_settings, messenger_settings : replyArgs.messenger_settings } }; //RECONNECTING----------------- var alertCallbackReference; var reconnectIntervalNum; var reconnectTries = 0; socketGateway.subscribe("updateCurrentUserPermissions", function (event) { if ( currentUser != undefined ) { currentUser.allowed_permissions = event.data; //todo inform subscribers onUpdateCurrentUserPermissions if ( home.subscribers['onUpdateCurrentUserPermissions'] != undefined ) { var i, l = home.subscribers['onUpdateCurrentUserPermissions'].length; for ( i = 0; i < l; i++ ) { home.subscribers['onUpdateCurrentUserPermissions'][i].fn.call( home.subscribers['onUpdateCurrentUserPermissions'][i].ctx, {} ) } } } }, home); socketGateway.subscribe("connect", function () { reconnectTries = 0; clearInterval(reconnectIntervalNum); getConnectedUser(alertCallbackReference); }, home); socketGateway.subscribe("disconnect", function () { setTimeout(function () { alertManager.waitingAlert("Bitte warten! Verbindung wird aufgebaut!", function (ready) { alertCallbackReference = ready; //pass the alert removal reference }); }, 500); clearInterval(reconnectIntervalNum); reconnectIntervalNum = setInterval(reconnect, 60 * 1000); }, home); socketGateway.subscribe("sessionOld", function () { clearInterval(reconnectIntervalNum); setTimeout(function () { clearScreen(); alertManager.waitingAlert("Session opened in a different device. Max 3 sessions allowed.", function () {}); }, 500); }); var reconnect = function () { reconnectTries++; if ( reconnectTries <= 20 && can_reconnect && socketGateway.isDisconnected()) { socketGateway.open(); } else { clearInterval(reconnectIntervalNum); } }; //------------------------------ home.setLiveCounter = function( number ) { /* clearInterval( live_counter_interval ); live_counter = number < 0 ? 0 : number; if ( live_counter > 0 ) { liveContentButton.className = "live menu-bar-button active"; liveContentButton.textContent = "Live (" + live_counter + ")"; live_counter_interval= setInterval( function( ) { liveContentButton.className = liveContentButton.className == "live menu-bar-button active" ? "live menu-bar-button neutral" : "live menu-bar-button active"; }, 300 ) } else { liveContentButton.className = "live menu-bar-button inactive"; liveContentButton.textContent = "Live"; } currentHome.api.sendEvent( { 'type' : 'notification', 'event' : 'live-counter', 'value' : live_counter } ); */ }; home.stockAction = null; home.externalAction = null; home.onStockAction = function (fn, ctx) { home.stockAction = { fn: fn, context: ctx } }; home.onAction = function (fn, ctx) { home.externalAction = { fn: fn, context: ctx } }; home.informExternalStock = function( data ) { if ( environment === "tradingdesk"){ if ( currentHome.stockAction != null) { currentHome.stockAction.fn.call(currentHome.stockAction.context, data.isin, data.source); } } else if( ["mobile", "messenger"].indexOf(environment) != -1){ //window.location.pathname = '/charttool/isin-' + data.isin alert("Dieser Inhalt ist in der App nicht verfügbar. Nutzen Sie das Trading-Desk"); } }; home.informExternal = function( data ) { if(environment === "tradingdesk"){ if (currentHome.externalAction != null) { currentHome.externalAction.fn.call( currentHome.externalAction.context, data ) } } else if(["mobile", "messenger"].indexOf(environment) != -1){ if ( data.type == "cloud" ) { window.open( 'https://desk.traderfox.com:88/TeamsShared/' + data.id, '_blank' ); } else if ( data.type == "tool" && data.value[0] == "cloud" ) { //todo: here open user cloud or profile with chart tweets?? } else if ( data.type == "order" ) { //do nothing, new window oppened. } else { alert("Dieser Inhalt ist in der App nicht verfügbar. Nutzen Sie das Trading-Desk"); } } }; home.element = element ? element : document.body; home.element.className = "traderchat-home"; home.element.ondragover = function (event) { event.preventDefault(); }; home.element.ondrop = function (event) { event.preventDefault(); event.stopPropagation(); }; home.login = function (email, password, callback) { var re = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i; if (!re.test(email)) { if ( callback ) { callback( { result : false} ) } alertManager.inform("Please insert a valid e-mail address"); } else { socketGateway.emit("loginUser", { "email": email, "password": password }, function (response) { if (response.result) { assignUserData(response.user); clearScreen(); createUI(); if ( callback ) { callback( { result : true} ) } } else { if ( callback ) { callback( { result : false} ) } alertManager.inform("Your log-in data are incorrect.") } }); } }; home.logout = function ( callback ) { socketGateway.emit("logoutUser", {}, function () { clearScreen(); createDefaultCurrentUser(); id = undefined; username = undefined; picturePath = undefined; createUI(); if ( callback ) { callback(); } }); }; home.close = function () { socketGateway.disconnect(); can_reconnect = false; //socketGateway = undefined; home.element.parentNode.removeChild(home.element); }; home.onOfflineButtonClick = function (callback) { offlineButtonCallback = callback; }; home.reloadStream = function (callback) { // clearScreen(); // createUI(); if (callback) { callback(); } }; home.group = function (group_id, callback) { // currentScreen = new GroupsScreen(id, id); //server am i in group XX if (chatLoaded) { if( environment === "tradingdesk" ){ if (currentHome.externalAction != null) { currentHome.externalAction.fn.call(currentHome.externalAction.context, { 'type' : 'group', id : group_id } ) } } socketGateway.emit("getGroupById", {group_id: group_id}, function (response) { if (response.result) { if ( response.member) { openGroup(response.data) } else { getGroupInfo(response.data) } if (callback) { callback(); } } }); } else { actionQueue.push({ "function": home.group, "context": this, "args": group_id, "callback": callback }); } }; home.groups = function (args, callback) { // currentScreen = new GroupsScreen(id, id); //server am i in group XX if (chatLoaded) { openGroups(callback); } else { actionQueue.push({ "function": home.groups, "context": this, "args": args, "callback": callback }); } } home.teams = function (args, callback) { if (chatLoaded) { showRooms( function(){}, 'teams' ); } else { actionQueue.push({ "function": home.teams, "context": this, "args": args, "callback": callback }); } } home.createTeam = function (args, callback) { if (chatLoaded) { showRooms( function(){ currentScreen.createTeam(); }, 'teams' ); } else { actionQueue.push({ "function": home.createTeam, "context": this, "args": args, "callback": callback }); } } home.createGroup = function (args, callback) { if (chatLoaded) { home.groups( args,function(){ currentScreen.createGroup(); } ); } else { actionQueue.push({ "function": home.createGroup, "context": this, "args": args, "callback": callback }); } } home.teams_counter = 0; home.updateTeamsCounter = function( number ) { home.teams_counter = number; teamsButton.textContent = number > 0 ? "Teams (" + number + ")" : 'Teams'; }; home.rooms_counter = 0; home.updateRoomsCounter = function( number ) { home.rooms_counter = number; roomsButton.textContent = number > 0 ? "Nachrichten (" + number + ")" : 'Nachrichten'; }; home.userByChatId = function( user_id, callback, tab ) { if (chatLoaded) { socketGateway.emit("getProfile", { "userid": user_id, 'tab' : tab }); } else { actionQueue.push({ "function": home.userByChatId, "context": this, "args": user_id, "callback": callback }); } }; home.user = function (user_id, callback) { if (chatLoaded) { if( environment === "tradingdesk" ){ if (currentHome.externalAction != null) { currentHome.externalAction.fn.call(currentHome.externalAction.context, { 'type' : 'group', id : null } ) } } socketGateway.emit("getUserByMainId", {"mainid": parseInt(user_id)}, function (response) { if (response.result) { home.getProfile(response.data); if (callback) { callback(); } } }); } else { actionQueue.push({ "function": home.user, "context": this, "args": user_id, "callback": callback }); } }; home.setLoggedOutStyle = function(){ header.style.display = "none"; viewElement.style.marginTop = "0px"; }; home.autoPost = null; home.autoPostEditor = null; home.dropData = null; home.setDropData = function (data) { home.dropData = data; }; home.shareInRoom = function (data) { if ( currentView.calls != undefined && currentView.calls.takeSharedElement != undefined ) { currentView.calls.takeSharedElement[1].call( currentView.calls.takeSharedElement[0], data ); } }; home.postSharedElement = function (data) { if ( currentView.calls != undefined && currentView.calls.postSharedElement != undefined ) { currentView.calls.postSharedElement[1].call( currentView.calls.postSharedElement[0], data ); } }; home.resetDropData = function () { home.dropData = null; }; home.preparePostData = function( data, callback ) { if (chatLoaded) { if ( home.autoPostEditor != null ) { home.autoPostEditor.addMoreCloudInfo(data); if ( callback ) { callback(); } } else { home.autoPost = data; home.buildShareSelector(); } } else { actionQueue.push({ "function": home.preparePostData, "context": this, "args": data, "callback": callback }); } }; home.buildShareSelector = function(){ var closePopUP = function () { home.element.removeChild(popup_element); }; var closeButton = document.createElement("BUTTON"); closeButton.className = "pop-up-container close"; closeButton.style.top = "33px"; closeButton.style.right = "-8px"; closeButton.style.zIndex = "99"; closeButton.onclick = function (event) { event.stopPropagation(); event.preventDefault(); home.autoPost = null; closePopUP(); }; var popup_element = document.createElement("DIV"); popup_element.className = "element-blocker"; popup_element.style.overflowY = 'auto'; popup_element.style.overflowX = 'hidden'; popup_element.onclick = function (event) { event.stopPropagation(); event.preventDefault(); closePopUP(); }; var list_wrapper = document.createElement('DIV'); list_wrapper.className = 'popup-content'; var content_container = document.createElement('DIV'); content_container.style.float = "left"; content_container.style.marginTop = "20px"; content_container.style.paddingBottom = "20px"; content_container.style.position = "relative"; var selectTab = function( button ) { content_container.textContent = ""; if ( button == 'room' ) { groups_tab.className = "share-tab groups"; rooms_tab.className = "share-tab rooms selected"; socketGateway.emit("getUserRooms", {}, function (data) { var l = data.length, i, groupNameElement; for (i = 0; i < l; i++) { if ( !data[i].status == "joined" ) { continue; } groupNameElement = document.createElement("DIV"); groupNameElement.className = "overlay-group-link"; groupNameElement.textContent = data[i].name; groupNameElement.onclick = function (event) { closePopUP(); home.room( { roomid : this.id} ); event.stopPropagation(); event.preventDefault(); }.bind( { id : data[i].id } ); content_container.appendChild( groupNameElement ); } }); } else if ( button == 'group' ) { rooms_tab.className = "share-tab rooms"; groups_tab.className = "share-tab groups selected"; socketGateway.emit("loadGroupsList", id, function (data) { var l = data.length, i, groupNameElement; for (i = 0; i < l; i++) { if ( !data[i].joined ) { continue; } groupNameElement = document.createElement("DIV"); groupNameElement.className = "overlay-group-link"; groupNameElement.textContent = data[i].name; groupNameElement.onclick = function (event) { closePopUP(); home.group( this.id ); event.stopPropagation(); event.preventDefault(); }.bind( { id : data[i].id } ); content_container.appendChild( groupNameElement ); } }); } }; var title = document.createElement('DIV'); title.className = 'popup-group-link title'; title.innerHTML = "
Wo möchten Sie dieses Cloud-Objekt teilen?
"; var public_tab = document.createElement('button'); public_tab.textContent = "Public Chat" ; public_tab.className = "share-tab public"; public_tab.onclick = function( event ) { closePopUP(); chatCounter = 0; chatButton.textContent = "Chat"; loadChat(); event.stopPropagation(); event.preventDefault(); } title.appendChild(public_tab); var groups_tab = document.createElement('button'); groups_tab.textContent = "Gruppen" ; groups_tab.className = "share-tab groups"; groups_tab.onclick = function( event ) { selectTab( 'group' ); event.stopPropagation(); event.preventDefault(); } title.appendChild(groups_tab); var rooms_tab = document.createElement('button'); rooms_tab.textContent = "Nachrichten" ; rooms_tab.className = "share-tab rooms"; rooms_tab.onclick = function( event ) { selectTab( 'room' ); event.stopPropagation(); event.preventDefault(); } title.appendChild(rooms_tab); list_wrapper.appendChild(title); list_wrapper.appendChild( content_container ); popup_element.appendChild(closeButton); popup_element.appendChild( list_wrapper ); home.element.appendChild(popup_element); popup_element.onclick = function( event ) { event.stopPropagation(); event.preventDefault(); } selectTab( 'group' ); }; home.reply = function( reply_id, callback ) { if (chatLoaded) { socketGateway.emit("getPostByReplyId", { "replyid": reply_id}, function (response) { if (response.result) { var postFromServer = response.data.posts[0]; postFromServer["postid"] = response.data.posts[0].id; postFromServer["readerid"] = id; postFromServer["groupid"] = response.groupid; postFromServer["highlighted_reply"] = response.highlighted_reply; postFromServer["show_all_replies"] = response.show_all_replies; var newPost = new MainPost(postFromServer); showPost(newPost, function(){}); if (callback) { callback(); } } } ) } else { actionQueue.push({ "function": home.reply, "context": this, "args": reply_id, "callback": callback }); } }; home.postByNiceTitle = function( nice_title, callback ) { if (chatLoaded) { socketGateway.emit("getPostIDByNiceTitle", {"nice_title": nice_title}, function (response) { if ( response.result ) { home.post( response.id, callback ); } }); } else { actionQueue.push({ "function": home.postByNiceTitle, "context": this, "args": nice_title, "callback": callback }); } }; home.post = function (post_id, callback) { if (chatLoaded) { socketGateway.emit("getPostById", {"postid": post_id}, function (response) { if (response.result) { var closeCallback, post, posts, infoStream, postPopupElement; var postFromServer = response.data.posts[0]; postFromServer["postid"] = post_id; postFromServer["readerid"] = id; postFromServer["groupid"] = response.groupid; if ( ( postFromServer.visible == undefined || postFromServer.visible ) ) { var newPost = new MainPost(postFromServer); /*if (groupViewer) { infoStream = groupViewer.chatScreen.infoStream; posts = infoStream.getPosts(); } else if ( currentScreenType === "ChatScreen") { infoStream = currentScreen.infoStream; posts = infoStream.getPosts(); } */ /*if ( false && infoStream ) { infoStream.createNewPostListeners(newPost, function () { postPopupElement.parentNode.removeChild(postPopupElement); }); if (post_id in posts) { closeCallback = function () { post = posts[post_id]; if (post) { posts[post_id] = newPost; post.element.parentNode.replaceChild(newPost.element, post.element); } }; } }*/ postPopupElement = showPost(newPost, closeCallback); } else { helper.createAdsWindow( permsLinks[postFromServer.permission_missing].img, permsLinks[postFromServer.permission_missing].order ) } if (callback) { callback(); } } }); } else { actionQueue.push({ "function": home.post, "context": this, "args": post_id, "callback": callback }); } }; home.room = function (args, callback) { if (chatLoaded) { if ( currentUser.id == null ) { return; } if ( args.roomid != -1 ) { socketGateway.emit("getRoom", args.roomid, function (roomData) { if ( roomData.result ) { home.showRoom(roomData); } else { if ( premiumTeams[args.roomid] != -1 ) { helper.createAdsWindow( permsLinks[premiumTeams[args.roomid]].img, permsLinks[premiumTeams[args.roomid]].order ) //showRooms( function(){}, args.type ) } else { showRooms( function(){}, args.type ) } } if(callback){ callback(); } }); } else { showRooms( function(){}, args.type ) } } else { actionQueue.push({ "function": home.room, "context": this, "args": args, "callback": callback }); } }; home.publishingStream = function (args, callback) { if (chatLoaded) { socketGateway.emit("getProfile", { "userid": currentUser.id, 'tab' : 'streams', 'selectedStream' : args.streamid }); } else { actionQueue.push({ "function": home.publishingStream, "context": this, "args": args, "callback": callback }); } }; home.showRoom = function (data) { load_more_button.style.display = "none"; home.autoPostEditor = null; clearReturnButton(); returnButton = document.createElement("BUTTON"); returnButton.className = "return"; returnButton.textContent = "<"; returnButton.title = "Return"; function onClickReturnButton() { load_more_button.style.display = "none"; home.autoPostEditor = null; if ( roomViewer ) { roomViewer.deactivateOnScroll(); roomViewer.element.parentNode.scrollTop = 0; } if(subheader){ viewElement.className = "home-viewer subheader"; header.appendChild(subheader); } clearRoomViewer(); clearReturnButton(); if (currentScreen) { viewElement.appendChild(currentScreen.element); } socketGateway.unsubscribe("newRoomMessage", roomViewer); } returnButton.onclick = function () { onClickReturnButton(); }; //header.insertBefore(returnButton, chatButton); clearViewScreen(); if(subheader && subheader.parentNode === header){ header.removeChild(subheader); viewElement.className = "home-viewer"; } //clearSubheader(); roomViewer = new Room(data); roomViewer.onClose(function () { onClickReturnButton(); showRooms(function(){}, 'private'); }); viewElement.appendChild(roomViewer.element); if ( data.private == 'Y' ) { selectButton(roomsButton); } else { selectButton(teamsButton); } }; /*Messenger API*/ home.api = { eventsHandler : null, viewHandler : null, showShareMenu : null, registerEventsHandler : function( handler ) { this.eventsHandler = handler; }, registerViewsHandler : function( handler ) { this.viewHandler = handler; }, registerShareMenuHandler : function( handler ) { this.showShareMenu = handler; }, sendEvent : function( event ) { if ( this.eventsHandler ) { this.eventsHandler( event ) } }, setView : function( event ) { if ( this.viewHandler ) { this.viewHandler( event ) } }, login : function( args, callback ) { if (chatLoaded) { home.login(args.email, args.password, callback); } else { apiQueue.push({ "function": this.login, "context": this, "args": args, "callback": callback }); } }, logout : function( args, callback ) { if (chatLoaded) { home.logout(callback); } else { apiQueue.push({ "function": this.logout, "context": this, "args": args, "callback": callback }); } }, searchStock : function( term, callback ) { if (chatLoaded) { socketGateway.emit("searchStock", term, function (response) { callback( response ); } ); } else { callback( { 'term' : term, 'data' : [] } ) } }, search : function( term, callback ) { if (chatLoaded) { socketGateway.emit("searchText", term, function (args) { callback( args ); } ); } else { callback(false) } }, getConnectedUser : function( args, callback ) { if (chatLoaded) { var user = { 'id' : currentUser.id, 'name' : currentUser.username, 'picture' : projectDomain + currentUser.picture, 'notifications' : notificationCenter.getNumberOfNotifications(), 'settings' : currentUser.messenger_settings } callback(user); } else { apiQueue.push({ "function": this.getConnectedUser, "context": this, "args": args, "callback": callback }); } }, getGroups : function( args, callback ) { if (chatLoaded) { var groups = []; socketGateway.emit("loadGroupsList", currentUser.id, function (data) { var i, l = data.length; for ( i = 0; i < l; i++ ) { groups.push( { 'id' : data[i].id, 'name' : data[i].name, 'description' : data[i].description, 'picture' : projectDomain + data[i].picturePath, 'unread' : data[i].new_posts, 'member' : data[i].joined, 'permission' : data[i].permission, 'promoted' : data[i].promoted == 'Y', 'admin' : data[i].admin } ) } callback(groups); }); } else { apiQueue.push({ "function": this.getGroups, "context": this, "args": args, "callback": callback }); } }, getPrivateMessages : function( args, callback ) { if (chatLoaded) { var private_rooms = []; socketGateway.emit("getUserRooms", {}, function (rooms) { var i, l = rooms.length; for ( i = 0; i < l; i++ ) { if ( rooms[i].private == 'Y' ) { var j, status = '', pictures = []; for ( j = 0; j < rooms[i].members.length; j++ ) { if ( rooms[i].members[j].userid == currentUser.id ) { status = rooms[i].members[j].status; } else { pictures.push( projectDomain + rooms[i].members[j].picture ); } } private_rooms.push( { 'id' : rooms[i].id, 'name' : rooms[i].name, 'unread' : rooms[i].new_messages, 'status' : status, 'pictures' : pictures } ) } } callback(private_rooms); }.bind(this)); } else { apiQueue.push({ "function": this.getPrivateMessages, "context": this, "args": args, "callback": callback }); } }, getTeams : function( args, callback ) { if (chatLoaded) { var teams = []; socketGateway.emit("getUserRooms", {}, function (rooms) { var i, l = rooms.length; for ( i = 0; i < l; i++ ) { if ( rooms[i].private == 'N' ) { var j, status = '', members = []; for ( j = 0; j < rooms[i].members.length; j++ ) { if ( rooms[i].members[j].userid == currentUser.id ) { status = rooms[i].members[j].status; } else { members.push( { name : rooms[i].members[j].memberName, picture : projectDomain + rooms[i].members[j].picture } ); } } if ( status != 'blocked' ) { teams.push( { 'id' : rooms[i].id, 'name' : rooms[i].name, 'unread' : rooms[i].new_messages, 'status' : status, 'members' : members, 'promoted' : rooms[i].promoted } ) } } } callback(teams); }.bind(this)); } else { apiQueue.push({ "function": this.getTeams, "context": this, "args": args, "callback": callback }); } }, getStreams : function( args, callback ) { if (chatLoaded) { socketGateway.emit("getUserStreams", { "userid": currentUser.id }, function (response) { callback( response.result ? response.data : [] ); }.bind( this ) ) } else { apiQueue.push({ "function": this.getStreams, "context": this, "args": args, "callback": callback }); } }, getFollowed : function( args, callback ) { if (chatLoaded) { var followed = []; socketGateway.emit("loadFollowedUsers", currentUser.id , function (f) { var i, l = f.length; for ( i = 0; i < l; i++ ) { f[i].picturePath = projectDomain + f[i].picturePath followed.push( f[i] ); } callback(followed); }.bind(this)); } else { apiQueue.push({ "function": this.getFollowed, "context": this, "args": args, "callback": callback }); } }, getConnectedUserCloud : function( args, callback ) { if (chatLoaded) { socketGateway.emit("getUserCloudItems", {}, function (cloud_items) { if ( cloud_items.result ) { } else { callback({}) } } ) } else { apiQueue.push({ "function": this.getConnectedUserCloud, "context": this, "args": args, "callback": callback }); } }, getConnectedUserFiles : function( args, callback ) { if (chatLoaded) { socketGateway.emit("getUserFiles", args, function (files) { if ( files.result ) { callback( files.data ); } else { callback({}) } } ) } else { apiQueue.push({ "function": this.getConnectedUserFiles, "context": this, "args": args, "callback": callback }); } }, saveCloudItem : function( args, callback ) { if (chatLoaded) { socketGateway.emit("saveCloudItem", args, function (result) { callback( result ); } ) } else { apiQueue.push({ "function": this.saveCloudItem, "context": this, "args": args, "callback": callback }); } }, joinTeamWithToken : function( token, callback ) { if (chatLoaded) { if ( currentUser.id == null ) { return; } socketGateway.emit("joinTeamByToken", token, function (response) { if ( response.result ) { this.openTeam(response.roomid); } }.bind( this ) ) } else { apiQueue.push({ "function": this.joinTeamWithToken, "context": this, "args": token, "callback": callback }); } }, openTeam : function (roomid, callback) { home.room( { roomid : roomid, type : 'teams' }, callback ); }, openPublishingStream : function (streamid, callback) { home.publishingStream( { streamid : streamid }, callback ); }, openPrivateMessage : function (roomid, callback) { home.room( { roomid : roomid, type : 'private' }, callback ); }, openGroup : function (groupid, callback) { home.group(groupid, callback) }, openGroups : function (args, callback) { home.groups(args, callback) }, openTeams : function (args, callback) { home.teams(args, callback) }, createTeam : function (args, callback) { home.createTeam(args, callback) }, createGroup : function (args, callback) { home.createGroup(args, callback) }, openNotifications : function (args, callback) { if (chatLoaded && notificationCenter.element != undefined ) { notificationCenter.element.onclick(); } else { actionQueue.push({ "function": this.openNotifications, "context": this, "args": args, "callback": callback }); } }, openUserStreamBySecret : function (args, callback) { if (chatLoaded ) { //home.userByChatId( currentUser.id, callback, args.tab ); socketGateway.emit("getUserByStreamSecret", {"secret": args}, function (response) { if (response.result) { socketGateway.emit("getProfile", { "userid": response.id, "secret": args, "tab" : "streams" }); callback(); } }); } else { actionQueue.push({ "function": this.openUserStreamBySecret, "context": this, "args": args, "callback": callback }); } }, openUserProfileByName : function (args, callback) { if (chatLoaded ) { //home.userByChatId( currentUser.id, callback, args.tab ); socketGateway.emit("getUserIdByName", {"name": args}, function (response) { if (response.result) { socketGateway.emit("getProfile", { "userid": response.id }); callback(); } }); } else { actionQueue.push({ "function": this.openUserProfileByName, "context": this, "args": args, "callback": callback }); } }, openUserProfile : function (args, callback) { if (chatLoaded ) { home.userByChatId( currentUser.id, callback, args.tab ); } else { actionQueue.push({ "function": this.openUserProfile, "context": this, "args": args, "callback": callback }); } }, openProfile : function (userid, callback) { if (chatLoaded ) { home.userByChatId( userid, callback ); } else { actionQueue.push({ "function": this.openProfile, "context": this, "args": userid, "callback": callback }); } }, openStream : function (args, callback) { /* if (chatLoaded ) { loadStream( args, callback ); } else { actionQueue.push({ "function": this.openStream, "context": this, "args": args, "callback": callback }); }*/ }, openMarketPlace : function (args, callback) { if (chatLoaded ) { openMarketPlace( args, callback ); } else { actionQueue.push({ "function": this.openMarketPlace, "context": this, "args": args, "callback": callback }); } }, openChat : function (args, callback) { if (chatLoaded ) { loadChat( args, callback ); } else { actionQueue.push({ "function": this.openChat, "context": this, "args": args, "callback": callback }); } }, openMyStream : function (args, callback) { if (chatLoaded ) { openMyStream( args, callback ); } else { actionQueue.push({ "function": this.openMyStream, "context": this, "args": args, "callback": callback }); } }, openOverview : function (args, callback) { if (chatLoaded ) { openOverview( args, callback ); } else { actionQueue.push({ "function": this.openOverview, "context": this, "args": args, "callback": callback }); } }, openLive : function (args, callback) { if (chatLoaded ) { loadLive( args, callback ); } else { actionQueue.push({ "function": this.openLive, "context": this, "args": args, "callback": callback }); } } } function showTopics( tag ) { load_more_button.style.display = "none"; home.autoPostEditor = null; clearViewScreen(); clearReturnButton(); clearSubheader(); if (currentScreen.deactivateOnScroll) { currentScreen.deactivateOnScroll(viewElement); } currentScreenType = "TopicsScreen"; subheader = document.createElement("DIV"); subheader.className = "home-subheader"; currentScreen = new TopicsScreen(subheader); viewElement.appendChild(subheader); //not header.appendChild viewElement.appendChild(currentScreen.element); viewElement.className = "home-viewer subheader"; selectButton(topicsButton) if ( tag ){ currentScreen.openTagsScreen(tag); //currentScreen.openTag(tag) } else { currentScreen.openStocksOverview(); } } function showRooms(callback, type) { load_more_button.style.display = "none"; home.autoPostEditor = null; if ( type == 'teams' ) { notificationCenter.resetTeamsNotificationCounter(); } else if ( type == 'private' ) { notificationCenter.resetRoomNotificationCounter(); } clearViewScreen(); clearReturnButton(); viewElement.className = "home-viewer"; if(currentScreenType !== "RoomScreen"){ clearSubheader(); } if (currentScreen.deactivateOnScroll) { currentScreen.deactivateOnScroll(viewElement); } currentScreenType = "RoomsScreen"; subheader = document.createElement("DIV"); subheader.className = "home-subheader"; currentScreen = new RoomsScreen(subheader, callback, type); viewElement.appendChild(subheader); //not ehader anymore viewElement.appendChild(currentScreen.element); viewElement.className = "home-viewer subheader"; if ( type == 'teams' ) { selectButton(teamsButton); } else { selectButton(roomsButton); } } home.tag = function (tag, callback) { if (chatLoaded) { showTopics(tag); //currentScreen.openTag(tag); if (callback) { callback(); } } else { actionQueue.push([home.tag, this, tag, callback]); } }; home.stock = function (stock, callback) { if (chatLoaded) { showTopics(); currentScreen.openStock(stock); if (callback) { callback() } } else { actionQueue.push([home.stock, this, stock, callback]); } }; var createDefaultCurrentUser = function(){ currentUser = { id: null, username: '', picture: '', allowed_permissions: null, // "Y" or "N", admin: false, mention_email: false, profile_mention_email: false, eod_rooms_email: false, eod_groups_email: false, live_post: false, visible: false, group_settings : {} }; }; var getConnectedUser = function (callback) { //the callback is optional, used for removing the reconnecting-window socketGateway.emit("getConnectedUser", {}, function (response) { if (response.result) { assignUserData(response.user); if (callback) { callback(); } else { //if new load clearScreen(); createUI(); } eventManager.informChatReady(); if (response.first_time) { /*var info_element = document.createElement("DIV"); var title = document.createElement('h3'); title.textContent = 'Wichtige Regeln zum Chat:' info_element.appendChild(title); var rules = [ 'Seien Sie freundlich und halten Sie die im Netz üblichen und allgemein akzeptierten Verhaltensregeln ein. Wenn Sie andere Nutzer beleidigen, werden Sie gelöscht.', 'Zahlende TraderFox-Kunden haben Zugriff zu moderierten Premium-Gruppen. Sie können am Chat natürlich auch rein als passiver Nutzer teilnehmen, um auf unsere moderierten Premium-Gruppen zuzugreifen.', 'Wenn Sie beim Chat angemeldet sind, werden Sie standardmäßig per Email benachrichtigt, wenn andere Nutzer an Ihre Pinnwand schreiben. Sie können diese Email-Benachrichtigungsfunktionen in den Chat-Einstellungen deaktivieren.', 'Wenn Sie beim Chat angemeldet sind, werden Sie standardmäßig benachrichtigt, wenn andere Nutzer Sie in einem Beitrag erwähnen (mittels #). Sie können diese Email-Benachrichtigungsfunktionen in den Chat-Einstellungen deaktivieren.' ] var rule, i, l = rules.length; for (i = 0; i < l; i++) { rule = document.createElement('div'); rule.style = 'margin-top:10px;float:left;clear:both'; rule.textContent = ( i + 1 ) + '. ' + rules[i]; info_element.appendChild(rule); }*/ socketGateway.emit("getRules", {}, function (rulesArray) { //alertManager.scrollableInform(createRulesElement alertManager.scrollableAsk(createRulesElement(rulesArray), function () { }, function () { socketGateway.emit("deleteUser", {}, function (response) { }); clearScreen(); //todo send to server and remove just created user!!! }) }); } } else { createDefaultCurrentUser() switch (response.reason) { case "ban": showBanNotification(); break; default: if (callback) { //if reconnecting callback(); } else { //if new load clearScreen(); createUI(); } break; } eventManager.informChatReady(); } }); }; Number.prototype.nf = function (decimals) { var p; if (decimals == undefined) { if (this > 1000) { decimals = 1; } else if (this > 10) { decimals = 2; } else { decimals = 4; } } else if (decimals == 0) { p = ( this + '' ).split('.'); p[0] = p[0].replace(/\B(?=(\d{3})+(?!\d))/g, "."); return p[0]; } var v = this.toFixed(decimals) + ''; p = v.split('.'); p[0] = p[0].replace(/\B(?=(\d{3})+(?!\d))/g, "."); if (isNaN(p[0])) { if (p[0] == 'NaN') { return ''; } else { return p[0] + ',' + p[1]; } } else { return p[0] + ',' + p[1]; } }; String.prototype.nf = function (decimals) { return parseFloat(this).nf(decimals); }; return home; } var viewManager = function(){ var manager = { type : '', id : null, onChangeView : null }; manager.setNewView = function( data ) { currentHome.api.setView(data.type); manager.type = data.type; manager.id = data.id; manager.calls = data.calls; if ( manager.onChangeView != null ) { manager.onChangeView(); } manager.onChangeView = data.onChangeView; }; return manager; }; function TraderChatHelper(){ var helper = {}; helper.timestampToBeauty = function( timestamp ) { var postDate = new Date(timestamp); var now = new Date(), dateRepresentation; var time = " um " + postDate.toLocaleTimeString('de'); if (now.getDate() === postDate.getDate()) { dateRepresentation = time; } else { dateRepresentation = " am " + postDate.toLocaleDateString('de') + time; } return dateRepresentation; }; helper.createAdsWindow = function( image, link ) { var element = alertManager.ads(); element.innerHTML = ""; var close = document.createElement("DIV") close.className = "fa fa-window-close"; close.style.position = "absolute"; close.style.top = "10px"; close.style.right = "10px"; close.style.color = "white"; close.style.backgroundColor = "#d5021f"; close.style.fontSize = "3rem"; close.style.cursor = "pointer"; element.appendChild(close); }; helper.now = function(){ var now = new Date(); return now.toLocaleDateString('de') + " " + now.toLocaleTimeString('de'); }; helper.isImage = function( text ) { var regex = /(?:([^:/?#]+):)?(?:\/\/([^/?#]*))?([^?#]*\.(?:jpe?g|gif|png))(?:\?([^#]*))?(?:#(.*))?/gi; return regex.test(text); }; helper.isNewsLink = function( text ) { return text.indexOf("news||") != -1; }; helper.isCloudLink = function( text ) { return text.indexOf("cloud||") != -1; }; helper.isStock = function( text ) { return text.indexOf("stock||") != -1; }; helper.isOrder = function( text ) { return text.indexOf("order:") != -1; }; helper.getNewsParts = function( text ) { return text.split('||'); }; helper.getCloudParts = function( text ) { return text.split('||'); }; helper.getStockName = function( text, callback ) { var stock_id = parseInt( text.split('||')[1] ); if ( !isNaN( stock_id ) ) { socketGateway.emit("getStockInfo", stock_id, function (response) { callback( response ) } ) } }; helper.getStockByWKNorISIN = function( text, callback ) { socketGateway.emit("getStockInfoByWKNorISIN", text, function (response) { callback( response ) } ) }; helper.isZipFile = function( name ){ if ( name == undefined ) { return false; } return name.slice(-3).toLowerCase() == "zip"; // var reg = /([0-9a-z]+)(?:[\?#]|$)/i; //var ext = reg.exec( name ); //return ext != null && ["zip"].indexOf( ext ) != -1 }; helper.isPDF = function( name ){ if ( name == undefined ) { return false; } return name.slice(-3).toLowerCase() == "pdf"; // var reg = /([0-9a-z]+)(?:[\?#]|$)/i; //var ext = reg.exec( name ); //return ext != null && ["zip"].indexOf( ext ) != -1 }; helper.isPostInteralLink = function(word){ if ( word.length >= 3 ) { if ( word[0] == '<' && word[word.length-1] == '>' ) { var postid = parseInt(word.replace('<', '').replace('>', '')); return !isNaN(postid); } } return false; }; helper.isTDTool = function(word){ return word.indexOf('tool||') != -1; }; helper.getTDToolData = function(word){ var info = word.split('||'); var data = { 'tool' : info[1] } if ( info[1] == "infobox" ) { data["stock_id"] = info[2]; data["title"] = info[3].replace(/###/g, ' ') + '\r\r\r'; } return data; }; helper.interpretTextClicked = function( event ) { var data_value = event.target.getAttribute('data-value'); if ( data_value != null ) { data_value = data_value.split('|'); if ( data_value[0] == 'tag' ) { currentHome.tag(data_value[1]); } if ( data_value[0] == 'comment' ) { currentHome.reply(data_value[1]); } if ( data_value[0] == 'post' ) { currentHome.post(data_value[1]); } if ( data_value[0] == 'mention' ) { currentHome.userByChatId(data_value[1]); } if ( data_value[0] == 'tool' ) { data_value.shift(); currentHome.informExternal( { type : 'tool', value : data_value } ); } } }; helper.parseMentions = function( html_text, mentions ) { var i, l = mentions.length; var namestring; for ( i = 0; i < l; i++ ) { namestring = '@' + mentions[i].name; html_text = html_text.replace( new RegExp( namestring, 'g'), "" + namestring + "" ) } return html_text; }; helper.getParsedHTML = function( text ) { var parsed_text = text.replace(/\r\n/g, '
'); parsed_text = parsed_text.replace(/\r/g, '
'); parsed_text = parsed_text.replace(/\n/g, '
'); //check for tags var tags_regex = /(#).*?()\w+/g; var tag, tags = []; while (( tag = tags_regex.exec(parsed_text)) !== null) { tags.push( tag[0] )} var i, l = tags.length; for ( i = 0; i < l; i++ ) { parsed_text = parsed_text.replace( tags[i], "" + tags[i] + "" ) } //check for url var url_regex = /((?:(http|https|Http|Https|rtsp|Rtsp):\/\/(?:(?:[a-zA-Z0-9\$\-\_\.\+\!\*\'\(\)\,\;\?\&\=]|(?:\%[a-fA-F0-9]{2})){1,64}(?:\:(?:[a-zA-Z0-9\$\-\_\.\+\!\*\'\(\)\,\;\?\&\=]|(?:\%[a-fA-F0-9]{2})){1,25})?\@)?)?((?:(?:[a-zA-Z0-9][a-zA-Z0-9\-]{0,64}\.)+(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnrwyz]|l[abcikrstuvy]|(?:mil|mobi|museum|m[acdghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eouw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agkmsyz]|v[aceginu]|w[fs]|y[etu]|z[amw]))|(?:(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))(?:\:\d{1,5})?)(\/(?:(?:[a-zA-Z0-9\;\/\?\:\@\&\=\#\~\-\.\+\!\*\'\(\)\,\_])|(?:\%[a-fA-F0-9]{2}))*)?(?:\b|$)/gi; var url, urls = []; while (( url = url_regex.exec(parsed_text)) !== null) { urls.push( url[0] )} var i, l = urls.length; for ( i = 0; i < l; i++ ) { parsed_text = parsed_text.replace( urls[i], "" + urls[i] + "" ) } //check for labels var labels_regex = /\[\[(.*?)\]\]/g; var label, labels = []; while (( label = labels_regex.exec(parsed_text)) !== null) { labels.push( label[0] )} var i, l = labels.length, meta, replacer; for ( i = 0; i < l; i++ ) { meta = labels[i].replace('[[', '').replace(']]', '').split('|'); if ( meta[0] == 'post' || meta[0] == 'comment' ) { parsed_text = parsed_text.replace( labels[i], "" + '#' + meta[1] + "" ) } } return parsed_text; }; helper.getPostIdFromInteralLink = function(link){ return parseInt(link.replace('<', '').replace('>', '')); }; helper.isReplyInteralLink = function(word){ if ( word.length >= 4 ) { if ( word[0] == '<' && word[1] == 'c' && word[word.length-1] == '>' ) { var postid = parseInt(word.replace('c', '').replace('<', '').replace('>', '')); return !isNaN(postid); } } return false; }; helper.getReplyIdFromInteralLink = function(link){ return parseInt(link.replace('c', '').replace('<', '').replace('>', '')); }; helper.getOffset = function ( el ) { var _x = 0; var _y = 0; while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) { _x += el.offsetLeft - el.scrollLeft; _y += el.offsetTop - el.scrollTop; if ( el.offsetParent != currentHome.element ) { //do not go out of given contianer for library. el = el.offsetParent; } else { el = null } } return { top: _y, left: _x }; }; helper.uploadFile = function( data, callback ) { var uploader = new UploadCreator(); if ( data[0].type == "application/x-zip-compressed" && data[0].size/1024 > 200 ) { //check filesize in kB alertManager.inform("Max zip size: 200kB"); } else { uploader.createFileUpload(data[0], function (fileObject) { if ( !fileObject.result ) { alertManager.inform(fileObject.message) } else { socketGateway.emit("uploadRoomFile", fileObject, function (data) { if (data.response === "ok") { callback(data); } else { if ( data.message != undefined ) { alertManager.inform(data.message); } else { alertManager.inform("Dateityp ist nicht erlaubt / Max size: 3MB"); } callback(data); } }); } }); } }; helper.cleanString = function( string ) { if ( string == undefined ) { return ""; } var clean = string.replace( / /gi, ' ' ); clean = clean.replace( / /gi, '_' ); clean = clean.replace( /ö/gi, 'oe' ); clean = clean.replace( /ü/gi, 'ue' ); clean = clean.replace( /ä/gi, 'ae' ); clean = clean.replace( /ß/gi, 'ss' ); clean = clean.replace( /ñ/gi, 'n' ); clean = clean.replace( /[^a-z0-9_\.]/gi, "" ); return clean; }; helper.createTimestampPresentation = function (timestamp) { var postDate = new Date(timestamp); var now = new Date(), dateRepresentation; var time = postDate.toLocaleTimeString('de'); var timeSplit = time.split(":"); var timeWithoutSeconds = timeSplit[0] + ":" + timeSplit[1]; if (now.getDate() === postDate.getDate()) { dateRepresentation = timeWithoutSeconds; } else { dateRepresentation = postDate.toLocaleDateString('de') + " - " + timeWithoutSeconds; } return dateRepresentation; }; helper.replaceAll = function( target, search, replacement ) { return target.replace( new RegExp(search, 'g'), replacement); }; helper.isValidURL = function (str) { var urlRegex = /((?:(http|https|Http|Https|rtsp|Rtsp):\/\/(?:(?:[a-zA-Z0-9\$\-\_\.\+\!\*\'\(\)\,\;\?\&\=]|(?:\%[a-fA-F0-9]{2})){1,64}(?:\:(?:[a-zA-Z0-9\$\-\_\.\+\!\*\'\(\)\,\;\?\&\=]|(?:\%[a-fA-F0-9]{2})){1,25})?\@)?)?((?:(?:[a-zA-Z0-9][a-zA-Z0-9\-]{0,64}\.)+(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnrwyz]|l[abcikrstuvy]|(?:mil|mobi|museum|m[acdghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eouw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agkmsyz]|v[aceginu]|w[fs]|y[etu]|z[amw]))|(?:(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))(?:\:\d{1,5})?)(\/(?:(?:[a-zA-Z0-9\;\/\?\:\@\&\=\#\~\-\.\+\!\*\'\(\)\,\_])|(?:\%[a-fA-F0-9]{2}))*)?(?:\b|$)/gi; ; return urlRegex.test(str); }; return helper; } /* This class offers some functions for taking the data of an input.type = "file" and transforming it to a buffer or a URL. */ function UploadCreator() { } UploadCreator.prototype.createFileUpload = function (file, callback) { this.readFileAsBuffer(file, callback); }; UploadCreator.prototype.readFileAsBuffer = function (file, callback) { var fr = new FileReader(); fr.onloadend = function () { if ( file.size > 3145728 ) { callback( {result : false, message : 'Max size: 3MB'} ) } else { callback({ "result" : true, "type": file.type, "size": file.size, "name": helper.cleanString(file.name), "dataBuffer": fr.result }); } }.bind(this); try { fr.readAsArrayBuffer(file); } catch (e){ //console.log(e); console.log( e ) } }; UploadCreator.prototype.readFileAsDataURL = function (file, callback) { var fr = new FileReader(); fr.onloadend = function () { callback(fr.result); }.bind(this); try { fr.readAsDataURL(file); } catch (e){ } }; /* A factory for non-thread-blocking pop-up windows. */ function nonBlockingCommunication(parent) { var nonBlockingCommunication = {}; nonBlockingCommunication.home = parent; var elementBlocker = document.createElement("DIV"); elementBlocker.className = "element-blocker"; var alertElement; var okButton; var textElement; var cancelButton; var countdownElement; var createAlertBody = function () { elementBlocker.onclick = null; alertElement = document.createElement("DIV"); if (elementBlocker.firstChild) { elementBlocker.removeChild(elementBlocker.firstChild); } textElement = document.createElement("DIV"); }; var createPlainTextAlertBody = function (text) { createAlertBody(); alertElement.className = "non-blocking alertManager"; textElement.className = "alert-text"; textElement.appendChild(document.createTextNode(text)); alertElement.appendChild(textElement); elementBlocker.appendChild(alertElement); parent.appendChild(elementBlocker); }; var createRichAlertBody = function (element) { createAlertBody(); alertElement.className = "non-blocking alertManager"; textElement.className = "alert-text"; textElement.appendChild(element); alertElement.appendChild(textElement); elementBlocker.appendChild(alertElement); parent.appendChild(elementBlocker); }; var createScrollableAlertBody = function (element) { createAlertBody(); alertElement.className = "non-blocking alertManager scrollable"; textElement.className = "alert-text scrollable"; textElement.appendChild(element); alertElement.appendChild(textElement); elementBlocker.appendChild(alertElement); parent.appendChild(elementBlocker); }; /*var createFunctionalAlertBody = function (element) { alertElement = document.createElement("DIV"); alertElement.className = "non-blocking alertManager"; if(elementBlocker.firstChild){ elementBlocker.removeChild(elementBlocker.firstChild); } textElement = };*/ var createOkButton = function (okCallback) { okButton = document.createElement("BUTTON"); okButton.textContent = "OK"; okButton.className = "ok"; okButton.onclick = function () { removeAlert(); if (okCallback) { okCallback(); } }; alertElement.appendChild(okButton); }; var createOkButtonScrollable = function (okCallback) { okButton = document.createElement("BUTTON"); okButton.textContent = "OK"; okButton.className = "ok scrollablePopup"; okButton.onclick = function () { removeAlert(); if (okCallback) { okCallback(); } }; alertElement.appendChild(okButton); }; var createCancelButton = function (cancelCallback) { cancelButton = document.createElement("BUTTON"); cancelButton.textContent = "Cancel"; cancelButton.className = "cancel"; cancelButton.onclick = function () { removeAlert(); if (cancelCallback) { cancelCallback(); } }; alertElement.appendChild(cancelButton); }; var createCancelButtonScrollable = function (cancelCallback) { cancelButton = document.createElement("BUTTON"); cancelButton.textContent = "Cancel"; cancelButton.className = "cancel scrollablePopup"; cancelButton.onclick = function () { removeAlert(); if (cancelCallback) { cancelCallback(); } }; alertElement.appendChild(cancelButton); }; var createCountdown = function (seconds) { countdownElement = document.createElement("DIV"); countdownElement.textContent = seconds + " s"; var countdownInterval = setInterval(function () { if (seconds === 0) { clearInterval(countdownInterval); return; } seconds--; countdownElement.textContent = seconds + " s"; }, 1000); alertElement.appendChild(countdownElement); }; var removeAlert = function () { if (elementBlocker.parentNode === parent) { parent.removeChild(elementBlocker); } }; nonBlockingCommunication.ask = function (text, okCallback, cancelCallback, rich) { if (rich) { createRichAlertBody(text); } else { createPlainTextAlertBody(text); } createCancelButton(cancelCallback); createOkButton(okCallback); return elementBlocker; }; nonBlockingCommunication.inform = function (textOrElement, okCallback, rich) { if (rich) { createRichAlertBody(textOrElement) } else { createPlainTextAlertBody(textOrElement); } createOkButton(okCallback); return elementBlocker; }; /* text: string - The text appearing in the pop-up seconds: number - the first countdown time timeoutCallback: function - What should be done after the countdown is over ---- readyCallback: function - call this if your process is over ---- notReadyCallback: function - call this if your process is not over */ nonBlockingCommunication.countdownAlert = function (text, seconds, timeoutCallback) { var alertTimeout; var timeoutFunc = function () { var readyCallback = function () { clearTimeout(alertTimeout); removeAlert(); }; var notReadyCallback = function () { //recreates the alert with an increased time removeAlert(); clearTimeout(alertTimeout); nonBlockingCommunication.countdownAlert(text, seconds, timeoutCallback); //the time doubles every time }; timeoutCallback(readyCallback, notReadyCallback); }; createPlainTextAlertBody(text); createCountdown(seconds); alertTimeout = setTimeout(timeoutFunc, seconds * 1000); return elementBlocker; }; nonBlockingCommunication.waitingAlert = function (text, callback) { createPlainTextAlertBody(text); callback(removeAlert); return elementBlocker; }; nonBlockingCommunication.infoCloseOnClick = function (element, callback) { createRichAlertBody(element); callback(removeAlert); elementBlocker.onclick = function (event) { event.stopPropagation(); removeAlert(); elementBlocker.onclick = null; } }; nonBlockingCommunication.scrollableInform = function (element, callback) { createScrollableAlertBody(element); createOkButtonScrollable(callback); }; nonBlockingCommunication.scrollableAsk = function (element, okCallback, cancelCallback) { createScrollableAlertBody(element); createCancelButtonScrollable(cancelCallback); createOkButtonScrollable(okCallback); return elementBlocker; }; nonBlockingCommunication.ads = function () { createAlertBody(); parent.appendChild(elementBlocker); elementBlocker.onclick = function(){ parent.removeChild(elementBlocker); } return elementBlocker; }; return nonBlockingCommunication; } function NotificationCenter() { var notificationCenter = {}; var notificationCount = 0; var rooms_notification_count = 0; var teams_notification_count = 0; var notifications = []; var onClickCallback; var user_feedback_timeout = null; notificationCenter.user_feedback_element = document.createElement('DIV'); notificationCenter.user_feedback_element.style.display = 'none'; notificationCenter.user_feedback_element.style.borderRadius = '4px'; notificationCenter.user_feedback_element.style.position = 'fixed'; notificationCenter.user_feedback_element.style.backgroundColor = '#FFEB3B'; notificationCenter.user_feedback_element.style.color = '#454242'; notificationCenter.user_feedback_element.style.padding = '2px 5px'; notificationCenter.user_feedback_element.style.zIndex = '99'; var countElement = document.createElement("DIV"); countElement.className = "notification-counter"; countElement.appendChild(document.createTextNode(notificationCount)); var notificationInformer = document.createElement("DIV"); notificationInformer.className = "notification-informer"; notificationInformer.style.display = 'none'; notificationInformer.onmouseleave = function () { notificationInformer.style.display = 'none'; }; var showNotifications = function () { notificationInformer.innerHTML = ""; notificationInformer.style.display = 'block'; if (notifications.length > 0) { var notif, i, l = notifications.length; for (i = 0; i < l; i++) { notif = notifications[i]; if (notif.type === "contact-post") { notificationInformer.appendChild(createContactNotification(notif.data)); } else if (notif.type === "mentioned-post") { notificationInformer.appendChild(createMentionNotification(notif.data)); } else if (notif.type === "reply") { notificationInformer.appendChild(createReplyNotification(notif.data)); } else if (notif.type === "room-invite"){ notificationInformer.appendChild(createInviteNotification(notif.data)); } else if(notif.type === "room-message"){ var shouldAttach = true; if(i > 0){ var previousNotification = notifications[i - 1]; if(canGroup(notif.data, previousNotification.data)){ previousNotification.element.childNodes[1].childNodes[1].firstChild.textContent = "hat mehrere Nachrichten geschrieben"; shouldAttach = false; } } var roomNotificationElement = createRoomNotification(notif.data); notif["element"] = roomNotificationElement; if(!shouldAttach){ roomNotificationElement.style.display = "none"; } notificationInformer.appendChild(roomNotificationElement); } else { notificationInformer.appendChild(createGroupNotification(notif.data)); } } } else { var no_notif = document.createElement("DIV"); no_notif.className = "no-notif"; no_notif.appendChild(document.createTextNode("Nichts neues")); notificationInformer.appendChild(no_notif) } }; function canGroup(currentNotification, previousNotification) { return previousNotification.type === currentNotification.type && previousNotification.username === currentNotification.username && previousNotification.roomid === currentNotification.roomid; } var markNotificationRead = function (notificationid, element) { var i; socketGateway.emit("markNotificationRead", notificationid, function (timestamp) { for(i = 0; i < notifications.length; i++){ var notificationData = notifications[i].data; if(notificationData.notificationid === notificationid){ notificationData.read = timestamp; break; } } }); }; var markNotificationsSaw = function (callback) { var notificationids = [], i, date = new Date(); for(i = 0; i < notifications.length; i++){ var notificationData = notifications[i].data; if(!notificationData.saw){ notificationids.push({"id": notificationData.notificationid}); notificationData.saw = date; } } socketGateway.emit("markNotificationsSaw", notificationids, callback); }; var createGroupNotification = function (data) { var div = document.createElement("DIV"); div.className = "entry"; var image = document.createElement("IMG"); image.src = projectDomain + data.picturePath; var image_div = document.createElement("DIV"); image_div.className = "image"; image_div.appendChild(image); var title_div = document.createElement("DIV"); if(data.read){ title_div.className = "title selected"; } else{ title_div.className = "title"; } var name = document.createElement("SPAN"); name.appendChild(document.createTextNode(data.groupName)); title_div.appendChild(name); var date = document.createElement("SPAN"); date.className = "date"; title_div.appendChild(date); var type = document.createElement("SPAN"); type.className = "sub"; type.appendChild(document.createTextNode(data.username + " hat einen Gruppen-Beitrag gemacht")); title_div.appendChild(type); div.appendChild(image_div); div.appendChild(title_div); div.onclick = function () { currentHome.group(data.groupid, function () { markNotificationRead(data.notificationid, div); currentHome.post(data.id); }); }; return div; }; var createMentionNotification = function (data) { var div = document.createElement("DIV"); div.className = "entry"; var image = document.createElement("IMG"); image.src = projectDomain + data.picturePath; var image_div = document.createElement("DIV"); image_div.className = "image"; image_div.appendChild(image); var title_div = document.createElement("DIV"); if(data.read){ title_div.className = "title selected"; } else{ title_div.className = "title"; } var name = document.createElement("SPAN"); name.appendChild(document.createTextNode(data.username)); title_div.appendChild(name); var date = document.createElement("SPAN"); date.className = "date"; title_div.appendChild(date); var type = document.createElement("SPAN"); type.className = "sub"; type.appendChild(document.createTextNode("Hat dich in einen Kommentar erwähnt")); title_div.appendChild(type); div.appendChild(image_div); div.appendChild(title_div); div.onclick = function () { markNotificationRead(data.notificationid, div); currentHome.post(data.id); }; return div; }; var createContactNotification = function (data) { var div = document.createElement("DIV"); div.className = "entry"; var image = document.createElement("IMG"); image.src = projectDomain + data.picturePath; var image_div = document.createElement("DIV"); image_div.className = "image"; image_div.appendChild(image); var title_div = document.createElement("DIV"); if ( data.read ) { title_div.className = "title selected"; } else { title_div.className = "title"; } var name = document.createElement("SPAN"); name.appendChild(document.createTextNode(data.username)); title_div.appendChild(name); var date = document.createElement("SPAN"); date.className = "date"; title_div.appendChild(date); var type = document.createElement("SPAN"); type.className = "sub"; type.appendChild(document.createTextNode("Neuer persönlicher Beitrag")); title_div.appendChild(type); div.appendChild(image_div); div.appendChild(title_div); div.onclick = function () { //currentHome.reloadStream(function () { markNotificationRead(data.notificationid, div); currentHome.post(data.id); //}); }; return div; }; var createReplyNotification = function (data) { var div = document.createElement("DIV"); div.className = "entry"; var image = document.createElement("IMG"); image.src = projectDomain + data.picturePath; var image_div = document.createElement("DIV"); image_div.className = "image"; image_div.appendChild(image); var title_div = document.createElement("DIV"); if(data.read){ title_div.className = "title selected"; } else{ title_div.className = "title"; } var name = document.createElement("SPAN"); name.appendChild(document.createTextNode(data.replyPosterName)); title_div.appendChild(name); var date = document.createElement("SPAN"); date.className = "date"; title_div.appendChild(date); var repliedOnText = data.postPosterid === currentUser.id ? "deinen Beitrag kommentiert" : "einen von dir bereits kommentierten Beitrag kommentiert"; var type = document.createElement("SPAN"); type.className = "sub"; type.appendChild(document.createTextNode("Hat auf " + repliedOnText)); title_div.appendChild(type); div.appendChild(image_div); div.appendChild(title_div); div.onclick = function () { if(data.groupid) { currentHome.group(data.groupid, function () { markNotificationRead(data.notificationid, div); currentHome.post(data.id, function () { }); }) } else { currentHome.post(data.id, function () { markNotificationRead(data.notificationid, div); }); } }; return div; }; var createInviteNotification = function (data) { var div = document.createElement("DIV"); div.className = "entry"; var image = document.createElement("IMG"); image.src = projectDomain + data.adminPicture; var image_div = document.createElement("DIV"); image_div.className = "image"; image_div.appendChild(image); var title_div = document.createElement("DIV"); if(data.read){ title_div.className = "title selected"; } else{ title_div.className = "title"; } var name = document.createElement("SPAN"); name.appendChild(document.createTextNode(data.adminName)); title_div.appendChild(name); var date = document.createElement("SPAN"); date.className = "date"; title_div.appendChild(date); var type = document.createElement("SPAN"); type.className = "sub"; var changingText = data.private === "Y" ? "ein persönliches Gespräch" : "einen Raum"; var text = "hat dich zu " + changingText + " eingeladen"; type.appendChild(document.createTextNode(text)); title_div.appendChild(type); div.appendChild(image_div); div.appendChild(title_div); div.onclick = function () { markNotificationRead(data.notificationid, div); currentHome.room({ roomid : data.roomid }); }; return div; }; var createInviteWaitingNotification = function (data) { var div = document.createElement("DIV"); div.className = "entry"; var image = document.createElement("IMG"); image.src = projectDomain + data.adminPicture; var image_div = document.createElement("DIV"); image_div.className = "image"; image_div.appendChild(image); var title_div = document.createElement("DIV"); if(data.read){ title_div.className = "title selected"; } else{ title_div.className = "title"; } var name = document.createElement("SPAN"); name.appendChild(document.createTextNode( data.roomName)); title_div.appendChild(name); var date = document.createElement("SPAN"); date.className = "date"; title_div.appendChild(date); var type = document.createElement("SPAN"); type.className = "sub"; var text = "One trader wants to join your Team."; type.appendChild(document.createTextNode(text)); title_div.appendChild(type); div.appendChild(image_div); div.appendChild(title_div); div.onclick = function () { markNotificationRead(data.notificationid, div); currentHome.room({ roomid : data.roomid }); }; return div; }; var createRoomNotification = function (data) { var div = document.createElement("DIV"); div.className = "entry"; var image = document.createElement("IMG"); image.src = projectDomain + data.picturePath; var image_div = document.createElement("DIV"); image_div.className = "image"; image_div.appendChild(image); var title_div = document.createElement("DIV"); if(data.read){ title_div.className = "title selected"; } else{ title_div.className = "title"; } var name = document.createElement("SPAN"); name.appendChild(document.createTextNode(data.username)); title_div.appendChild(name); var date = document.createElement("SPAN"); date.className = "date"; title_div.appendChild(date); var type = document.createElement("SPAN"); type.className = "sub"; var text = "hat eine Nachricht geschrieben"; type.appendChild(document.createTextNode(text)); title_div.appendChild(type); div.appendChild(image_div); div.appendChild(title_div); div.onclick = function () { markNotificationRead(data.notificationid, div); currentHome.room({roomid : data.roomid}); }; return div; }; var updateCounter = function () { countElement.childNodes[0].textContent = notificationCount; currentHome.api.sendEvent( { 'type' : 'notification', 'event' : 'update-notifications-counter', 'value' : notificationCount } ) }; var notificationAlreadyExists = function (notificationid) { var i; for(i = 0; i < notifications.length; i++){ var notificationData = notifications[i].data; if(notificationid === notificationData.notificationid){ return true; } } return false; }; notificationCenter.resetCounter = function () { notificationCount = 0; updateCounter(); }; notificationCenter.element = document.createElement("DIV"); notificationCenter.element.className = "notifications-button"; //countElement.appendChild(balloon); notificationCenter.element.appendChild(countElement); notificationCenter.element.appendChild(notificationInformer); notificationCenter.increment = function () { notificationCount++; updateCounter(); }; notificationCenter.incrementRoomNotifications = function () { rooms_notification_count++; currentHome.updateRoomsCounter(rooms_notification_count); }; notificationCenter.resetRoomNotificationCounter = function () { rooms_notification_count = 0; currentHome.updateRoomsCounter(rooms_notification_count); }; notificationCenter.incrementTeamsNotifications = function () { teams_notification_count++; currentHome.updateTeamsCounter(teams_notification_count); }; notificationCenter.resetTeamsNotificationCounter = function () { teams_notification_count = 0; currentHome.updateTeamsCounter(teams_notification_count); }; notificationCenter.addNotification = function (type, data) { if( !notificationAlreadyExists(data.notificationid)){ notifications.unshift({ type: type, data: data }); var shouldCount = true; if(type === "room-message" && notifications.length > 1){ shouldCount = currentHome.rooms_counter == 0 || !canGroup(data, notifications[1].data); } if(!data.saw && (notificationCount === 0 || (shouldCount && notificationCount > 0))){ notificationCenter.increment(); if ( type == 'room-message') { if ( data.roomType == 'teams' ) { notificationCenter.incrementTeamsNotifications(); } else if ( data.roomType == 'private' ) { notificationCenter.incrementRoomNotifications(); } } } } }; notificationCenter.element.onclick = function (event) { socketGateway.emit("getProfileAsync", { "userid": currentUser.id }, function( data ){ notificationCenter.resetCounter(); data.tab = 'notifications'; currentHome.getProfile( data ); }); if ( event ) { event.stopPropagation(); } /* if(notificationInformer.style.display === 'none'){ showNotifications(); markNotificationsSaw(function () { notificationCenter.resetCounter(); }); } else{ notificationInformer.style.display = 'none' } */ }; notificationCenter.onClick = function (callback) { onClickCallback = callback; }; notificationCenter.createNotificationRow = function( notif ) { if (notif.type === "contact-post") { return createContactNotification(notif.data); } else if (notif.type === "mentioned-post") { return createMentionNotification(notif.data); } else if (notif.type === "reply") { return createReplyNotification(notif.data); } else if (notif.type === "room-invite"){ return createInviteNotification(notif.data); } else if (notif.type === "room-member-waiting"){ return createInviteWaitingNotification(notif.data); } else if(notif.type === "room-message"){ return createRoomNotification(notif.data); } else { return createGroupNotification(notif.data); } }; notificationCenter.showUserFeedback = function( message, x, y ) { if ( x == undefined ) { x = 0; } if ( y == undefined ) { y = 10; } clearTimeout( notificationCenter.user_feedback_timeout ); notificationCenter.user_feedback_element.style.top = y + 'px'; notificationCenter.user_feedback_element.style.left = x + 'px'; notificationCenter.user_feedback_element.style.display = 'block'; notificationCenter.user_feedback_element.textContent = message; notificationCenter.user_feedback_timeout = setTimeout( function(){ notificationCenter.user_feedback_element.style.display = 'none' }, 1.5 * 1000 ); }; notificationCenter.getNumberOfNotifications = function(){ return notificationCount; } return notificationCenter; } /* A wrapper class for socket.io, giving it some option like manual managing of reconnections. */ function SocketGatewayClient( session ) { var socketGateway = {}; var events = {}; var options = { "secure": true, "reconnection": false, "autoConnect": false } if ( session != undefined ) { options["query"] = 'session=' + session; } var socket = ioTFCompatible( projectDomain + '/traderChat', options ); socket.on("disconnect", function () { informSubscribers({ "eventName": "disconnect" }) }); socket.on("event", function (args) { informSubscribers(args); }); socket.on("error", function (args) { //console.log( args ) }); socket.on("connect_error", function (err) { console.log( err.message ) }); socket.on("connect", function () { informSubscribers({ "eventName": "connect" }); }); function informSubscribers (args) { var eventName = args.eventName; if(eventName in events){ var callbackArray = events[eventName], i, callbackArrayLength = callbackArray.length; for(i = 0; i < callbackArrayLength; i++){ callbackArray[i][0](args); } } } socketGateway.subscribe = function (eventName, callback, context) { if(!events[eventName]){ events[eventName] = []; } events[eventName].push([callback, context]); }; socketGateway.emit = function (eventName, args, callback) { socket.emit(eventName, args, callback); }; socketGateway.unsubscribe = function(eventName, context){ if(eventName in events && context){ var i, event = events[eventName], eventLength = event.length; for(i = 0; i < eventLength; i++){ if(event[i][1] === context){ event.splice(i, 1); return; } } } }; socketGateway.disconnect = function () { socket.disconnect(); }; socketGateway.isConnected = function () { return socket && socket.connected; }; socketGateway.isDisconnected = function () { return !socketGateway.isConnected(); }; socketGateway.open = function (callback) { socket.open(callback); }; socket.open(function () { //console.log("bla"); }); socket.on("connect_timeout", function () { //console.log("blabla"); }); return socketGateway; } /* A field used to search for users of the chat */ function SearchField(parent) { var searchField = {}; var timeoutNum; var inputedText; var results; var onResultClickCallback; searchField.stopAndRemoveSearch = function () { stopTimeout(); searchField.clearResults(); clearTextField(); }; var stopTimeout = function () { if (timeoutNum) { timeoutNum = undefined; clearTimeout(timeoutNum); } }; searchField.clearResults = function () { if (results) { var parentElement = results.parentNode; parentElement.removeChild(results); results = undefined; } }; var clearTextField = function () { textField.value = null; }; var createNoPictureResult = function( text ) { var resultTable = document.createElement("TABLE"); resultTable.className = "search-result"; var tr1 = document.createElement("TR"); var nameCell = document.createElement("TD"); nameCell.className = "name"; nameCell.style.fontSize = "13px"; nameCell.style.padding = "5px 10px"; var name = document.createTextNode(text); nameCell.appendChild(name); tr1.appendChild(nameCell); resultTable.appendChild(tr1); return resultTable; }; var createResult = function (args) { var resultTable = document.createElement("TABLE"); resultTable.className = "search-result"; var tr1 = document.createElement("TR"); var pictureCell = document.createElement("TD"); pictureCell.className = "picture"; var picture = document.createElement("IMG"); picture.className = "search-result-picture"; picture.src = projectDomain + args.picture; var nameCell = document.createElement("TD"); nameCell.className = "name"; var name = document.createTextNode(args.name); pictureCell.appendChild(picture); nameCell.appendChild(name); tr1.appendChild(pictureCell); tr1.appendChild(nameCell); resultTable.appendChild(tr1); return resultTable; }; var createUserResult = function (args) { var resultTable = createResult(args); resultTable.onclick = function () { searchField.clearResults(); clearTextField(); socketGateway.emit("getProfile", { "userid": args.id }); }; return resultTable; }; var createGroupResult = function (args) { var resultTable = createResult(args); resultTable.onclick = function () { searchField.clearResults(); clearTextField(); socketGateway.emit("getGroupInfo", args.id); }; return resultTable; }; var createTagResult = function (tag) { var resultTable = createNoPictureResult('#' + tag); resultTable.onclick = function () { searchField.clearResults(); clearTextField(); currentHome.tag(tag); }; return resultTable; }; var createStockResult = function (args) { var resultTable = createNoPictureResult(args.name); resultTable.onclick = function () { searchField.clearResults(); clearTextField(); currentHome.stock(args); }; return resultTable; }; var isInFilter = function (value) { }; var createUsersResults = function (users) { var i, usersLength = users.length, user; var usersResults = document.createElement("DIV"); for (i = 0; i < usersLength; i++) { user = users[i]; usersResults.appendChild(createUserResult(user)); } return usersResults; }; var createGroupsResults = function (groups) { var i, groupsLength = groups.length, group; var groupsResults = document.createElement("DIV"); for (i = 0; i < groupsLength; i++) { group = groups[i]; groupsResults.appendChild(createGroupResult(group)); } return groupsResults; }; var createTagsResult = function (tags) { var i, tagsLength = tags.length; var tagsResults = document.createElement("DIV"); for (i = 0; i < tagsLength; i++) { tagsResults.appendChild(createTagResult(tags[i])); } return tagsResults; }; var createStocksResult = function (stocks) { var i, stocksLength = stocks.length; var stocksResults = document.createElement("DIV"); for (i = 0; i < stocksLength; i++) { stocksResults.appendChild(createStockResult(stocks[i])); } return stocksResults; }; var createUserTagResult = function (user) { var resultTable = createResult(user); resultTable.onclick = function () { user["type"] = "user"; onResultClickCallback(user); searchField.clearResults(); }; return resultTable; }; var createGroupTagResult = function (group) { var resultTable = createResult(group); resultTable.onclick = function () { group["type"] = "group"; onResultClickCallback(group); searchField.clearResults(); }; return resultTable; }; var createUsersTagResults = function (users, usersFilters) { var i, usersLength = users.length, user; var usersResults = document.createElement("DIV"); for (i = 0; i < usersLength; i++) { user = users[i]; if(usersFilters.indexOf(parseInt(user.id)) === -1){ //if not in filter usersResults.appendChild(createUserTagResult(user)); } } return usersResults; }; var createGroupsTagResults = function (groups) { var i, groupsLength = groups.length, group; var groupsResults = document.createElement("DIV"); for (i = 0; i < groupsLength; i++) { group = groups[i]; groupsResults.appendChild(createGroupTagResult(group)); } return groupsResults; }; var createResults = function (args, usersFunction, groupsFunction, tagsFunction, stocksFunction) { var users = args.users || []; var groups = args.groups || []; var tags = args.tags || []; var stocks = args.stocks || []; var usersFilter = args.usersFilter ? args.usersFilter : []; //an array of IDs to be excluded from the results var usersLength = users.length, groupsLength = groups.length, tagsLength = tags.length, stocksLength = stocks.length; if (usersLength > 0 || groupsLength > 0 || tagsLength > 0 || stocksLength > 0 ) { searchField.clearResults(); results = document.createElement("DIV"); results.className = "result-container"; results.onmouseleave = function () { searchField.clearResults(); }; if (usersLength > 0) { var usersLabel = document.createElement("DIV"); usersLabel.className = "search-results-label"; usersLabel.textContent = "Traders"; results.appendChild(usersLabel); results.appendChild(usersFunction(users, usersFilter)); } if (groupsLength > 0) { var groupsLabel = document.createElement("DIV"); groupsLabel.className = "search-results-label"; groupsLabel.textContent = "Groups"; results.appendChild(groupsLabel); results.appendChild(groupsFunction(groups)); } if (tagsLength > 0) { var tagsLabel = document.createElement("DIV"); tagsLabel.className = "search-results-label"; tagsLabel.textContent = "Tags"; results.appendChild(tagsLabel); results.appendChild(tagsFunction(tags)); } if (stocksLength > 0) { var stocksLabel = document.createElement("DIV"); stocksLabel.className = "search-results-label"; stocksLabel.textContent = "Aktien"; results.appendChild(stocksLabel); results.appendChild(stocksFunction(stocks)); } } else { searchField.clearResults(); } }; var createSearchFieldResults = function (args) { createResults(args, createUsersResults, createGroupsResults, createTagsResult, createStocksResult); }; var createTaggingResults = function (args) { createResults(args, createUsersTagResults, createGroupsTagResults); }; searchField.createAndAttachResults = function (args, element, callback ) { searchField.clearResults(); createTaggingResults(args); onResultClickCallback = callback; if(results){ element.appendChild(results); return results; } }; if(parent){ //if a parent was given, then a search field for input is attached to it searchField.element = document.createElement("DIV"); searchField.element.className = "search-field-container menu-bar-button"; var textField = document.createElement("INPUT"); textField.className = "search-text-field"; textField.type = "text"; textField.placeholder = "Suche nach Tradern oder Gruppen"; if(!currentUser){ textField.disabled = true; } textField.onkeyup = function () { inputedText = textField.value.trim(); stopTimeout(); if (inputedText.length > 0) { var textToBeSent = inputedText; //make a copy for the timeout timeoutNum = setTimeout(function () { socketGateway.emit("searchText", textToBeSent, function (args) { timeoutNum = undefined; if (args["originalText"] === inputedText) { createSearchFieldResults(args); if(results){ searchField.element.appendChild(results); } } }); }, 200); } else { searchField.clearResults(); } }; /* var searchIcon = document.createElement("IMG"); searchIcon.className = "search-icon"; searchIcon.height = 15; searchIcon.src = "public/images/searchIcon.png"; */ searchField.element.appendChild(textField); // searchField.element.appendChild(searchIcon); parent.appendChild(searchField.element); } return searchField; } /* A simple element that overlays a picture clicked from a post. */ function PictureViewer(parent, args) { var pictureViewer = {}; var element = document.createElement("DIV"); element.className = "element-blocker picture"; element.onclick = function (event) { event.stopPropagation(); close() }; var pictureContainer = document.createElement("DIV"); pictureContainer.style.position = "relative"; pictureContainer.style.float = "left"; pictureContainer.style.width = "100%"; pictureContainer.style.height = "100%"; pictureContainer.style.overflow = "auto"; var picture = document.createElement("IMG"); picture.className = "non-blocking picture"; picture.src = args.path; pictureContainer.appendChild(picture); element.appendChild(pictureContainer); var close = function () { parent.removeChild(element); }; var open_bigger = document.createElement("DIV"); open_bigger.className = "fa fa-external-link"; open_bigger.style.position = "absolute"; open_bigger.style.top = "10px"; open_bigger.style.right = "10px"; open_bigger.style.padding = "10px"; open_bigger.style.background = "white"; open_bigger.style.color = "black"; open_bigger.style.fontsize = "16px"; open_bigger.style.cursor = "pointer"; open_bigger.title = "Open in new tab"; open_bigger.onclick = function(){ window.open( args.path ,'_blank' ) close() } pictureContainer.appendChild( open_bigger ); parent.insertBefore(element, parent.firstChild); return pictureViewer; } /* This class is supposed to inform outsiders of events happening in the chat. Current only used for if the chat is ready. */ function ChatEventManager() { var chatEventManager = {}; var eventSubscribers = { "chatReady": [] }; chatEventManager.onChatReady = function (context, callback) { eventSubscribers["chatReady"].push({"context": context, "callback": callback}); }; chatEventManager.removeChatReady = function (context, callback) { removeSubscriber("chatReady", context, callback); }; chatEventManager.informChatReady = function () { informSubscribers("chatReady"); }; function informSubscribers(eventType) { var i, subscriberArray = eventSubscribers[eventType], l = subscriberArray.length; for(i = 0; i < l; i++){ var context = subscriberArray[i]["context"]; var callback = subscriberArray[i]["callback"]; callback.call(context); } } function removeSubscriber(eventType, context, callback) { var i, subscriberArray = eventSubscribers[eventType], l = subscriberArray.length, subscriberContext, subscriberCallback; for(i = 0; i < l; i++){ subscriberContext = subscriberArray[i]["context"]; subscriberCallback = subscriberArray[i]["callback"]; if(subscriberContext === context && subscriberCallback === callback){ subscriberArray.splice(i); i--; } } } return chatEventManager; } !function(e,t){"function"==typeof define&&define.amd?define(["exports"],t):t("object"==typeof exports&&"string"!=typeof exports.nodeName?exports:e.commonJsStrict={})}(this,function(exports){function e(e){if(e in O)return e;for(var t=e[0].toUpperCase()+e.slice(1),n=N.length;n--;)if(e=N[n]+t,e in O)return e}function t(e,n){e=e||{};for(var i in n)n[i]&&n[i].constructor&&n[i].constructor===Object?(e[i]=e[i]||{},t(e[i],n[i])):e[i]=n[i];return e}function n(e,t,n){var i;return function(){var o=this,r=arguments,a=function(){i=null,n||e.apply(o,r)},l=n&&!i;clearTimeout(i),i=setTimeout(a,t),l&&e.apply(o,r)}}function i(e){if("createEvent"in document){var t=document.createEvent("HTMLEvents");t.initEvent("change",!1,!0),e.dispatchEvent(t)}else e.fireEvent("onchange")}function o(e,t,n){if("string"==typeof t){var i=t;t={},t[i]=n}for(var o in t)e.style[o]=t[o]}function r(e,t){e.classList?e.classList.add(t):e.className+=" "+t}function a(e,t){e.classList?e.classList.remove(t):e.className=e.className.replace(t,"")}function l(e){return parseInt(e,10)}function s(e,t){var n=t||new Image;return n.style.opacity=0,new Promise(function(t){n.src===e?t(n):(n.removeAttribute("crossOrigin"),e.match(/^https?:\/\/|^\/\//)&&n.setAttribute("crossOrigin","anonymous"),n.onload=function(){setTimeout(function(){t(n)},1)},n.src=e)})}function u(e,t){window.EXIF||t(0),EXIF.getData(e,function(){var e=EXIF.getTag(this,"Orientation");t(e)})}function c(e,t,n){var i=t.width,o=t.height,r=e.getContext("2d");switch(e.width=t.width,e.height=t.height,r.save(),n){case 2:r.translate(i,0),r.scale(-1,1);break;case 3:r.translate(i,o),r.rotate(180*Math.PI/180);break;case 4:r.translate(0,o),r.scale(1,-1);break;case 5:e.width=o,e.height=i,r.rotate(90*Math.PI/180),r.scale(1,-1);break;case 6:e.width=o,e.height=i,r.rotate(90*Math.PI/180),r.translate(0,-o);break;case 7:e.width=o,e.height=i,r.rotate(-90*Math.PI/180),r.translate(-i,o),r.scale(1,-1);break;case 8:e.width=o,e.height=i,r.translate(0,i),r.rotate(-90*Math.PI/180)}r.drawImage(t,0,0,i,o),r.restore()}function h(){var e,t,n,i,a,l,s=this,u="croppie-container",c=s.options.viewport.type?"cr-vp-"+s.options.viewport.type:null;s.options.useCanvas=s.options.enableOrientation||p.call(s),s.data={},s.elements={},e=s.elements.boundary=document.createElement("div"),n=s.elements.viewport=document.createElement("div"),t=s.elements.img=document.createElement("img"),i=s.elements.overlay=document.createElement("div"),s.options.useCanvas?(s.elements.canvas=document.createElement("canvas"),s.elements.preview=s.elements.canvas):s.elements.preview=s.elements.img,r(e,"cr-boundary"),a=s.options.boundary.width,l=s.options.boundary.height,o(e,{width:a+(isNaN(a)?"":"px"),height:l+(isNaN(l)?"":"px")}),r(n,"cr-viewport"),c&&r(n,c),o(n,{width:s.options.viewport.width+"px",height:s.options.viewport.height+"px"}),n.setAttribute("tabindex",0),r(s.elements.preview,"cr-image"),r(i,"cr-overlay"),s.element.appendChild(e),e.appendChild(s.elements.preview),e.appendChild(n),e.appendChild(i),r(s.element,u),s.options.customClass&&r(s.element,s.options.customClass),w.call(this),s.options.enableZoom&&d.call(s)}function p(){return this.options.enableExif&&window.EXIF}function m(e){if(this.options.enableZoom){var t=this.elements.zoomer,n=F(e,4);t.value=Math.max(t.min,Math.min(t.max,n))}}function d(){function e(){f.call(n,{value:parseFloat(o.value),origin:new D(n.elements.preview),viewportRect:n.elements.viewport.getBoundingClientRect(),transform:T.parse(n.elements.preview)})}function t(t){var i,o;i=t.wheelDelta?t.wheelDelta/1200:t.deltaY?t.deltaY/1060:t.detail?t.detail/-60:0,o=n._currentZoom+i*n._currentZoom,t.preventDefault(),m.call(n,o),e.call(n)}var n=this,i=n.elements.zoomerWrap=document.createElement("div"),o=n.elements.zoomer=document.createElement("input");r(i,"cr-slider-wrap"),r(o,"cr-slider"),o.type="range",o.step="0.0001",o.value=1,o.style.display=n.options.showZoomer?"":"none",n.element.appendChild(i),i.appendChild(o),n._currentZoom=1,n.elements.zoomer.addEventListener("input",e),n.elements.zoomer.addEventListener("change",e),n.options.mouseWheelZoom&&(n.elements.boundary.addEventListener("mousewheel",t),n.elements.boundary.addEventListener("DOMMouseScroll",t))}function f(e){function t(){var e={};e[z]=i.toString(),e[S]=a.toString(),o(n.elements.preview,e)}var n=this,i=e?e.transform:T.parse(n.elements.preview),r=e?e.viewportRect:n.elements.viewport.getBoundingClientRect(),a=e?e.origin:new D(n.elements.preview);if(n._currentZoom=e?e.value:n._currentZoom,i.scale=n._currentZoom,t(),n.options.enforceBoundary){var l=v.call(n,r),s=l.translate,u=l.origin;i.x>=s.maxX&&(a.x=u.minX,i.x=s.maxX),i.x<=s.minX&&(a.x=u.maxX,i.x=s.minX),i.y>=s.maxY&&(a.y=u.minY,i.y=s.maxY),i.y<=s.minY&&(a.y=u.maxY,i.y=s.minY)}t(),q.call(n),b.call(n)}function v(e){var t=this,n=t._currentZoom,i=e.width,o=e.height,r=t.elements.boundary.clientWidth/2,a=t.elements.boundary.clientHeight/2,l=t.elements.preview.getBoundingClientRect(),s=l.width,u=l.height,c=i/2,h=o/2,p=-1*(c/n-r),m=p-(s*(1/n)-i*(1/n)),d=-1*(h/n-a),f=d-(u*(1/n)-o*(1/n)),v=1/n*c,g=s*(1/n)-v,w=1/n*h,y=u*(1/n)-w;return{translate:{maxX:p,minX:m,maxY:d,minY:f},origin:{maxX:g,minX:v,maxY:y,minY:w}}}function g(){var e=this,t=e._currentZoom,n=e.elements.preview.getBoundingClientRect(),i=e.elements.viewport.getBoundingClientRect(),r=T.parse(e.elements.preview.style[z]),a=new D(e.elements.preview),l=i.top-n.top+i.height/2,s=i.left-n.left+i.width/2,u={},c={};u.y=l/t,u.x=s/t,c.y=(u.y-a.y)*(1-t),c.x=(u.x-a.x)*(1-t),r.x-=c.x,r.y-=c.y;var h={};h[S]=u.x+"px "+u.y+"px",h[z]=r.toString(),o(e.elements.preview,h)}function w(){function e(e,t){var n=d.elements.preview.getBoundingClientRect(),i=p.y+t,o=p.x+e;d.options.enforceBoundary?(h.top>n.top+t&&h.bottomn.left+e&&h.right=37&&e.keyCode<=40){e.preventDefault();var l=t(e.keyCode);p=T.parse(d.elements.preview),document.body.style[P]="none",h=d.elements.viewport.getBoundingClientRect(),n(l)}}else{var s=0;s=e.keyCode==o?parseFloat(d.elements.zoomer.value,10)+parseFloat(d.elements.zoomer.step,10):parseFloat(d.elements.zoomer.value,10)-parseFloat(d.elements.zoomer.step,10),d.setZoom(s)}}function n(t){var n=t[0],i=t[1],r={};e(n,i),r[z]=p.toString(),o(d.elements.preview,r),y.call(d),document.body.style[P]="",g.call(d),b.call(d),c=0}function r(e){if(e.preventDefault(),!f){if(f=!0,s=e.pageX,u=e.pageY,e.touches){var t=e.touches[0];s=t.pageX,u=t.pageY}p=T.parse(d.elements.preview),window.addEventListener("mousemove",a),window.addEventListener("touchmove",a),window.addEventListener("mouseup",l),window.addEventListener("touchend",l),document.body.style[P]="none",h=d.elements.viewport.getBoundingClientRect()}}function a(t){t.preventDefault();var n=t.pageX,r=t.pageY;if(t.touches){var a=t.touches[0];n=a.pageX,r=a.pageY}var l=n-s,h=r-u,f={};if("touchmove"==t.type&&t.touches.length>1){var v=t.touches[0],g=t.touches[1],w=Math.sqrt((v.pageX-g.pageX)*(v.pageX-g.pageX)+(v.pageY-g.pageY)*(v.pageY-g.pageY));c||(c=w/d._currentZoom);var b=w/c;return m.call(d,b),void i(d.elements.zoomer)}e(l,h),f[z]=p.toString(),o(d.elements.preview,f),y.call(d),u=r,s=n}function l(){f=!1,window.removeEventListener("mousemove",a),window.removeEventListener("touchmove",a),window.removeEventListener("mouseup",l),window.removeEventListener("touchend",l),document.body.style[P]="",g.call(d),b.call(d),c=0}var s,u,c,h,p,d=this,f=!1;d.elements.overlay.addEventListener("mousedown",r),d.elements.viewport.addEventListener("keydown",t),d.elements.overlay.addEventListener("touchstart",r)}function y(){var e=this,t=e.elements.boundary.getBoundingClientRect(),n=e.elements.preview.getBoundingClientRect();o(e.elements.overlay,{width:n.width+"px",height:n.height+"px",top:n.top-t.top+"px",left:n.left-t.left+"px"})}function b(){var e,t=this,n=t.get();if(x.call(t))if(t.options.update.call(t,n),t.$&&"undefined"==typeof Prototype)t.$(t.element).trigger("update",n);else{var e;window.CustomEvent?e=new CustomEvent("update",{detail:n}):(e=document.createEvent("CustomEvent"),e.initCustomEvent("update",!0,!0,n)),t.element.dispatchEvent(e)}}function x(){return this.elements.preview.offsetHeight>0&&this.elements.preview.offsetWidth>0}function C(){var e,t,n,r,a,l=this,s=0,u=1.5,c=1,h={},p=l.elements.preview,d=l.elements.zoomer,f=new T(0,0,c),v=new D,w=x.call(l);if(w&&!l.data.bound){if(l.data.bound=!0,h[z]=f.toString(),h[S]=v.toString(),h.opacity=1,o(p,h),e=p.getBoundingClientRect(),t=l.elements.viewport.getBoundingClientRect(),n=l.elements.boundary.getBoundingClientRect(),l._originalImageWidth=e.width,l._originalImageHeight=e.height,l.options.enableZoom){l.options.enforceBoundary&&(r=t.width/e.width,a=t.height/e.height,s=Math.max(r,a)),s>=u&&(u=s+1),d.min=F(s,4),d.max=F(u,4);var b=Math.max(n.width/e.width,n.height/e.height);c=null!==l.data.boundZoom?l.data.boundZoom:b,m.call(l,c),i(d)}else l._currentZoom=c;f.scale=l._currentZoom,h[z]=f.toString(),o(p,h),l.data.points.length?E.call(l,l.data.points):_.call(l),g.call(l),y.call(l)}}function E(e){if(4!=e.length)throw"Croppie - Invalid number of points supplied: "+e;var t=this,n=e[2]-e[0],i=t.elements.viewport.getBoundingClientRect(),r=t.elements.boundary.getBoundingClientRect(),a={left:i.left-r.left,top:i.top-r.top},l=i.width/n,s=e[1],u=e[0],c=-1*e[1]+a.top,h=-1*e[0]+a.left,p={};p[S]=u+"px "+s+"px",p[z]=new T(h,c,l).toString(),o(t.elements.preview,p),m.call(t,l),t._currentZoom=l}function _(){var e=this,t=e.elements.preview.getBoundingClientRect(),n=e.elements.viewport.getBoundingClientRect(),i=e.elements.boundary.getBoundingClientRect(),r=n.left-i.left,a=n.top-i.top,l=r-(t.width-n.width)/2,s=a-(t.height-n.height)/2,u=new T(l,s,e._currentZoom);o(e.elements.preview,z,u.toString())}function B(e){var t=this,n=t.elements.canvas,i=t.elements.img,o=n.getContext("2d"),r=p.call(t),e=t.options.enableOrientation&&e;o.clearRect(0,0,n.width,n.height),n.width=i.width,n.height=i.height,r?u(i,function(t){c(n,i,l(t,10)),e&&c(n,i,e)}):e&&c(n,i,e)}function R(e){var t=this,n=e.points,i=l(n[0]),o=l(n[1]),r=l(n[2]),a=l(n[3]),s=r-i,u=a-o,c=e.circle,h=document.createElement("canvas"),p=h.getContext("2d"),m=s,d=u,f=0,v=0,g=m,w=d,y=e.outputWidth&&e.outputHeight,b=1;return y&&(g=e.outputWidth,w=e.outputHeight,b=g/m),h.width=g,h.height=w,e.backgroundColor&&(p.fillStyle=e.backgroundColor,p.fillRect(0,0,m,d)),0>i&&(f=Math.abs(i),i=0),0>o&&(v=Math.abs(o),o=0),r>t._originalImageWidth&&(s=t._originalImageWidth-i,m=s),a>t._originalImageHeight&&(u=t._originalImageHeight-o,d=u),1!==b&&(f*=b,v*=b,m*=b,d*=b),p.drawImage(this.elements.preview,i,o,s,u,f,v,m,d),c&&(p.fillStyle="#fff",p.globalCompositeOperation="destination-in",p.beginPath(),p.arc(m/2,d/2,m/2,0,2*Math.PI,!0),p.closePath(),p.fill()),h}function I(e){var t=e.points,n=document.createElement("div"),i=document.createElement("img"),a=t[2]-t[0],l=t[3]-t[1];return r(n,"croppie-result"),n.appendChild(i),o(i,{left:-1*t[0]+"px",top:-1*t[1]+"px"}),i.src=e.url,o(n,{width:a+"px",height:l+"px"}),n}function Z(e){return R.call(this,e).toDataURL(e.format,e.quality)}function L(e){var t=this;return new Promise(function(n){R.call(t,e).toBlob(function(e){n(e)},e.format,e.quality)})}function M(e,t){var n,i=this,o=[],r=null;if("string"==typeof e)n=e,e={};else if(Array.isArray(e))o=e.slice();else{if("undefined"==typeof e&&i.data.url)return C.call(i),b.call(i),null;n=e.url,o=e.points||[],r="undefined"==typeof e.zoom?null:e.zoom}return i.data.bound=!1,i.data.url=n||i.data.url,i.data.boundZoom=r,s(n,i.elements.img).then(function(n){if(o.length)i.options.relative&&(o=[o[0]*n.naturalWidth/100,o[1]*n.naturalHeight/100,o[2]*n.naturalWidth/100,o[3]*n.naturalHeight/100]),i.data.points=o.map(function(e){return parseFloat(e)});else{var r,a,l=n.naturalWidth,s=n.naturalHeight,u=i.elements.viewport.getBoundingClientRect(),c=u.width/u.height;l/s>c?(a=s,r=a*c):(r=l,a=r/c);var h=(l-r)/2,p=(s-a)/2,m=h+r,d=p+a;i.data.points=[h,p,m,d]}i.options.useCanvas&&(i.elements.img.exifdata=null,B.call(i,e.orientation||1)),C.call(i),b.call(i),t&&t()})}function F(e,t){return parseFloat(e).toFixed(t||0)}function W(){var e=this,t=e.elements.preview.getBoundingClientRect(),n=e.elements.viewport.getBoundingClientRect(),i=n.left-t.left,o=n.top-t.top,r=(n.width-e.elements.viewport.offsetWidth)/2,a=(n.height-e.elements.viewport.offsetHeight)/2,l=i+e.elements.viewport.offsetWidth+r,s=o+e.elements.viewport.offsetHeight+a,u=e._currentZoom;(u===1/0||isNaN(u))&&(u=1);var c=e.options.enforceBoundary?0:Number.NEGATIVE_INFINITY;return i=Math.max(c,i/u),o=Math.max(c,o/u),l=Math.max(c,l/u),s=Math.max(c,s/u),{points:[F(i),F(o),F(l),F(s)],zoom:u}}function X(e){var n,i=this,o=W.call(i),r=t(U,t({},e)),a="string"==typeof e?e:r.type||"base64",l=r.size,s=r.format,u=r.quality,c=r.backgroundColor,h="boolean"==typeof r.circle?r.circle:"circle"===i.options.viewport.type,p=i.elements.viewport.getBoundingClientRect(),m=p.width/p.height;return"viewport"===l?(o.outputWidth=p.width,o.outputHeight=p.height):"object"==typeof l&&(l.width&&l.height?(o.outputWidth=l.width,o.outputHeight=l.height):l.width?(o.outputWidth=l.width,o.outputHeight=l.width/m):l.height&&(o.outputWidth=l.height*m,o.outputHeight=l.height)),Q.indexOf(s)>-1&&(o.format="image/"+s,o.quality=u),o.circle=h,o.url=i.data.url,o.backgroundColor=c,n=new Promise(function(e){switch(a.toLowerCase()){case"rawcanvas":e(R.call(i,o));break;case"canvas":case"base64":e(Z.call(i,o));break;case"blob":L.call(i,o).then(e);break;default:e(I.call(i,o))}})}function k(){C.call(this)}function H(e){if(!this.options.useCanvas)throw"Croppie: Cannot rotate without enableOrientation";var t=this,n=t.elements.canvas,i=(t.elements.img,document.createElement("canvas")),o=1;i.width=n.width,i.height=n.height;var r=i.getContext("2d");r.drawImage(n,0,0),(90===e||-270===e)&&(o=6),(-90===e||270===e)&&(o=8),(180===e||-180===e)&&(o=3),c(n,i,o),f.call(t)}function Y(){var e=this;e.element.removeChild(e.elements.boundary),a(e.element,"croppie-container"),e.options.enableZoom&&e.element.removeChild(e.elements.zoomerWrap),delete e.elements}function j(e,n){if(this.element=e,this.options=t(t({},j.defaults),n),"img"===this.element.tagName.toLowerCase()){var i=this.element;r(i,"cr-original-image");var o=document.createElement("div");this.element.parentNode.appendChild(o),o.appendChild(i),this.element=o,this.options.url=this.options.url||i.src}if(h.call(this),this.options.url){var a={url:this.options.url,points:this.options.points};delete this.options.url,delete this.options.points,M.call(this,a)}}"function"!=typeof Promise&&!function(e){function t(e,t){return function(){e.apply(t,arguments)}}function n(e){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof e)throw new TypeError("not a function");this._state=null,this._value=null,this._deferreds=[],s(e,t(o,this),t(r,this))}function i(e){var t=this;return null===this._state?void this._deferreds.push(e):void c(function(){var n=t._state?e.onFulfilled:e.onRejected;if(null===n)return void(t._state?e.resolve:e.reject)(t._value);var i;try{i=n(t._value)}catch(o){return void e.reject(o)}e.resolve(i)})}function o(e){try{if(e===this)throw new TypeError("A promise cannot be resolved with itself.");if(e&&("object"==typeof e||"function"==typeof e)){var n=e.then;if("function"==typeof n)return void s(t(n,e),t(o,this),t(r,this))}this._state=!0,this._value=e,a.call(this)}catch(i){r.call(this,i)}}function r(e){this._state=!1,this._value=e,a.call(this)}function a(){for(var e=0,t=this._deferreds.length;t>e;e++)i.call(this,this._deferreds[e]);this._deferreds=null}function l(e,t,n,i){this.onFulfilled="function"==typeof e?e:null,this.onRejected="function"==typeof t?t:null,this.resolve=n,this.reject=i}function s(e,t,n){var i=!1;try{e(function(e){i||(i=!0,t(e))},function(e){i||(i=!0,n(e))})}catch(o){if(i)return;i=!0,n(o)}}var u=setTimeout,c="function"==typeof setImmediate&&setImmediate||function(e){u(e,1)},h=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};n.prototype["catch"]=function(e){return this.then(null,e)},n.prototype.then=function(e,t){var o=this;return new n(function(n,r){i.call(o,new l(e,t,n,r))})},n.all=function(){var e=Array.prototype.slice.call(1===arguments.length&&h(arguments[0])?arguments[0]:arguments);return new n(function(t,n){function i(r,a){try{if(a&&("object"==typeof a||"function"==typeof a)){var l=a.then;if("function"==typeof l)return void l.call(a,function(e){i(r,e)},n)}e[r]=a,0===--o&&t(e)}catch(s){n(s)}}if(0===e.length)return t([]);for(var o=e.length,r=0;ri;i++)e[i].then(t,n)})},n._setImmediateFn=function(e){c=e},"undefined"!=typeof module&&module.exports?module.exports=n:e.Promise||(e.Promise=n)}(this),"function"!=typeof window.CustomEvent&&!function(){function e(e,t){t=t||{bubbles:!1,cancelable:!1,detail:void 0};var n=document.createEvent("CustomEvent");return n.initCustomEvent(e,t.bubbles,t.cancelable,t.detail),n}e.prototype=window.Event.prototype,window.CustomEvent=e}(),HTMLCanvasElement.prototype.toBlob||Object.defineProperty(HTMLCanvasElement.prototype,"toBlob",{value:function(e,t,n){for(var i=atob(this.toDataURL(t,n).split(",")[1]),o=i.length,r=new Uint8Array(o),a=0;o>a;a++)r[a]=i.charCodeAt(a);e(new Blob([r],{type:t||"image/png"}))}});var S,z,P,N=["Webkit","Moz","ms"],O=document.createElement("div").style;z=e("transform"),S=e("transformOrigin"),P=e("userSelect");var A={translate3d:{suffix:", 0px"},translate:{suffix:""}},T=function(e,t,n){this.x=parseFloat(e),this.y=parseFloat(t),this.scale=parseFloat(n)};T.parse=function(e){return e.style?T.parse(e.style[z]):e.indexOf("matrix")>-1||e.indexOf("none")>-1?T.fromMatrix(e):T.fromString(e)},T.fromMatrix=function(e){var t=e.substring(7).split(",");return t.length&&"none"!==e||(t=[1,0,0,1,0,0]),new T(l(t[4]),l(t[5]),parseFloat(t[0]))},T.fromString=function(e){var t=e.split(") "),n=t[0].substring(j.globals.translate.length+1).split(","),i=t.length>1?t[1].substring(6):1,o=n.length>1?n[0]:0,r=n.length>1?n[1]:0;return new T(o,r,i)},T.prototype.toString=function(){var e=A[j.globals.translate].suffix||"";return j.globals.translate+"("+this.x+"px, "+this.y+"px"+e+") scale("+this.scale+")"};var D=function(e){if(!e||!e.style[S])return this.x=0,void(this.y=0);var t=e.style[S].split(" ");this.x=parseFloat(t[0]),this.y=parseFloat(t[1])};D.prototype.toString=function(){return this.x+"px "+this.y+"px"};var q=n(y,500),U={type:"canvas",format:"png",quality:1},Q=["jpeg","webp","png"];if(window.jQuery){var $=window.jQuery;$.fn.croppie=function(e){var t=typeof e;if("string"===t){var n=Array.prototype.slice.call(arguments,1),i=$(this).data("croppie");return"get"===e?i.get():"result"===e?i.result.apply(i,n):"bind"===e?i.bind.apply(i,n):this.each(function(){var t=$(this).data("croppie");if(t){var i=t[e];if(!$.isFunction(i))throw"Croppie "+e+" method not found";i.apply(t,n),"destroy"===e&&$(this).removeData("croppie")}})}return this.each(function(){var t=new j(this,e);t.$=$,$(this).data("croppie",t)})}}j.defaults={viewport:{width:100,height:100,type:"square"},boundary:{},orientationControls:{enabled:!0,leftClass:"",rightClass:""},customClass:"",showZoomer:!0,enableZoom:!0,mouseWheelZoom:!0,enableExif:!1,enforceBoundary:!0,enableOrientation:!1,update:function(){}},j.globals={translate:"translate3d"},t(j.prototype,{bind:function(e,t){return M.call(this,e,t)},get:function(){var e=W.call(this),t=e.points;return this.options.relative&&(t[0]/=this.elements.img.naturalWidth/100,t[1]/=this.elements.img.naturalHeight/100,t[2]/=this.elements.img.naturalWidth/100,t[3]/=this.elements.img.naturalHeight/100),e},result:function(e){return X.call(this,e)},refresh:function(){return k.call(this)},setZoom:function(e){m.call(this,e),i(this.elements.zoomer)},rotate:function(e){H.call(this,e)},destroy:function(){return Y.call(this)}}),exports.Croppie=window.Croppie=j,"object"==typeof module&&module.exports&&(module.exports=j)}); /* A wrapper around Croppie that also uploads the new picture to the server. Used to change the profile or group picture. */ function PictureUploader(options) { //croppie options come also here this.element = document.createElement("DIV"); this.element.className = "picture-uploader-croppie"; this.croppie = null; this.startingOptions = {}; if(options){ this.options = options; this.startingOptions.viewport = this.options.viewport; this.startingOptions.boundary = this.options.boundary; this.startingOptions.showZoomer = false; this.startingOptions.enableZoom = false; } this.acceptButton = null; this.cancelButton = null; this.uploadReadyCallback = null; this.uploadReadyContext = null; this.uploadCanceledContext = null; this.uploadCanceledCallback = null; this.changePictureCallback = null; this.changePictureContext = null; } PictureUploader.prototype.createCropper = function (imageUrl) { this.croppieContainer = document.createElement("DIV"); this.croppieContainer.className = "pictureUploader-cropper"; this.element.appendChild(this.croppieContainer); this.croppie = new Croppie(this.croppieContainer, this.startingOptions); this.croppie.elements.img.src = imageUrl ? imageUrl : this.options.startingPicture; this.croppie.elements.img.width = this.options.viewport.width; this.croppie.elements.img.height = this.options.viewport.height; this.croppie.elements.viewport.appendChild(this.croppie.elements.img); }; PictureUploader.prototype.createPicture = function (imageUrl) { this.croppieContainer = document.createElement("DIV"); this.element.appendChild(this.croppieContainer); this.picture = document.createElement("IMG"); this.picture.src = imageUrl ? imageUrl : this.options.startingPicture; this.picture.width = this.options.viewport.width; this.picture.height = this.options.viewport.height; this.croppieContainer.appendChild(this.picture); }; PictureUploader.prototype.createChangeButton = function () { var fileUploadContainer = document.createElement("DIV"); fileUploadContainer.textContent = "Bild ändern"; fileUploadContainer.className = "change-image-button selected"; var fileUploadButton = document.createElement("INPUT"); fileUploadButton.type = "file"; fileUploadButton.accept = ".jpg,.gif,.png,.jpeg"; fileUploadButton.className = "picture-upload-button"; fileUploadButton.style.cssText = "display: none; position: relative; width: 100%; z-index: 1; float: left;"; fileUploadContainer.onclick = function () { if(this.changePictureCallback && this.changePictureContext){ this.changePictureCallback.call(this.changePictureContext); } fileUploadButton.click(); }.bind(this); fileUploadButton.onchange = function (event) { this.removeCroppie(); var data = event.target.files; var uploader = new UploadCreator(); this.createAcceptAndCancelButtons(uploader, function (action) { fileUploadButton.value = null; this.removeCroppie(); if(action === "cancel"){ if(this.uploadCanceledCallback && this.uploadCanceledContext){ this.uploadCanceledCallback.call(this.uploadCanceledContext); } this.createCropper(); } }.bind(this)); this.croppie = new Croppie(this.croppieContainer, this.options); if(data.length === 0 && this.currentPicture){ this.croppie.bind({url: this.currentPicture}); } else{ uploader.readFileAsDataURL(data[0], function (fileObject) { this.currentPicture = fileObject; this.croppie.bind({url: fileObject}); }.bind(this)); } }.bind(this); this.element.insertBefore(fileUploadContainer, this.croppieContainer); this.element.insertBefore(fileUploadButton, this.croppieContainer); }; PictureUploader.prototype.createAcceptAndCancelButtons = function (uploader, onButtonPressedCallback) { this.acceptButton = document.createElement("BUTTON"); this.acceptButton.className = "pictureUploader-button ok"; this.acceptButton.textContent = "Akzeptieren"; this.acceptButton.onclick = function () { this.croppie.result("blob").then(function (blob) { uploader.createFileUpload(blob, function (fileObject) { if ( !fileObject.result ) { alertManager.inform(fileObject.message); } else { if(this.uploadReadyCallback && this.uploadReadyContext){ this.uploadReadyCallback.call(this.uploadReadyContext, fileObject, blob); } onButtonPressedCallback("accept"); } }.bind(this)); }.bind(this)); }.bind(this); this.cancelButton = document.createElement("BUTTON"); this.cancelButton.className = "pictureUploader-button cancel"; this.cancelButton.textContent = "Abbrechen"; this.cancelButton.onclick = function () { onButtonPressedCallback("cancel"); }.bind(this); this.element.appendChild(this.acceptButton); this.element.appendChild(this.cancelButton); }; PictureUploader.prototype.removeCroppie = function () { if(this.acceptButton && this.acceptButton.parentNode){ this.element.removeChild(this.acceptButton); } if(this.cancelButton && this.cancelButton.parentNode){ this.element.removeChild(this.cancelButton); } if(this.croppie){ this.croppie.destroy(); } this.croppie = null; }; PictureUploader.prototype.onUploadReady = function (context, callback) { this.uploadReadyContext = context; this.uploadReadyCallback = callback; }; PictureUploader.prototype.onChangePictureClick = function (context, callback) { this.changePictureContext = context; this.changePictureCallback = callback; }; PictureUploader.prototype.onUploadCanceled = function (context, callback) { this.uploadCanceledContext = context; this.uploadCanceledCallback = callback; }; /* A screen under profile for admins. Currently it contains a list of users that can be unbanned. */ function AdminScreen() { this.element = document.createElement("DIV"); this.searchContainer = document.createElement("DIV"); this.searchResults; this.searchInput; this.users; this.createBannedSection(); } AdminScreen.prototype.createBannedSection = function () { this.searchContainer.className = "admin-banned-container"; this.searchResults = document.createElement("DIV"); this.searchResults.style.width = "calc( 100% - 4px )"; this.searchResults.style.float = "left"; this.searchResults.style.margin = "10px 0px 30px 10px"; var title = document.createElement("DIV"); title.className = "admin-banned-title"; title.textContent = "Suche für gesperrte Nutzer:"; this.searchInput = document.createElement("INPUT"); this.searchInput.className = "admin-banned-input"; this.searchInput.onkeydown = function (event) { this.searchForUsers(event); }.bind(this); this.searchContainer.appendChild(title); this.searchContainer.appendChild(this.searchInput); this.searchContainer.appendChild(this.searchResults); this.createBannedUsersList(function () { this.element.appendChild(this.searchContainer); }.bind(this)); }; AdminScreen.prototype.createBannedUsersList = function (callback) { var bannedList = document.createElement("DIV"); var unbanButton = document.createElement("BUTTON"); unbanButton.className = "ok unban"; unbanButton.textContent = "Nutzer freischalten"; unbanButton.onclick = function () { var radios = document.getElementsByName('bannedUser'); for (var i = 0, length = radios.length; i < length; i++) { if (radios[i].checked) { var value = radios[i].value; alertManager.ask("Das wird den Nutzer '" + value + "' freischalten. Fortfahren?", function () { var id; for(var i = 0; i < this.users.length; i++){ var user = this.users[i]; if(user.name === value){ id = user.id; break; } } socketGateway.emit("unbanUser", {"userid": id}, function () { alertManager.inform("Der Nutzer wurde freigeschaltet.", function () { this.searchContainer.removeChild(bannedList); this.searchContainer.removeChild(unbanButton); this.createBannedUsersList(); }.bind(this)) }.bind(this)); }.bind(this)); break; } } }.bind(this); socketGateway.emit("getBannedUsers", {}, function (users) { this.users = users; for(var i in users){ if(users.hasOwnProperty(i)){ var user = users[i]; bannedList.appendChild(this.createBannedUserEntry(user)); } } if(callback){ callback(); } }.bind(this)); this.searchContainer.appendChild(bannedList); this.searchContainer.appendChild(unbanButton); }; AdminScreen.prototype.createBannedUserEntry = function (user) { var userEntry = document.createElement("DIV"); userEntry.className = "banned-user-entry"; var userImage = document.createElement("IMG"); userImage.style.float = "left"; userImage.src = projectDomain + user.picture; var userName = document.createElement("DIV"); userName.style.float = "left"; userName.style.marginLeft = "10px"; userName.textContent = user.name; var radioButton = document.createElement("INPUT"); radioButton.style.float = "right"; radioButton.style.marginRight = "15px"; radioButton.type = "radio"; radioButton.name = "bannedUser"; radioButton.value = user.name; userEntry.appendChild(userImage); userEntry.appendChild(userName); userEntry.appendChild(radioButton); return userEntry; }; AdminScreen.prototype.searchForUsers = function (event) { var deactivateSearch = function () { if (this.search) { this.search.clearResults(); this.search = undefined; this.searchInput.onclick = undefined; } }.bind(this); var activateSearch = function () { this.searchTerm = ""; this.search = new SearchField(); this.searchInput.onclick = function () { this.search.clearResults(); }.bind(this); }.bind(this); var isCharLetter = function (char) { var regex = /^\w|[ÀÈÌÒÙàèìòùÁÉÍÓÚÝáéíóúýÂÊÎÔÛâêîôûÃÑÕãñõÄËÏÖÜäëïöüçÇßØøÅåÆæÞþÐð]$/; var result = char.match(regex); return result && result[0] === result.input; }; var pressedKey = event.key; if (this.search && (pressedKey === " ")) { deactivateSearch(); } if(!this.search && isCharLetter(pressedKey)){ activateSearch(); } if (this.search && (isCharLetter(pressedKey) || pressedKey === "Backspace")) { var results; if (pressedKey === "Backspace") { this.searchTerm = this.searchTerm.slice(0, -1); } else { this.searchTerm += pressedKey; } if (this.searchTerm === "") { deactivateSearch(); } else if (this.searchTerm === ",") { this.search.clearResults(); } else { socketGateway.emit("searchBannedUsers", this.searchTerm, function (args) { var originalText = args["originalText"]; results = this.search.createAndAttachResults({ "originalText": args.originalText, "users": args.bannedUsers, "groups": [], "usersFilter":[] }, this.searchResults, function (args) { alertManager.ask("Das wird den Nutzer '" + args.name + "' freischalten. Fortfahren?", function () { socketGateway.emit("unbanUser", {"userid": args.id}, function () { alertManager.inform("Der Nutzer wurde freigeschaltet.", function () { }) }); }); this.searchInput.value = ""; this.searchInput.focus(); deactivateSearch(); }.bind(this)); }.bind(this)); } } }; currentHome = new Home( rootElement ); return currentHome; };