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