share-annotator.js 36.7 KB
Newer Older
daniel cebrian committed
1
/* 
2
Share Annotation Plugin v1.1 (https://github.com/danielcebrian/share-annotator)
3
Copyright (C) 2014 Daniel Cebrian Robles
daniel cebrian committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
License: https://github.com/danielcebrian/share-annotator/blob/master/License.rst

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
var _ref,
  __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  __hasProp = {}.hasOwnProperty,
  __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

Annotator.Plugin.Share = (function(_super) {
26 27 28 29 30 31
    __extends(Share, _super);
    
    // Default Share configuration
    Share.prototype.options = {
        shareIn: ['facebook', 'twitter', 'email', 'google'],
        getUrl: {
32
            'facebook': function(title, link, noteText) {
33 34
                return 'https://www.facebook.com/sharer/sharer.php?s=100&p[url]=' + link + '&p[title]=' + encodeURIComponent('Open Video Annotation') + '&p[summary]=' + noteText;
            },
35
            'twitter': function(title, link, noteText) {
36 37
                return 'https://twitter.com/intent/tweet?original_referer=' + link + '&source=tweetbutton&url=' + link + "&via=OpenVideoAnnotation&text=" + encodeURIComponent('I want to share the following Open Video Annotation: ');
            },
38
            'google': function(title, link, noteText) {
39 40 41 42 43 44 45 46
                return 'https://plus.google.com/share?url=' + link;
            },
            'email': function(title, link, noteText){
                return 'mailto:?subject=' + title + '&body=' + link;
            }
        },
        baseUrl: '', // baseUrl = the base url for all the shared annotations
    };
daniel cebrian committed
47

48
    function Share(element, options) {
49 50 51
        if (typeof options !== 'undefined') {
            this.options.shareIn = typeof options.shareIn !== 'undefined' ? options.shareIn : this.options.shareIn;
        }
52 53 54 55 56 57
        this.buildHTMLShareButton = __bind(this.buildHTMLShareButton, this);
        this.runningAPI = __bind(this.runningAPI, this);
        this.updateViewer = __bind(this.updateViewer, this);
        _ref = Share.__super__.constructor.apply(this, arguments);
        return _ref;
    }
daniel cebrian committed
58

59
    Share.prototype.field = null;
daniel cebrian committed
60

61
    Share.prototype.input = null;
daniel cebrian committed
62

63 64 65 66 67 68 69 70 71 72
    Share.prototype.pluginInit = function() {
        // Check that annotator is working
        if (!Annotator.supported()) {
            return;
        }
        
        // -- Editor
        this.field = this.annotator.editor.addField({
            type: 'input', // options (textarea, input, select, checkbox)
        });
daniel cebrian committed
73

74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
        // Modify the element created with annotator to be an invisible span
        var newfield = Annotator.$('<li class="annotator-item">' + this.buildHTMLShareButton('Share without saving:') + '</li>');
        Annotator.$(this.field).replaceWith(newfield);
        this.field=newfield[0];
        // Create the actions for the buttons
        this.buttonsActions(this.field, 2, this.options.baseUrl); // 2 is the method of the API that will be for share without saving
        
        // Init the API plugin
        var APIoptions = this.initAPI();
        
        this.runAPI(APIoptions);
        
        // -- Viewer
        var newview = this.annotator.viewer.addField({
            load: this.updateViewer,
        });
daniel cebrian committed
90

91 92 93 94 95 96
        return this.input = $(this.field).find(':input');
    };
    
    // Share button HTML
    Share.prototype.buildHTMLShareButton = function(title, id) {
        var title = title || '';
97 98
        var id = typeof id !== 'undefined' ? 'annotationId="' + id + '"' : '';
        var titleText = title !== '' ? '<div class="share-text-annotator">' + title + '</div>' : '';
99 100 101
        var shareButton = '<div class="share-button-annotator share-button" ' + id + '></div>';
        var popup = '<div class="share-popup-overlay-bg" style="z-index:30000000000"><div class="share-popup"><div class="share-popup-items"></div><div class="close-btn">Close</div></div></div>';
        // checks to make sure that no popup overlay already exists (though hidden) and creates a new one if it does not exist
102
        if ($('.share-popup-overlay-bg').length === 0) {
103
            $('.annotator-wrapper').append(popup);
104
        }
105 106 107 108 109 110
        return '<div class="share-container-annotator">' + titleText + shareButton + '</div>';
    }
    
    // template for the design of the Share Plugin
    Share.prototype.buildHTMLPopup = function(title) {
        var buttons = '';
111
        if (typeof this.options.shareIn !== 'undefined'){
112 113 114 115
            this.options.shareIn.forEach(function(item) { 
                buttons += '<div class="share-' + item + '-annotator share-button">' + item.charAt(0).toUpperCase() + item.slice(1) + '</div>';
            });
        }
116
        this.uri = (typeof this.uri !== 'undefined') ? this.uri : '';
117 118 119 120 121 122 123 124
        var title = '<div class="share-popup-title">' + title.replace(":", "") + '</div>';
        var copy = '<div class="share-popup-copy">Copy and Share:</div>';
        var uri = '<input type="text" class="share-popup-uri" onclick="javascript:this.select();" readonly="true" value="' + this.uri + '">';
        var popup = title + buttons + copy + uri;
        return popup;
    }
    
    // Create the actions for the buttons
125
    Share.prototype.buttonsActions = function(field, method, url) {
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
        var share = this;
        
        //  hide popup when user clicks on close button
        $('.close-btn').click(function() {
            $('.share-popup-overlay-bg').hide();
        });
        //  hides the popup if user clicks anywhere outside the container
        $('.share-popup-overlay-bg').click(function() {
            $('.share-popup-overlay-bg').hide();
        });
        //  prevents the overlay from closing if user clicks inside the popup overlay
        $('.share-popup').click(function() {
            return false;
        });
        //  Share button
        $(field).find('.share-button-annotator.share-button').click(function(event) {
            event.preventDefault(); //  disable normal link function so that it doesn't refresh the page
143 144 145
            var _field = this;
            var ovaId = $(this).attr('annotationId');
            var title = method === 1 ? 'Share' : 'Share without saving';
146 147
            
            //  share.uri will be useful for buildHTMLPopup functions
148
            share.uri = share.createAPIURL(method, ovaId, url); 
149 150 151 152 153 154 155 156
            
            // display your popup
            $('.share-popup-overlay-bg').show(); 
            
            // build buttons
            $('.share-popup-items').html(share.buildHTMLPopup(title)); 
            
            // buttons actions
157
            if (typeof share.options.shareIn !== 'undefined') {
158 159
                share.options.shareIn.forEach(function(item) {
                    $('.share-' + item + '-annotator.share-button').click(function() {
160
                        var url = share.createAPIURL(method, ovaId, url);
161 162 163 164
                        var title = "Sharing a annotation with Open Video Annotation";
                        var link = encodeURIComponent(url);
                        var noteText = share.getSource('ovaText');
                        var finalUrl = '';
165
                        if (method === 1) {
166 167 168 169
                            var viewer = share.annotator.viewer;
                            var textarea = $(viewer.element).find('div:first').html();
                            noteText = encodeURIComponent(textarea);
                        }
170 171
                        finalUrl = typeof share.options.getUrl[item] !== 'undefined' ? share.options.getUrl[item](title, link, noteText) : '';
                        if (typeof share.options.getUrl[item] !== 'undefined') {
172
                            window.open(finalUrl);
173
                        }
174 175 176 177 178 179 180
                    }); 
                });
            }
        });
    };
    
    
181
    Share.prototype.createAPIURL = function(method, ovaId, url) {
182 183 184
        var annotator = this.annotator;
        var editor = annotator.editor;
        var method = method || 1;
185
        var url = url || window.location.href;
186
        
187
        url += (url.indexOf('?') >= 0) ? '&' : '?';
188
            
189
        if (method === 1) {
190
            var ovaId = (typeof ovaId !== 'undefined') ? ovaId : '';
191
            url += 'ovaId=' + ovaId;
192 193 194 195 196 197 198 199 200
        } else if (method === 2) {
            var ovaText = this.getSource('ovaText') || " ";
            url += 'ovaText=' + ovaText;
            if (typeof editor.VideoJS !== 'undefined' && editor.VideoJS !== -1) {  // Video Annotation
                var ovaStart = this.getSource('ovaStart') || " ";
                var ovaEnd = this.getSource('ovaEnd') || " ";
                var ovaContainer = this.getSource('ovaContainer') || " ";
                var ovaSrc = this.getSource('ovaSrc') || " ";
                url += '&ovaStart=' + ovaStart
201 202 203
                    + '&ovaEnd=' + ovaEnd 
                    + '&ovaContainer=' + ovaContainer
                    + '&ovaSrc=' + ovaSrc;
204 205 206 207 208 209 210 211 212 213 214
            } else if (typeof editor.OpenSeaDragon !== 'undefined' && editor.OpenSeaDragon !== -1) {  // Image Annotation
                var ovaLeft = this.getSource('ovaLeft') || " ";
                var ovaTop = this.getSource('ovaTop') || " ";
                var ovaWidth = this.getSource('ovaWidth') || " ";
                var ovaHeight = this.getSource('ovaHeight') || " ";
                var ovaLeftZoom = this.getSource('ovaLeftZoom') || " ";
                var ovaTopZoom = this.getSource('ovaTopZoom') || " ";
                var ovaWidthZoom = this.getSource('ovaWidthZoom') || " ";
                var ovaHeightZoom = this.getSource('ovaHeightZoom') || " ";
                var ovaContainer = this.getSource('ovaContainer') || " ";
                var ovaSrc = this.getSource('ovaSrc') || " ";
215 216 217 218 219 220 221 222 223 224
                url += '&ovaLeft=' + ovaLeft
                    + '&ovaTop=' + ovaTop
                    + '&ovaWidth=' + ovaWidth
                    + '&ovaHeight=' + ovaHeight
                    + '&ovaLeftZoom=' + ovaLeftZoom
                    + '&ovaTopZoom=' + ovaTopZoom
                    + '&ovaWidthZoom=' + ovaWidthZoom
                    + '&ovaHeightZoom=' + ovaHeightZoom 
                    + '&ovaContainer=' + ovaContainer
                    + '&ovaSrc=' + ovaSrc;
225 226 227 228 229
            } else {  // Text Annotation
                var ovaStart = this.getSource('ovaStart') || " ";
                var ovaEnd = this.getSource('ovaEnd') || " ";
                var ovastartOffset = this.getSource('ovastartOffset') || " ";
                var ovaendOffset = this.getSource('ovaendOffset') || " ";
230 231 232 233
                url += '&ovaStart=' + ovaStart
                    + '&ovaEnd=' + ovaEnd
                    + '&ovastartOffset=' + ovastartOffset
                    + '&ovaendOffset=' + ovaendOffset;
234 235 236 237 238 239 240
            }
        }
        return url;
    };
    
    Share.prototype.getSource = function(source) {
        var source = source || '';
241 242 243
        if (source === 'ovaId') { // method 1
            source = this.annotation.id;
        } else { // method 2
244
            var annotator = this.annotator;
245
            var editor = annotator.editor;
246
            var textarea = $(editor.element).find('textarea')[0];
daniel cebrian committed
247

248
            if (source === 'ovaText') {
249
                source = textarea.value;
250
            }
251

252 253
            if (typeof editor.VideoJS !== 'undefined' && editor.VideoJS !== -1) {  // Video Annotation
                if (source === 'ovaContainer') {
254
                    source = editor.VideoJS;
255 256
                }
                else if (source === 'ovaSrc') {
257
                    source = annotator.mplayer[editor.VideoJS].tech.options_.source.src;
258
                } else if (source === 'ovaStart') {
259
                    source = annotator.mplayer[editor.VideoJS].rangeslider.getValues().start;
260
                } else if (source === 'ovaEnd') {
261
                    source = annotator.mplayer[editor.VideoJS].rangeslider.getValues().end;
262 263
                }
            } else if (typeof editor.OpenSeaDragon !== 'undefined' && editor.OpenSeaDragon !== -1) {  // Image Annotation
264
                var annotation = editor.annotation;
265
                if (source === 'ovaLeft') {
266
                    source = annotator.osda.rectPosition ? annotator.osda.rectPosition.left : annotation.rangePosition.left;
267
                } else if (source === 'ovaTop') {
268
                    source = annotator.osda.rectPosition ? annotator.osda.rectPosition.top : annotation.rangePosition.top;
269
                } else if (source === 'ovaWidth') {
270
                    source = annotator.osda.rectPosition ? annotator.osda.rectPosition.width : annotation.rangePosition.width;
271
                } else if (source ==='ovaHeight') {
272
                    source = annotator.osda.rectPosition ? annotator.osda.rectPosition.height : annotation.rangePosition.height;
273
                } else if (source === 'ovaLeftZoom') {
274
                    source = annotator.osda.viewer.drawer.viewport.getBounds().x;
275
                } else if (source === 'ovaTopZoom') {
276
                    source = annotator.osda.viewer.drawer.viewport.getBounds().y;
277
                } else if (source === 'ovaWidthZoom') {
278
                    source = annotator.osda.viewer.drawer.viewport.getBounds().width;
279
                } else if (source === 'ovaHeightZoom') {
280
                    source = annotator.osda.viewer.drawer.viewport.getBounds().height;
281
                } else if (source === 'ovaContainer') {
282
                    source = annotator.osda.viewer.id;
283
                } else if (source === 'ovaSrc') {
284 285 286 287 288 289 290 291 292
                    var source = annotator.osda.viewer.source;
                    var tilesUrl = typeof source.tilesUrl !== 'undefined' ? source.tilesUrl : '';
                    var functionUrl = typeof source.getTileUrl !== 'undefined' ? source.getTileUrl : '';
                    source = tilesUrl !== '' ? tilesUrl : ('' + functionUrl).replace(/\s+/g, ' '); //  - target.src (media source)
                }
            } else {  // Text Annotation
                var annotation = editor.annotation;
                // if ranges is 0 then it is a comment
                if (annotation.ranges.length > 0) {
293
                    if(source === 'ovastartOffset') {
294
                        source = annotation.ranges[0].startOffset;
295
                    } else if (source === 'ovaendOffset') {
296
                        source = annotation.ranges[0].endOffset;
297
                    } else if (source === 'ovaStart') {
298
                        source = annotation.ranges[0].start;
299
                    } else if (source === 'ovaEnd') {
300
                        source = annotation.ranges[0].end;
301
                    }
302
                }
303 304 305 306 307 308 309 310 311 312 313
            }
        }
        return encodeURIComponent(source);
    };
    
    Share.prototype.initAPI = function() {
        //  -- Detect API in the URL -- //
        /*
        The first option is to give a known id of an annotation
        Example http:// url.com/#id=rTcpOjIMT2aF1apDtboC-Q
        */
314
        var API = {};
315 316 317 318 319 320 321
        var ovaId = this.getParameterByName('ovaId'); // Method 1 (Obligatory)
        var start = this.getParameterByName('ovaStart'); // Method 2 (Obligatory)
        var end = this.getParameterByName('ovaEnd'); // Method 2 (Obligatory)
        var container = this.getParameterByName('ovaContainer'); // Method 2 (Obligatory)
        var src = this.getParameterByName('ovaSrc'); // Method 2 (Obligatory)
        var text = this.getParameterByName('ovaText'); // Method 2 
        var user = this.getParameterByName('ovaUser'); // Method 2 
322 323 324 325 326 327 328 329
        var Left = this.getParameterByName('ovaLeft'); // Method 2 
        var Top = this.getParameterByName('ovaTop'); // Method 2 
        var Width = this.getParameterByName('ovaWidth'); // Method 2 
        var Height = this.getParameterByName('ovaHeight'); // Method 2 
        var leftZoom = this.getParameterByName('ovaLeftZoom'); // Method 2 
        var topZoom = this.getParameterByName('ovaTopZoom'); // Method 2 
        var widthZoom = this.getParameterByName('ovaWidthZoom'); // Method 2 
        var heightZoom = this.getParameterByName('ovaHeightZoom'); // Method 2  
330
        var startOffset = this.getParameterByName('ovastartOffset'); // Method 2 
331
        var endOffset = this.getParameterByName('ovaendOffset'); // Method 2 
332 333 334
        
        // remove the variables from the url browser
        var stripped_url = top.location.href;
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
        if (ovaId !== '') stripped_url = this.removeVariableFromURL(stripped_url, 'ovaId');
        if (start !== '') stripped_url = this.removeVariableFromURL(stripped_url, 'ovaStart');
        if (end !== '') stripped_url = this.removeVariableFromURL(stripped_url, 'ovaEnd');
        if (container !== '') stripped_url = this.removeVariableFromURL(stripped_url, 'ovaContainer');
        if (src !== '') stripped_url = this.removeVariableFromURL(stripped_url, 'ovaSrc');
        if (text !== '') stripped_url = this.removeVariableFromURL(stripped_url, 'ovaText');
        if (user !== '') stripped_url = this.removeVariableFromURL(stripped_url, 'ovaUser');
        if (Left !== '') stripped_url = this.removeVariableFromURL(stripped_url, 'ovaLeft');
        if (Top !== '') stripped_url = this.removeVariableFromURL(stripped_url, 'ovaTop');
        if (Width !== '') stripped_url = this.removeVariableFromURL(stripped_url, 'ovaWidth');
        if (Height !== '') stripped_url = this.removeVariableFromURL(stripped_url, 'ovaHeight');
        if (leftZoom !== '') stripped_url = this.removeVariableFromURL(stripped_url, 'ovaLeftZoom');
        if (topZoom !== '') stripped_url = this.removeVariableFromURL(stripped_url, 'ovaTopZoom');
        if (widthZoom !== '') stripped_url = this.removeVariableFromURL(stripped_url, 'ovaWidthZoom');
        if (heightZoom !== '') stripped_url = this.removeVariableFromURL(stripped_url, 'ovaHeightZoom');
        if (startOffset !== '') stripped_url = this.removeVariableFromURL(stripped_url, 'ovastartOffset');
        if (endOffset !== '') stripped_url = this.removeVariableFromURL(stripped_url, 'ovaendOffset');
352 353 354 355 356
        window.history.pushState("object or string", "Title", stripped_url);
        
        
        //  Method 1 API with the Id of the annotation
        // Example: http://danielcebrian.com/annotations/demo.html?&ovaId=wtva_SjnQb2HtqppDihKug
357 358
        if (ovaId !== '') {
            $.extend(API, {method: 1, ovaId: ovaId});
359 360 361 362 363
        }
        // Method 2 API with all the parameter to load the annotation
        // Example with video: http://danielcebrian.com/annotations/demo.html?ovaContainer=vid1&ovaSrc=http%3A%2F%2Fvideo-js.zencoder.com%2Foceans-clip.mp4&ovaStart=2&ovaEnd=10&ovaText=This%20is%20test&ovaUser=Test%20User
        // Example with text: http://danielcebrian.com/annotations/demo.html?ovaStart=%2Fp%5B1%5D&ovaEnd=%2Fp%5B1%5D&ovastartOffset=542&ovaendOffset=572&ovaText=API
    
364
        if (start !== '' && end !== '' && container !== '' && src !== '') { // video api
365
            $.extend(API, {method: 2, start: start, end: end, container: container, src: src, text: text, user: user});
366
        } else if (Left !== '' && Top !== '' && Width !== '' && Height !== '' && leftZoom !== '' && topZoom !== '' && widthZoom !== '' && heightZoom !== '') { // image api
367
            $.extend(API, {method: 2, Left: Left, Top: Top, Width: Width, Height: Height, leftZoom: leftZoom, topZoom: topZoom, widthZoom: widthZoom, heightZoom: heightZoom, container: container, src: src, text: text, user: user});
368
        } else if (start !== '' && end !== '' && startOffset !== '' && endOffset !== '') { // text api
369
            $.extend(API, {method: 2, start: start, end: end, startOffset: startOffset, endOffset: endOffset, text: text, user: user});
370 371 372 373 374 375 376
        }
        return API;
    }
    Share.prototype.runningAPI = function (annotations, API) {
        var wrapper = $('.annotator-wrapper').parent()[0];
        var mplayer;
        var osda;
377
        var self = this;
378 379 380 381
        
        // Set Annotator in wrapper to fix quick DOM
        $.data(wrapper, 'annotator', self.annotator);// Set the object in the span
        annotator = window.annotator = $.data(wrapper, 'annotator');
382 383
        mplayer = (typeof annotator.mplayer !== 'undefined') ? annotator.mplayer : [];
        osda = (typeof annotator.osda !== 'undefined') ? annotator.osda : [];
384 385
        
        // Detect if the URL has an API element
386 387
        if (typeof API !== 'undefined' && typeof API.method !== 'undefined' && (parseInt(API.method, 10) === 1 || parseInt(API.method, 10) === 2)) {
            if (parseInt(API.method, 10) === 1) {
388
                var allannotations = annotator.plugins['Store'].annotations;
389
                var ovaId = parseInt(decodeURIComponent(API.ovaId), 10);
390 391 392
                
                for (var item in allannotations) {
                    var an = allannotations[item];
393
                    var olditem;
394 395 396
                    if (typeof an.id !== 'undefined' && parseInt(an.id, 10) === ovaId) { // this is the annotation
                        if (self._isVideo(an)) {// It is a video
                            if (typeof mplayer[an.target.container] !== 'undefined') {
397
                                var player = mplayer[an.target.container];
398
                                if (player.id_ === an.target.container) {
399
                                    var anFound = an;
400 401
                                    videojs(player.id_).ready(function() {
                                        if (player.techName !== 'Youtube') {
402 403 404 405 406 407 408
                                            player.preload('auto');
                                        }
                                        player.autoPlayAPI = anFound;
                                        player.play();
                                    });
                                }
                            }
409 410
                        } else if (an.media === "image") { // It is a OpenSeaDragon Annotation
                            if ($("div#" + an.target.container).length) {
411 412 413
                                var isOpenViewer = typeof annotator.osda !== "undefined" && typeof annotator.osda.viewer !== "undefined"; 
                                function waitingOsda(){
                                    isOpenViewer = typeof annotator.osda !== "undefined" && typeof annotator.osda.viewer !== "undefined";
414
                                    if (typeof olditem === "undefined") {
415 416 417
                                        olditem = item;
                                    }
                                    if (!isOpenViewer) {
418
                                        setTimeout(waitingOsda, 200);
419 420 421 422 423 424 425 426 427
                                    } else {
                                        an = allannotations[olditem];
                                        $(an.highlights).parent().find('.annotator-hl').removeClass('api'); 
                                        // change the color
                                        $(an.highlights).addClass('api');
                                        // change zoom
                                        if (typeof annotator !== 'undefined' && typeof annotator.osda !== 'undefined') {
                                            var currentBounds = annotator.osda.viewer.drawer.viewport.getBounds();
                                            var bounds = typeof an.bounds !== 'undefined' ? an.bounds : {};
428 429 430 431 432 433 434 435 436 437 438 439 440

                                            if (typeof bounds.x !== 'undefined') {
                                                currentBounds.x = bounds.x;
                                            }
                                            if (typeof bounds.y !== 'undefined') {
                                                currentBounds.y = bounds.y;
                                            }
                                            if (typeof bounds.width !== 'undefined') {
                                                currentBounds.width = bounds.width;
                                            }
                                            if (typeof bounds.height !== 'undefined') {
                                                currentBounds.height = bounds.height;
                                            }
441 442 443 444 445 446 447 448 449 450 451 452 453 454
                                            annotator.osda.viewer.drawer.viewport.fitBounds(currentBounds); 
                                        }
                                        // animate to the annotation
                                        $('html,body').animate({
                                            scrollTop: $(annotator.osda.viewer.element).offset().top
                                        }, 'slow');
                                    }
                                }
                                waitingOsda();
                            }
                        } else {  // It is a text
                            var hasRanges = typeof an.ranges !== 'undefined' && typeof an.ranges[0] !== 'undefined';
                            var startOffset = hasRanges ? an.ranges[0].startOffset : '';
                            var endOffset = hasRanges ? an.ranges[0].endOffset : '';
455
                
456
                            if (typeof startOffset !== 'undefined' && typeof endOffset !== 'undefined') { 
457 458 459
                                // change the color
                                $(an.highlights).addClass('api'); 
                                // animate to the annotation
460 461 462
                                $('html,body').animate({
                                    scrollTop: $(an.highlights[0]).offset().top
                                }, 'slow');
463 464 465 466
                            }
                        }
                    }
                }
467
            } else if (parseInt(API.method, 10) === 2) {
468
                if (typeof mplayer !== 'undefined') {
469
                    // variable for Video
470
                    var container = decodeURIComponent(API.container);
471
                    var player = mplayer[container];
472
                    var isVideo = (typeof player !== 'undefined' && container === player.id_);
473 474 475
                    var isNumber = (!isNaN(parseFloat(API.start)) && isFinite(API.start) && !isNaN(parseFloat(API.end)) && isFinite(API.end));
                    var isSource = false;
                        
476
                    if (isVideo) {
477 478 479
                        // Compare without extension
                        var src = decodeURIComponent(API.src);
                        var targetSrc = src.substring(0, src.lastIndexOf("."));
480
                        var playerSrc = (player.tech.options_.source.src === '') ? player.tag.currentSrc : player.tech.options_.source.src;
481
                        playerSrc = playerSrc.substring(0, playerSrc.lastIndexOf("."));
482
                        isSource = (targetSrc === playerSrc);
483 484 485
                    }
        
                    // Open Video Annotation
486
                    if (isVideo && isNumber && isSource) { 
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
                        var annotation = {
                                rangeTime: {
                                    start: API.start,
                                    end: API.end
                                },
                                created: new Date().toISOString(),
                                updated: new Date().toISOString(),
                                target: {
                                    container: container,
                                    src: src
                                },
                                media: 'video',
                                text: decodeURIComponent(API.text),
                                user: decodeURIComponent(API.user)
                            };
                        videojs(player.id_).ready(function(){
503
                            if (player.techName !== 'Youtube'){
504 505 506 507 508 509 510 511 512 513 514 515
                                player.preload('auto');
                            }
                            player.autoPlayAPI = annotation;
                            player.play();
                        });
                    }
                }
                // variable for text
                var startOffset = API.startOffset;
                var endOffset = API.endOffset;
                
                // Text Annotation
516
                if (!isVideo && typeof startOffset !== 'undefined' && typeof endOffset !== 'undefined') { 
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
                    var annotation = {
                        ranges: [{
                            start: decodeURIComponent(API.start),
                            end: decodeURIComponent(API.end),
                            startOffset: decodeURIComponent(API.startOffset),
                            endOffset: decodeURIComponent(API.endOffset),
                        }],
                        created: new Date().toISOString(),
                        updated: new Date().toISOString(),
                        media: 'text',
                        text: decodeURIComponent(API.text),
                        user: decodeURIComponent(API.user)
                    };
                    // show the annotation
                    annotator.setupAnnotation(annotation);
                    // to change the color
                    $(annotation.highlights).addClass('api'); 
                    // animate to the annotation
                    $('html, body').animate({
536 537
                        scrollTop: $(annotation.highlights[0]).offset().top
                    }, 'slow');
538
                }
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
                // variables for images
                var Left = API.Left;
                var Top = API.Top;
                var Width = API.Width;
                var Height = API.Height;
                var leftZoom = API.leftZoom;
                var topZoom = API.topZoom;
                var widthZoom = API.widthZoom;
                var heightZoom = API.heightZoom; 
                
                // Image Annotation
                if (!isVideo && typeof Left !== 'undefined' && typeof Top !== 'undefined' && typeof Width !== 'undefined' && typeof Height !== 'undefined' && typeof leftZoom !== 'undefined' && typeof topZoom !== 'undefined' && typeof widthZoom !== 'undefined' && typeof heightZoom !== 'undefined') { 
                    var an = {
                        rangePosition: {
                            width: parseFloat(decodeURIComponent(API.Width)),
                            top: parseFloat(decodeURIComponent(API.Top)),
                            left: parseFloat(decodeURIComponent(API.Left)),
                            height: parseFloat(decodeURIComponent(API.Height)),
                        },
                        bounds: {
                            width: parseFloat(decodeURIComponent(API.widthZoom)),
                            x: parseFloat(decodeURIComponent(API.leftZoom)),
                            y: parseFloat(decodeURIComponent(API.topZoom)),
                            height: parseFloat(decodeURIComponent(API.heightZoom)),
                        },
                        target:{
                            container: API.container,
                            src: API.src
                        },
                        created: new Date().toISOString(),
                        updated: new Date().toISOString(),
                        media: 'image',
                        text: decodeURIComponent(API.text),
                        user: decodeURIComponent(API.user)
                    };

                    var isOpenViewer = typeof annotator.osda !== "undefined" && typeof annotator.osda.viewer !== "undefined"; 
                    function waitingOsda() {
                        isOpenViewer = typeof annotator.osda !== "undefined" && typeof annotator.osda.viewer !== "undefined";
                        if (!isOpenViewer) {
                            setTimeout(waitingOsda, 200);
                        } else {
                            // show the annotation
                            annotator.plugins['Store'].annotations.push(an);
                            annotator.osda.viewer.annotationInstance.drawRect(an);
                            // change the color
                            $(an.highlights).addClass('api');
                            // change zoom
                            var currentBounds = annotator.osda.viewer.drawer.viewport.getBounds();
                            var bounds = typeof an.bounds !== 'undefined' ? an.bounds : {};
589 590 591 592 593 594 595 596 597 598 599 600
                            if (typeof bounds.x !== 'undefined') {
                                currentBounds.x = bounds.x;
                            }
                            if (typeof bounds.y !== 'undefined') {
                                currentBounds.y = bounds.y;
                            }
                            if (typeof bounds.width !== 'undefined') {
                                currentBounds.width = bounds.width;
                            }
                            if (typeof bounds.height !== 'undefined') {
                                currentBounds.height = bounds.height;
                            }
601 602 603 604 605 606 607 608 609
                            annotator.osda.viewer.drawer.viewport.fitBounds(currentBounds); 
                            // animate to the annotation
                            $('html,body').animate({
                                scrollTop: $(annotator.osda.viewer.element).offset().top
                            }, 'slow');
                        }
                    }
                    waitingOsda();
                }
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
                
            }
        }
        // Let know to others API that this plugin is loaded
        annotator.isShareLoaded = true;
        annotator.publish('shareloaded');
    }
    Share.prototype.runAPI = function(API) {
        var self = this;
        var func = function(annotations) {
            self.runningAPI(annotations, API);
            self.annotator.unsubscribe("annotationsLoaded", func);    
        };
        this.annotator
            // -- Finished the Annotator DOM
            .subscribe("annotationsLoaded", func);
    }
    
628
    Share.prototype._isVideo = function(an) {
629 630 631
        // Detect if the annotation is a Open Video Annotation
        var an = an || {};
        var rt = an.rangeTime;
632 633 634
        var isVideo = (typeof an.media !== 'undefined' && an.media === 'video');
        var hasContainer = (typeof an.target !== 'undefined' && typeof an.target.container !== 'undefined' );
        var isNumber = (typeof rt !== 'undefined' && !isNaN(parseFloat(rt.start)) && isFinite(rt.start) && !isNaN(parseFloat(rt.end)) && isFinite(rt.end));
635 636 637
        return (isVideo && hasContainer && isNumber);
    }
    
638
    Share.prototype._isImage = function(annotation) {
639 640 641 642 643 644 645 646
        var wrapper = $('.annotator-wrapper').parent()[0];
        var annotator = window.annotator = $.data(wrapper, 'annotator');
        var rp = an.rangePosition;
        var isOpenSeaDragon = (typeof annotator.osda !== 'undefined');
        var isContainer = (typeof an.target !== 'undefined' && typeof an.target.container !== 'undefined');
        var isImage = (typeof an.media !== 'undefined' && an.media === 'image');
        var isRP = (typeof rp !== 'undefined');
        return (isOpenSeaDragon && isContainer && isImage && isRP);
647
    }
648

649 650 651 652
    Share.prototype.getParameterByName = function(name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
        var results = regex.exec('?' + window.location.href.split('?')[1]);
653
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
    };
    
    Share.prototype.removeVariableFromURL = function(url_string, variable_name) {
        var URL = String(url_string);
        var regex = new RegExp( "\\?" + variable_name + "=[^&]*&?", "gi");
        URL = URL.replace(regex,'?');
        regex = new RegExp( "\\&" + variable_name + "=[^&]*&?", "gi");
        URL = URL.replace(regex,'&');
        URL = URL.replace(/(\?|&)$/,'');
        regex = null;
        return URL;
    }

    Share.prototype.updateViewer = function(field, annotation) {
        this.annotation = annotation;
        
        var self = this;
        var field = $(field);
        var ret = field.addClass('share-viewer-annotator').html(function() {
673
            var string;
674 675 676 677
            return self.buildHTMLShareButton('Share:', self.getSource('ovaId'));
        });
            
        // Create the actions for the buttons
678
        this.buttonsActions(field[0], 1, this.options.baseUrl); // 1 is the method of the API that will be for share some annotation in the database
679 680 681 682
        return ret;
    };

    return Share;
daniel cebrian committed
683 684

})(Annotator.Plugin);