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