]> git.mxchange.org Git - friendica.git/blob - view/js/linkPreview.js
Merge pull request #7605 from annando/pending-2
[friendica.git] / view / js / linkPreview.js
1 // @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt Expat
2 // @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL
3 /**
4  * Copyright (c) 2014 Leonardo Cardoso (http://leocardz.com)
5  * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
6  * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
7  * 
8  * Restructured by Rabzuarus (https://friendica.kommune4.de/profile/rabuzarus)
9  * to use it in the decentralized social network Friendica (https://friendi.ca).
10  * 
11  * Version: 1.4.0
12  */
13 (function ($) {
14         $.fn.linkPreview = function (options) {
15                 var opts = jQuery.extend({}, $.fn.linkPreview.defaults, options);
16
17                 var selector = $(this).selector;
18                 selector = selector.substr(1);
19
20                 var previewTpl = '\
21                         <div id="preview_' + selector + '" class="preview {0}">\
22                                 {1}\
23                                 <input type="hidden" name="has_attachment" id="hasAttachment_' + selector + '" value="{2}" />\
24                                 <input type="hidden" name="attachment_url" id="attachmentUrl_' + selector + '" value="{3}" />\
25                                 <input type="hidden" name="attachment_type" id="attachmentType_' + selector + '" value="{4}" />\
26                         </div>';
27
28                 var attachmentTpl = '\
29                         <hr class="previewseparator">\
30                         <div id="closePreview_' + selector + '" title="Remove" class="closePreview" >\
31                                 <button type="button" class="previewActionBtn">×</button>\
32                         </div>\
33                         <div id="previewImages_' + selector + '" class="previewImages">\
34                                 <div id="previewImgBtn_' + selector + '" class="previewImgBtn">\
35                                         <button type="button" id="previewChangeImg_' + selector + '" class="buttonChangeDeactive previewActionBtn" style="display: none">\
36                                                 <i class="fa fa-exchange" aria-hidden="true"></i>\
37                                         </button>\
38                                 </div>\
39                                 <div id="previewImage_' + selector + '" class="previewImage">\
40                                 </div>\
41                                 <input type="hidden" id="photoNumber_' + selector + '" class="photoNumber" value="0" />\
42                                 <input type="hidden" name="attachment_img_src" id="attachmentImageSrc_' + selector + '" value="" />\
43                                 <input type="hidden" name="attachment_img_width" id="attachmentImageWidth_' + selector + '" value="0" />\
44                                 <input type="hidden" name="attachment_img_height" id="attachmentImageHeight_' + selector + '" value="0" />\
45                         </div>\
46                         <div id="previewContent_' + selector + '" class="previewContent">\
47                                 <h4 id="previewTitle_' + selector + '" class="previewTitle"></h4>\
48                                 <blockquote id="previewDescription_' + selector + '" class="previewDescription"></blockquote>\
49                                 <div id="hiddenDescription_' + selector + '" class="hiddenDescription"></div>\
50                                 <sup id="previewUrl_' + selector + '" class="previewUrl"></sup>\
51                         </div>\
52                         <div class="clear"></div>\
53                         <hr class="previewseparator">';
54                 var text;
55                 var urlRegex = /^(?:https?\:\/\/|\s)[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})(?:\/+[a-z0-9_.\:\;-]*)*(?:\?[\&\%\|\+a-z0-9_=,\.\:\;-]*)?(?:[\&\%\|\+&a-z0-9_=,\:\;\.-]*)(?:[\!\#\/\&\%\|\+a-z0-9_=,\:\;\.-]*)}*$/i;
56                 var binurl;
57                 var block = false;
58                 var blockTitle = false;
59                 var blockDescription = false;
60                 var cache = {};
61                 var images = "";
62                 var isExtern = false;
63                 var photoNumber = 0;
64                 var firstPosted = false;
65                 var isActive = false;
66                 var isCrawling = false;
67                 var defaultTitle = opts.defaultTitle;
68                 var defaultDescription = opts.defaultDescription;
69
70                 /**
71                  * Initialize the plugin
72                  * 
73                  * @returns {void}
74                  */
75                 var init = function() {
76                         $('#' + selector).bind({
77                                 paste: function () {
78                                         setTimeout(function () {
79                                                 crawlText();
80                                         }, 100);
81                                 },
82                                 keyup: function (e) {
83                                         // on enter, space, ctrl
84                                         if ((e.which === 13 || e.which === 32 || e.which === 17)) {
85                                                 crawlText();
86                                         }
87                                 }
88                         });
89
90                         // Check if we have already attachment bbcode in the textarea
91                         // and add it to the attachment preview.
92                         var content = $('#' + selector).val();
93                         addBBCodeToPreview(content);
94                 };
95
96                 /**
97                  * Reset some values.
98                  * 
99                  * @returns {void}
100                  */
101                 var resetPreview = function() {
102                         $('#hasAttachment_' + selector).val(0);
103                         photoNumber = 0;
104                         images = "";
105                 };
106
107                 /**
108                  * Crawl a text string if it contains an url and try
109                  * to attach it.
110                  * 
111                  * If no text is passed to crawlText() we take
112                  * the previous word before the cursor of the textarea.
113                  * 
114                  * @param {string} text (optional)
115                  * @returns {void}
116                  */
117                 var crawlText = function (text) {
118                         block = false;
119                         images = '';
120                         isExtern = false;
121
122                         // If no text is passed to crawlText() we 
123                         // take the previous word before the cursor.
124                         if (typeof text === 'undefined') {
125                                 text = getPrevWord(selector);
126                         } else {
127                                 isExtern = true;
128                         }
129
130                         // Don't procces the textarea input if we have already
131                         // an attachment preview.
132                         if (!isExtern && isActive) {
133                                 return;
134                         }
135
136                         if (trim(text) !== "" && block === false && urlRegex.test(text)) {
137                                 binurl = bin2hex(text);
138                                 block = true;
139
140                                 isCrawling = true;
141                                 $('#profile-rotator').show();
142
143                                 if (binurl in cache) {
144                                         isCrawling = false;
145                                         processContentData(cache[binurl]);
146                                 } else {
147                                         getContentData(binurl, processContentData);
148                                 }
149                         }
150                 };
151
152                 /**
153                  * Process the attachment data according to
154                  * its content type (image, audio, video, attachment)
155                  * 
156                  * @param {object} result
157                  * @returns {void}
158                  */
159                 var processContentData = function(result) {
160                         if (result.contentType === 'image') {
161                                 insertImage(result.data);
162                         }
163                         if (result.contentType === 'audio') {
164                                 insertAudio(result.data);
165                         }
166                         if (result.contentType === 'video') {
167                                 insertVideo(result.data);
168                         }
169                         if (result.contentType === 'attachment') {
170                                 insertAttachment(result.data);
171                         }
172                         $('#profile-rotator').hide();
173                 };
174
175                 /**
176                  * Fetch the content of link which should be attached.
177                  * 
178                  * @param {string} binurl Link which should be attached as hexadecimal string.
179                  * @param {type} callback
180                  * @returns {void}
181                  */
182                 var getContentData = function(binurl, callback) {
183                         $.get('parse_url?binurl='+ binurl + '&format=json', function (answer) {
184                                 obj = sanitizeInputData(answer);
185
186                                 // Put the data into a cache
187                                 cache[binurl] = obj;
188
189                                 callback(obj);
190
191                                 isCrawling = false;
192                         });
193                 };
194
195                 /*
196                  * Add a [img] bbtag with the image url to the jot editor.
197                  * 
198                  * @param {type} data
199                  * @returns {void}
200                  */
201                 var insertImage = function(data) {
202                         if (!isExtern) {
203                                 return;
204                         }
205                         var bbcode = '\n[img]' + data.url + '[/img]\n';
206                         addeditortext(bbcode);
207                 };
208
209                 /*
210                  * Add a [audio] bbtag with the audio url to the jot editor.
211                  * 
212                  * @param {type} data
213                  * @returns {void}
214                  */
215                 var insertAudio = function(data) {
216                         if (!isExtern) {
217                                 return;
218                         }
219                         var bbcode = '\n[audio]' + data.url + '[/audio]\n';
220                         addeditortext(bbcode);
221                 };
222
223                 /*
224                  * Add a [video] bbtag with the video url to the jot editor.
225                  * 
226                  * @param {type} data
227                  * @returns {void}
228                  */
229                 var insertVideo = function(data) {
230                         if (!isExtern) {
231                                 return;
232                         }
233                         var bbcode = '\n[video]' + data.url + '[/video]\n';
234                         addeditortext(bbcode);
235                 };
236
237                 /**
238                  * Proccess all attachment data and show up a html
239                  * attachment preview.
240                  * 
241                  * @param {obj} data Attachment data.
242                  * @returns {void}
243                  */
244                 var insertAttachment = function(data) {
245                         // If we have already a preview, leaver here.
246                         // Note: if we finish the Preview of other media content type,
247                         // we can move this condition to the beggining of crawlText();
248                         if (isActive) {
249                                 $('#profile-rotator').hide();
250                                 return;
251                         }
252
253                         if (data.type !== 'link' && data.type !== 'video' && data.type !== 'photo' || data.url === data.title) {
254                                 $('#profile-rotator').hide();
255                                 return;
256                         }
257
258                         $('#photoNumber_' + selector).val(0);
259                         resetPreview();
260
261                         processAttachmentTpl(data, 'type-' + data.type);
262                         addTitleDescription(data);
263                         addHostToAttachment(data.url);
264                         addImagesToAttachment(data.images);
265
266                         processEventListener();
267                         $('#profile-rotator').hide();
268                 };
269
270                 /**
271                  * Construct the attachment html from the attachment template and
272                  * add it to the DOM.
273                  * 
274                  * @param {object} data Attachment data.
275                  * @returns {void}
276                  */
277                 var processAttachmentTpl = function(data) {
278                         // Load and add the template if it isn't allready loaded.
279                         if ($('#preview_' + selector).length === 0) {
280                                 var tpl = previewTpl.format(
281                                         'type-' + data.type,
282                                         attachmentTpl,
283                                         1,
284                                         bin2hex(data.url),
285                                         data.type
286                                 );
287                                 $('#' + selector).after(tpl);
288                         }
289
290                         isActive = true;
291                 };
292
293                 /**
294                  * Add the attachment title and the description
295                  * to the attachment preview.
296                  * 
297                  * @param {object} data Attachment data.
298                  * @returns {void}
299                  */
300                 var addTitleDescription = function(data) {
301                         var description = data.text;
302
303                         if (description === '') {
304                                 description = defaultDescription;
305                         }
306
307                         $('#previewTitle_' + selector).html("\
308                                 <span id='previewSpanTitle_" + selector + "' class='previewSpanTitle' >" + escapeHTML(data.title) + "</span>\
309                                 <input type='text' name='attachment_title' value='" + escapeHTML(data.title) + "' id='previewInputTitle_" + selector + "' class='previewInputTitle inputPreview' style='display: none;'/>"
310                         );
311
312                         $('#previewDescription_' + selector).html("\
313                                 <span id='previewSpanDescription_" + selector + "' class='previewSpanDescription' >" + escapeHTML(description) + "</span>\n\
314                                 <textarea id='previewInputDescription_" + selector + "' name='attachment_text' class='previewInputDescription' style='display: none;' class='inputPreview' >" + escapeHTML(data.text) + "</textarea>"
315                         );
316                 };
317
318                 /**
319                  * Add the host to the attachment preview.
320                  * 
321                  * @param {string} url The url of the link attachment.
322                  * @returns {void}
323                  */
324                 var addHostToAttachment = function(url) {
325                         if (url) {
326                                 var regexpr = "(https?://)([^:^/]*)(:\\d*)?(.*)?";
327                                 var regResult = url.match(regexpr);
328                                 var urlHost = regResult[1] + regResult[2];
329                                 $('#previewUrl_' + selector).html("<a href='" + url + "'>" + urlHost + "</a>");
330                         }
331                 };
332
333                 /**
334                  * Add preview images to the attachment.
335                  * 
336                  * @param {array} images
337                  * 
338                  * @returns {void}
339                  */
340                 var addImagesToAttachment = function(images) {
341                         var imageClass = 'attachment-preview';
342         
343                         if (Array.isArray(images)) {
344                                 $('#previewImages_' + selector).show();
345                                 $('#attachmentImageSrc_' + selector).val(bin2hex(images[photoNumber].src));
346                                 $('#attachmentImageWidth_' + selector).val(images[photoNumber].width);
347                                 $('#attachmentImageHeight_' + selector).val(images[photoNumber].height);
348                         } else {
349                                 $('#previewImages_' + selector).hide();
350                         }
351
352                         images.length = parseInt(images.length);
353                         var appendImage = "";
354
355                         for (i = 0; i < images.length; i++) {
356                                 // For small preview images we use a smaller attachment format.
357                                 ///@todo here we need to add a check for !Config::get('system', 'always_show_preview').
358                                 if (images[i].width >= 500 && images[i].width >= images[i].height) {
359                                                 imageClass = 'attachment-image';
360                                 }
361
362                                 if (i === 0) {
363                                         appendImage += "<img id='imagePreview_" + selector + "_" + i + "' src='" + images[i].src + "' class='" + imageClass + "' ></img>";
364                                 } else {
365                                         appendImage += "<img id='imagePreview_" + selector + "_" + i + "' src='" + images[i].src + "' class='" + imageClass + "' style='display: none;'></img>";
366                                 }
367                         }
368
369                         $('#previewImage_' + selector).html(appendImage + "<div id='whiteImage' style='color: transparent; display:none;'>...</div>");
370
371                         // More than just one image.
372                         if (images.length > 1) {
373                                 // Enable the the button to change the preview pictures.
374                                 $('#previewChangeImg_' + selector).show();
375
376                                 if (firstPosted === false) {
377                                         firstPosted = true;
378
379                                         $('#previewChangeImg_' + selector).unbind('click').click(function (e) {
380                                                 e.stopPropagation();
381                                                 if (images.length > 1) {
382                                                         $('#imagePreview_' + selector + '_' + photoNumber).css({
383                                                                 'display': 'none'
384                                                         });
385                                                         photoNumber += 1;
386
387                                                         // If have reached the last image, begin with the first image.
388                                                         if (photoNumber === images.length) {
389                                                                 photoNumber = 0;
390                                                         }
391
392                                                         $('#imagePreview_' + selector + '_' + photoNumber).css({
393                                                                 'display': 'block'
394                                                         });
395                                                         $('#photoNumber_' + selector).val(photoNumber);
396                                                         $('#attachmentImageSrc_' + selector).val(bin2hex(images[photoNumber].src));
397                                                         $('#attachmentImageWidth_' + selector).val(images[photoNumber].width);
398                                                         $('#attachmentImageHeight_' + selector).val(images[photoNumber].height);
399                                                 }
400                                         });
401                                 }
402                         }
403                 };
404
405                 /**
406                  * Add event listener to control the attachment preview.
407                  * 
408                  * @returns {void}
409                  */
410                 var processEventListener = function() {
411                         $('#previewSpanTitle_' + selector).unbind('click').click(function (e) {
412                                 e.stopPropagation();
413                                 if (blockTitle === false) {
414                                         blockTitle = true;
415                                         $('#previewSpanTitle_' + selector).hide();
416                                         $('#previewInputTitle_' + selector).show();
417                                         $('#previewInputTitle_' + selector).val($('#previewInputTitle_' + selector).val());
418                                         $('#previewInputTitle_' + selector).focus().select();
419                                 }
420                         });
421
422                         $('#previewInputTitle_' + selector).blur(function () {
423                                 blockTitle = false;
424                                 $('#previewSpanTitle_' + selector).html($('#previewInputTitle_' + selector).val());
425                                 $('#previewSpanTitle_' + selector).show();
426                                 $('#previewInputTitle_' + selector).hide();
427                         });
428
429                         $('#previewInputTitle_' + selector).keypress(function (e) {
430                                 if (e.which === 13) {
431                                         blockTitle = false;
432                                         $('#previewSpanTitle_' + selector).html($('#previewInputTitle_' + selector).val());
433                                         $('#previewSpanTitle_' + selector).show();
434                                         $('#previewInputTitle_' + selector).hide();
435                                 }
436                         });
437
438                         $('#previewSpanDescription_' + selector).unbind('click').click(function (e) {
439                                 e.stopPropagation();
440                                 if (blockDescription === false) {
441                                         blockDescription = true;
442                                         $('#previewSpanDescription_' + selector).hide();
443                                         $('#previewInputDescription_' + selector).show();
444                                         $('#previewInputDescription_' + selector).val($('#previewInputDescription_' + selector).val());
445                                         $('#previewInputDescription_' + selector).focus().select();
446                                 }
447                         });
448
449                         $('#previewInputDescription_' + selector).blur(function () {
450                                 blockDescription = false;
451                                 $('#previewSpanDescription_' + selector).html($('#previewInputDescription_' + selector).val());
452                                 $('#previewSpanDescription_' + selector).show();
453                                 $('#previewInputDescription_' + selector).hide();
454                         });
455
456                         $('#previewInputDescription_' + selector).keypress(function (e) {
457                                 if (e.which === 13) {
458                                         blockDescription = false;
459                                         $('#previewSpanDescription_' + selector).html($('#previewInputDescription_' + selector).val());
460                                         $('#previewSpanDescription_' + selector).show();
461                                         $('#previewInputDescription_' + selector).hide();
462                                 }
463                         });
464
465                         $('#previewSpanTitle_' + selector).mouseover(function () {
466                                 $('#previewSpanTitle_' + selector).css({
467                                         "background-color": "#ff9"
468                                 });
469                         });
470
471                         $('#previewSpanTitle_' + selector).mouseout(function () {
472                                 $('#previewSpanTitle_' + selector).css({
473                                         "background-color": "transparent"
474                                 });
475                         });
476
477                         $('#previewSpanDescription_' + selector).mouseover(function () {
478                                 $('#previewSpanDescription_' + selector).css({
479                                         "background-color": "#ff9"
480                                 });
481                         });
482
483                         $('#previewSpanDescription_' + selector).mouseout(function () {
484                                 $('#previewSpanDescription_' + selector).css({
485                                         "background-color": "transparent"
486                                 });
487                         });
488
489                         $('#closePreview_' + selector).unbind('click').click(function (e) {
490                                 e.stopPropagation();
491                                 block = false;
492                                 images = '';
493                                 isActive = false;
494                                 firstPosted = false;
495                                 $('#preview_' + selector).fadeOut("fast", function () {
496                                         $('#preview_' + selector).remove();
497                                         $('#profile-rotator').hide();
498                                         $('#' + selector).focus();
499                                 });
500
501                         });
502                 };
503
504                 /**
505                  * Convert attachmant bbcode into an array.
506                  * 
507                  * @param {string} content Text content with the attachment bbcode.
508                  * @returns {object || null}
509                  */
510                 var getAttachmentData = function(content) {
511                         var data = {};
512
513                         var match = content.match(/([\s\S]*)\[attachment([\s\S]*?)\]([\s\S]*?)\[\/attachment\]([\s\S]*)/im);
514                         if (match === null || match.length < 5) {
515                                 return null;
516                         }
517
518                         var attributes = match[2];
519                         data.text = trim(match[1]);
520
521                         var type = '';
522                         var matches = attributes.match(/type='([\s\S]*?)'/im);
523                         if (matches !== null && typeof matches[1] !== 'undefined') {
524                                 type = matches[1].toLowerCase();
525                         }
526
527                         matches = attributes.match(/type="([\s\S]*?)"/im);
528                         if (matches !== null && typeof matches[1] !== 'undefined') {
529                                 type = matches[1].toLowerCase();
530                         }
531
532                         if (type === '') {
533                                 return null;
534                         }
535
536                         if (
537                                 type !== 'link'
538                                 && type !== 'audio'
539                                 && type !== 'photo'
540                                 && type !== 'video')
541                         {
542                                 return null;
543                         }
544
545                         if (type !== '') {
546                                 data.type = type;
547                         }
548
549                         var url = '';
550
551                         matches = attributes.match(/url='([\s\S]*?)'/im);
552                         if (matches !== null && typeof matches[1] !== 'undefined') {
553                                 url = matches[1].toLowerCase();
554                         }
555
556                         matches = attributes.match(/url="([\s\S]*?)"/im);
557                         if (matches !== null && typeof matches[1] !== 'undefined') {
558                                 url = matches[1].toLowerCase();
559                         }
560
561                         if(url !== '') {
562                                 data.url = escapeHTML(url);
563                         }
564
565                         var title = '';
566
567                         matches = attributes.match(/title='([\s\S]*?)'/im);
568                         if (matches !== null && typeof matches[1] !== 'undefined') {
569                                 title = matches[1].toLowerCase();
570                         }
571
572                         matches = attributes.match(/title="([\s\S]*?)"/im);
573                         if (matches !== null && typeof matches[1] !== 'undefined') {
574                                 title = matches[1].toLowerCase();
575                         }
576
577                         if (title !== '') {
578                                 data.title = escapeHTML(title);
579                         }
580
581                         var image = '';
582
583                         matches = attributes.match(/image='([\s\S]*?)'/im);
584                         if (matches !== null && typeof matches[1] !== 'undefined') {
585                                 image = matches[1].toLowerCase();
586                         }
587
588                         matches = attributes.match(/image="([\s\S]*?)"/im);
589                         if (matches !== null && typeof matches[1] !== 'undefined') {
590                                 image = matches[1].toLowerCase();
591                         }
592
593                         if (image !== '') {
594                                 data.image = escapeHTML(image);
595                         }
596
597                         var preview = '';
598
599                         matches = attributes.match(/preview='([\s\S]*?)'/im);
600                         if (matches !== null && typeof matches[1] !== 'undefined') {
601                                 preview = matches[1].toLowerCase();
602                         }
603
604                         matches = attributes.match(/preview="([\s\S]*?)"/im);
605                         if (matches !== null && typeof matches[1] !== 'undefined') {
606                                 preview = matches[1].toLowerCase();
607                         }
608
609                         if (preview !== '') {
610                                 data.preview = escapeHTML(preview);
611                         }
612
613                         data.text = trim(match[3]);
614                         data.after = trim(match[4]);
615
616                         return data;
617                 };
618
619                 /**
620                  * Process txt content and if it contains attachment bbcode
621                  * add it to the attachment preview .
622                  * 
623                  * @param {string} content
624                  * @returns {void}
625                  */
626                 var addBBCodeToPreview =function(content) {
627                         var attachmentData = getAttachmentData(content);
628                         if (attachmentData) {
629                                 reAddAttachment(attachmentData);
630                                 // Remove the attachment bbcode from the textarea.
631                                 var content = content.replace(/\[attachment[\s\S]*\[\/attachment]/im, '');
632                                 $('#' + selector).val(content);
633                                 $('#' + selector).focus();
634                         }
635                 };
636
637                 /**
638                  * Add an Attachment with data from an old bbcode
639                  * generated attachment.
640                  * 
641                  * @param {object} json The attachment data.
642                  * @returns {void}
643                  */
644                 var reAddAttachment = function(json) {
645                         if (isActive) {
646                                 $('#profile-rotator').hide();
647                                 return;
648                         }
649
650                         if (json.type !== 'link' && json.type !== 'video' && json.type !== 'photo' || json.url === json.title) {
651                                 $('#profile-rotator').hide();
652                                 return;
653                         }
654
655                         var obj = {data: json};
656                         obj = sanitizeInputData(obj);
657
658                         var data = obj.data;
659
660                         resetPreview();
661
662                         processAttachmentTpl(data);
663                         addTitleDescription(data);
664                         addHostToAttachment(data.url);
665
666                         // Since we don't have an array of image data,
667                         // we need to add the preview images in a different way
668                         // than in function addImagesToAttachment().
669                         var imageClass = 'attachment-preview';
670                         var image = '';
671
672                         if (data.image !== '') {
673                                 imageClass = 'attachment-image';
674                                 image = data.image;
675                         } else {
676                                 image = data.preview;
677                         }
678
679                         if (image !== '') {
680                                 var appendImage = "<img id='imagePreview_" + selector + "' src='" + image + "' class='" + imageClass + "' ></img>"
681                                 $('#previewImage_' + selector).html(appendImage);
682                                 $('#attachmentImageSrc_' + selector).val(bin2hex(image));
683
684                                 // We need to add the image widht and height when it is 
685                                 // loaded.
686                                 $('<img/>' ,{
687                                         load : function(){
688                                                 $('#attachmentImageWidth_' + selector).val(this.width);
689                                                 $('#attachmentImageHeight_' + selector).val(this.height);
690                                         },
691                                         src  : image
692                                 });
693                         }
694
695                         processEventListener();
696                         $('#profile-rotator').hide();
697                 };
698
699                 /**
700                  * Add missing default properties to the input data object.
701                  * 
702                  * @param {object} obj Input data.
703                  * @returns {object}
704                  */
705                 var sanitizeInputData = function(obj) {
706                         if (typeof obj.contentType === 'undefined'
707                                 || obj.contentType === null)
708                         {
709                                 obj.contentType = "";
710                         }
711                         if (typeof obj.data.url === 'undefined'
712                                 || obj.data.url === null)
713                         {
714                                 obj.data.url = "";
715                         }
716                         if (typeof obj.data.title === 'undefined'
717                                 || obj.data.title === null
718                                 || obj.data.title === "")
719                         {
720                                 obj.data.title = defaultTitle;
721                         }
722                         if (typeof obj.data.text === 'undefined'
723                                 || obj.data.text === null
724                                 || obj.data.text === "")
725                         {
726                                 obj.data.text = "";
727                         }
728                         if (typeof obj.data.images === 'undefined'
729                                 || obj.data.images === null)
730                         {
731                                 obj.data.images = "";
732                         }
733
734                         if (typeof obj.data.image === 'undefined'
735                                 || obj.data.image === null)
736                         {
737                                 obj.data.image = "";
738                         }
739
740                         if (typeof obj.data.preview === 'undefined'
741                                 || obj.data.preview === null)
742                         {
743                                 obj.data.preview = "";
744                         }
745
746                         return obj;
747                 };
748
749                 /**
750                  * Destroy the plugin.
751                  * 
752                  * @returns {void}
753                  */
754                 var destroy = function() {
755                         $('#' + selector).unbind();
756                         $('#preview_' + selector).remove();
757                         binurl;
758                         block = false;
759                         blockTitle = false;
760                         blockDescription = false;
761                         cache = {};
762                         images = "";
763                         isExtern = false;
764                         photoNumber = 0;
765                         firstPosted = false;
766                         isActive = false;
767                         isCrawling = false;
768                         selector = "";
769                 };
770
771                 var trim = function(str) {
772                         return str.replace(/^\s+|\s+$/g, "");
773                 };
774                 var escapeHTML = function(unsafe_str) {
775                         return unsafe_str
776                                 .replace(/&/g, '&amp;')
777                                 .replace(/</g, '&lt;')
778                                 .replace(/>/g, '&gt;')
779                                 .replace(/\"/g, '&quot;')
780                                 .replace(/\[/g, '&#91;')
781                                 .replace(/\]/g, '&#93;')
782                                 .replace(/\'/g, '&#39;'); // '&apos;' is not valid HTML 4
783                 };
784
785                 // Initialize LinkPreview 
786                 init();
787
788                 return {
789                         // make crawlText() accessable from the outside.
790                         crawlText: function(text) {
791                                 crawlText(text);
792                         },
793                         addBBCodeToPreview: function(content) {
794                                 addBBCodeToPreview(content);
795                         },
796                         destroy: function() {
797                                 destroy();
798                         }
799                 };
800         };
801
802         $.fn.linkPreview.defaults = {
803                 defaultDescription: "Enter a description",
804                 defaultTitle: "Enter a title"
805         };
806
807         /**
808         * Get in a textarea the previous word before the cursor.
809         * 
810         * @param {object} text Textarea elemet.
811         * @param {integer} caretPos Cursor position.
812         * 
813         * @returns {string} Previous word.
814         */
815         function returnWord(text, caretPos) {
816                 var index = text.indexOf(caretPos);
817                 var preText = text.substring(0, caretPos);
818                 // If the last charachter is a space or enter remove it
819                 // We need this in friendica for the url  preview.
820                 var lastChar = preText.slice(-1)
821                 if ( lastChar === " "
822                         || lastChar === "\n"
823                         || lastChar === "\r"
824                         )
825                 {
826                         preText = preText.substring(0, preText.length -1);
827                 }
828
829                 // Replace new line with space.
830                 preText = preText.replace(/\n/g, " ");
831
832                 if (preText.indexOf(" ") > 0) {
833                         var words = preText.split(" ");
834                         return words[words.length - 1]; //return last word
835                 }
836                 else {
837                         return preText;
838                 }
839         }
840
841         /**
842          * Get in a textarea the previous word before the cursor.
843          * 
844          * @param {string} id The ID of a textarea element.
845          * @returns {sting|null} Previous word or null if no word is available.
846          */
847         function getPrevWord(id) {
848                 var text = document.getElementById(id);
849                 var caretPos = getCaretPosition(text);
850                 var word = returnWord(text.value, caretPos);
851                 if (word != null) {
852                         return word
853                 }
854
855         }
856
857         /**
858          * Get the cursor posiotion in an text element.
859          * 
860          * @param {object} ctrl Textarea elemet.
861          * @returns {integer} Position of the cursor.
862          */
863         function getCaretPosition(ctrl) {
864                 var CaretPos = 0;   // IE Support
865                 if (document.selection) {
866                         ctrl.focus();
867                         var Sel = document.selection.createRange();
868                         Sel.moveStart('character', -ctrl.value.length);
869                         CaretPos = Sel.text.length;
870                 }
871                 // Firefox support
872                 else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
873                         CaretPos = ctrl.selectionStart;
874                 }
875                 return (CaretPos);
876         }
877 })(jQuery);
878
879 // @license-end