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