videogular.js 61.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 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 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
/**
 * @license videogular v1.4.1 http://videogular.com
 * Two Fucking Developers http://twofuckingdevelopers.com
 * License: MIT
 */
"use strict";
angular.module("com.2fdevs.videogular", ["ngSanitize"])
    .run(
    ["$templateCache", function ($templateCache) {
        $templateCache.put("vg-templates/vg-media-video", "<video></video>");
        $templateCache.put("vg-templates/vg-media-audio", "<audio></audio>");

        // Support for browsers that doesn't have .bind()
        if (!Function.prototype.bind) {
            Function.prototype.bind = function (oThis) {
                if (typeof this !== 'function') {
                    // closest thing possible to the ECMAScript 5
                    // internal IsCallable function
                    throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
                }

                var aArgs = Array.prototype.slice.call(arguments, 1),
                    fToBind = this,
                    fNOP = function () {
                    },
                    fBound = function () {
                        return fToBind.apply(this instanceof fNOP
                                ? this
                                : oThis,
                            aArgs.concat(Array.prototype.slice.call(arguments)));
                    };

                fNOP.prototype = this.prototype;
                fBound.prototype = new fNOP();

                return fBound;
            };
        }
    }]
);

/**
 * @ngdoc service
 * @name com.2fdevs.videogular.constant:VG_STATES
 *
 * @description
 * Possible video states:
 *  - VG_STATES.PLAY: "play"
 *  - VG_STATES.PAUSE: "pause"
 *  - VG_STATES.STOP: "stop"
 **/
/**
 * @ngdoc service
 * @name com.2fdevs.videogular.constant:VG_VOLUME_KEY
 *
 * @description localStorage key name for persistent video play volume on a domain.
 **/
"use strict";
angular.module("com.2fdevs.videogular")
    .constant("VG_STATES", {
        PLAY: "play",
        PAUSE: "pause",
        STOP: "stop"
    })
    .constant("VG_VOLUME_KEY", "videogularVolume");

"use strict";
/**
 * @ngdoc controller
 * @name com.2fdevs.videogular.controller:vgController
 * @description
 * Videogular controller.
 * This controller offers a public API:
 *
 * Methods
 * - play(): Plays media.
 * - pause(): Pause media.
 * - stop(): Stops media.
 * - playPause(): Toggles play and pause.
 * - seekTime(value, byPercent): Seeks to a specified time position. Param value must be an integer representing the target position in seconds or a percentage. By default seekTime seeks by seconds, if you want to seek by percentage just pass byPercent to true.
 * - setVolume(volume): Sets volume. Param volume must be an integer with a value between 0 and 1.
 * - setPlayback(playback): Sets playback. Param plaback must be an integer with a value between 0 and 2.
 * - setState(state): Sets a new state. Param state mus be an string with 'play', 'pause' or 'stop'. This method only changes the state of the player, but doesn't plays, pauses or stops the media file.
 * - toggleFullScreen(): Toggles between fullscreen and normal mode.
 * - updateTheme(css-url): Removes previous CSS theme and sets a new one.
 * - clearMedia(): Cleans the current media file.
 * - changeSource(array): Updates current media source. Param `array` must be an array of media source objects.
 * A media source is an object with two properties `src` and `type`. The `src` property must contains a trustful url resource.
 * <pre>{src: $sce.trustAsResourceUrl("http://static.videogular.com/assets/videos/videogular.mp4"), type: "video/mp4"}</pre>
 *
 * Properties
 * - config: String with a url to JSON config file.
 * - isReady: Boolean value with current player initialization state.
 * - isBuffering: Boolean value to know if player is buffering media.
 * - isCompleted: Boolean value to know if current media file has been completed.
 * - isLive: Boolean value to know if current media file is a Live Streaming.
 * - playsInline: Boolean value to know if Videogular is using inline playing or not.
 * - nativeFullscreen: Boolean value to know if Videogular if fullscreen mode will use native mode or emulated mode.
 * - mediaElement: Reference to video/audio object.
 * - videogularElement: Reference to videogular tag.
 * - sources: Array with current sources.
 * - tracks: Array with current tracks.
 * - cuePoints: Object containing a list of timelines with cue points. Each property in the object represents a timeline, which is an Array of objects with the next definition:
 * <pre>{
 *    timeLapse:{
 *      start: 0,
 *      end: 10
 *    },
 *    onEnter: callback(currentTime, timeLapse, params),
 *    onLeave: callback(currentTime, timeLapse, params),
 *    onUpdate: callback(currentTime, timeLapse, params),
 *    onComplete: callback(currentTime, timeLapse, params),
 *    params: {
 *      // Custom object with desired structure and data
 *    }
 * }</pre>
 *
 *    * **timeLapse:** Object with start and end properties to define in seconds when this timeline is active.\n
 *    * **onEnter:** Callback function that will be called when progress reaches a cue point or being outside a cue point user seeks to a cue point manually.
 *    * **onLeave:** Callback function that will be called when user seeks and the new time doesn't reach to the timeLapse.start property.
 *    * **onUpdate:** Callback function that will be called when the progress is in the middle of timeLapse.start and timeLapse.end.
 *    * **onComplete:** Callback function that will be called when the progress is bigger than timeLapse.end.
 *    * **params:** Custom object with data to pass to the callbacks.
 *
 * - isFullScreen: Boolean value to know if we’re in fullscreen mode.
 * - currentState: String value with “play”, “pause” or “stop”.
 * - currentTime: Number value with current media time progress.
 * - totalTime: Number value with total media time.
 * - timeLeft: Number value with current media time left.
 * - volume: Number value with current volume between 0 and 1.
 * - playback: Number value with current playback between 0 and 2.
 * - bufferEnd: Number value with latest buffer point in milliseconds.
 * - buffered: Array of TimeRanges objects that represents current buffer state.
 *
 */
angular.module("com.2fdevs.videogular")
    .controller("vgController",
    ['$scope', '$window', 'vgConfigLoader', 'vgFullscreen', 'VG_UTILS', 'VG_STATES', 'VG_VOLUME_KEY', function ($scope, $window, vgConfigLoader, vgFullscreen, VG_UTILS, VG_STATES, VG_VOLUME_KEY) {
        var currentTheme = null;
        var isFullScreenPressed = false;
        var isMetaDataLoaded = false;
        var hasStartTimePlayed = false;
        var isVirtualClip = false;

        // PUBLIC $API
        this.videogularElement = null;

        this.clearMedia = function () {
            this.mediaElement[0].src = '';
            this.mediaElement[0].removeEventListener("canplay", this.onCanPlay.bind(this), false);
            this.mediaElement[0].removeEventListener("loadedmetadata", this.onLoadMetaData.bind(this), false);
            this.mediaElement[0].removeEventListener("waiting", this.onStartBuffering.bind(this), false);
            this.mediaElement[0].removeEventListener("ended", this.onComplete.bind(this), false);
            this.mediaElement[0].removeEventListener("playing", this.onStartPlaying.bind(this), false);
            this.mediaElement[0].removeEventListener("play", this.onPlay.bind(this), false);
            this.mediaElement[0].removeEventListener("pause", this.onPause.bind(this), false);
            this.mediaElement[0].removeEventListener("volumechange", this.onVolumeChange.bind(this), false);
            this.mediaElement[0].removeEventListener("playbackchange", this.onPlaybackChange.bind(this), false);
            this.mediaElement[0].removeEventListener("timeupdate", this.onUpdateTime.bind(this), false);
            this.mediaElement[0].removeEventListener("progress", this.onProgress.bind(this), false);
            this.mediaElement[0].removeEventListener("seeking", this.onSeeking.bind(this), false);
            this.mediaElement[0].removeEventListener("seeked", this.onSeeked.bind(this), false);
            this.mediaElement[0].removeEventListener("error", this.onVideoError.bind(this), false);
        };

        this.onRouteChange = function() {
            if (this.clearMediaOnNavigate === undefined || this.clearMediaOnNavigate === true) {
                this.clearMedia();
            }
        };

        this.onCanPlay = function (evt) {
            this.isBuffering = false;
            $scope.$apply($scope.vgCanPlay({$event: evt}));

            if (!hasStartTimePlayed && (this.startTime > 0 || this.startTime === 0)) {
                this.seekTime(this.startTime);
                hasStartTimePlayed = true;
            }
        };

        this.onVideoReady = function () {
            this.isReady = true;
            this.autoPlay = $scope.vgAutoPlay;
            this.playsInline = $scope.vgPlaysInline;
            this.nativeFullscreen = $scope.vgNativeFullscreen || true;
            this.cuePoints = $scope.vgCuePoints;
            this.startTime = $scope.vgStartTime;
            this.virtualClipDuration = $scope.vgVirtualClipDuration;
            this.clearMediaOnNavigate = $scope.vgClearMediaOnNavigate || true;
            this.currentState = VG_STATES.STOP;

            isMetaDataLoaded = true;
            isVirtualClip = this.startTime >= 0 && this.virtualClipDuration > 0;

            //Set media volume from localStorage if available
            if (VG_UTILS.supportsLocalStorage()) {
                //Default to 100% volume if local storage setting does not exist.
                this.setVolume(parseFloat($window.localStorage.getItem(VG_VOLUME_KEY) || '1'));
            }

            if ($scope.vgConfig) {
                vgConfigLoader.loadConfig($scope.vgConfig).then(
                    this.onLoadConfig.bind(this)
                );
            }
            else {
                $scope.vgPlayerReady({$API: this});
            }
        };

        this.onLoadConfig = function (config) {
            this.config = config;

            $scope.vgTheme = this.config.theme;
            $scope.vgAutoPlay = this.config.autoPlay;
            $scope.vgPlaysInline = this.config.playsInline;
            $scope.vgNativeFullscreen = this.config.nativeFullscreen;
            $scope.vgCuePoints = this.config.cuePoints;
            $scope.vgClearMediaOnNavigate = this.config.clearMediaOnNavigate;
            $scope.vgStartTime = this.config.startTime;
            $scope.vgVirtualClipDuration = this.config.virtualClipDuration;
            isVirtualClip = $scope.vgStartTime >= 0 && $scope.vgVirtualClipDuration > 0;

            $scope.vgPlayerReady({$API: this});
        };

        this.onLoadMetaData = function (evt) {
            this.isBuffering = false;
            this.onUpdateTime(evt);
        };

        this.onProgress = function (event) {
            this.updateBuffer(event);

            $scope.$apply();
        };

        this.updateBuffer = function getBuffer(event) {
            if (event.target.buffered.length) {
                this.buffered = event.target.buffered;
                this.bufferEnd = 1000 * event.target.buffered.end(event.target.buffered.length - 1);

                // Avoid bufferEnd overflow by virtual clips
                if (this.bufferEnd > this.totalTime) this.bufferEnd = this.totalTime;
            }
        };

        this.onUpdateTime = function (event) {
            var targetTime = 1000 * event.target.currentTime;

            this.updateBuffer(event);

            if (event.target.duration != Infinity) {
                // Fake the duration and current time for virtual clips
                if (isVirtualClip) {
                    if (hasStartTimePlayed && (event.target.currentTime < this.startTime || event.target.currentTime - this.startTime > this.virtualClipDuration)) {
                        this.onComplete();
                    }
                    else {
                        this.currentTime = Math.max(0, targetTime - (1000 * this.startTime));
                        this.totalTime = 1000 * this.virtualClipDuration;
                        this.timeLeft = (1000 * this.virtualClipDuration) - this.currentTime;
                    }
                }
                else {
                    this.currentTime = targetTime;
                    this.totalTime = 1000 * event.target.duration;
                    this.timeLeft = 1000 * (event.target.duration - event.target.currentTime);
                }

                this.isLive = false;
            }
            else {
                // It's a live streaming without and end
                this.currentTime = targetTime;
                this.isLive = true;
            }

            var targetSeconds = isVirtualClip ? this.currentTime / 1000 : event.target.currentTime;
            var targetDuration = isVirtualClip ? this.totalTime / 1000 : event.target.duration;

            if (this.cuePoints) {
                this.checkCuePoints(targetSeconds);
            }

            $scope.vgUpdateTime({$currentTime: targetSeconds, $duration: targetDuration});

            // Safe apply just in case we're calling from a non-event
            if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') {
                $scope.$apply();
            }
        };

        this.checkCuePoints = function checkCuePoints(currentTime) {
            for (var tl in this.cuePoints) {
                for (var i = 0, l = this.cuePoints[tl].length; i < l; i++) {
                    var cp = this.cuePoints[tl][i];
                    var currentSecond = parseInt(currentTime, 10);
                    var start = parseInt(cp.timeLapse.start, 10);

                    // If timeLapse.end is not defined we set it as 1 second length
                    if (!cp.timeLapse.end) cp.timeLapse.end = cp.timeLapse.start + 1;

                    if (currentTime < cp.timeLapse.end) cp.$$isCompleted = false;

                    // Fire the onEnter event once reach to the cue point
                    if(!cp.$$isDirty && currentSecond === start && (typeof cp.onEnter == 'function')) {
                        cp.onEnter(currentTime, cp.timeLapse, cp.params);
                        cp.$$isDirty = true;
                    }

                    // Check if we've been reached to the cue point
                    if (currentTime > cp.timeLapse.start) {
                        // We're in the timelapse
                        if (currentTime < cp.timeLapse.end) {
                            // Trigger onUpdate each time we enter here
                            if (cp.onUpdate) cp.onUpdate(currentTime, cp.timeLapse, cp.params);

                            // Trigger onEnter if we enter on the cue point by manually seeking
                            if (!cp.$$isDirty && (typeof cp.onEnter === 'function')) {
                                cp.onEnter(currentTime, cp.timeLapse, cp.params);
                            }
                        }

                        // We've been passed the cue point
                        if (currentTime >= cp.timeLapse.end) {
                            if (cp.onComplete && !cp.$$isCompleted) {
                                cp.$$isCompleted = true;
                                cp.onComplete(currentTime, cp.timeLapse, cp.params);
                            }
                        }

                        cp.$$isDirty = true;
                    }
                    else {
                        if (cp.onLeave && cp.$$isDirty) {
                            cp.onLeave(currentTime, cp.timeLapse, cp.params);
                        }

                        cp.$$isDirty = false;
                    }
                }
            }
        };

        this.onPlay = function () {
            this.setState(VG_STATES.PLAY);
            $scope.$apply();
        };

        this.onPause = function () {
            var currentTime = isVirtualClip ? this.currentTime : this.mediaElement[0].currentTime;

            if (currentTime == 0) {
                this.setState(VG_STATES.STOP);
            }
            else {
                this.setState(VG_STATES.PAUSE);
            }

            $scope.$apply();
        };

        this.onVolumeChange = function () {
            this.volume = this.mediaElement[0].volume;
            $scope.$apply();
        };

        this.onPlaybackChange = function () {
            this.playback = this.mediaElement[0].playbackRate;
            $scope.$apply();
        };

        this.onSeeking = function (event) {
            $scope.vgSeeking({$currentTime: event.target.currentTime, $duration: event.target.duration});
        };

        this.onSeeked = function (event) {
            $scope.vgSeeked({$currentTime: event.target.currentTime, $duration: event.target.duration});
        };

        this.seekTime = function (value, byPercent) {
            var second;
            if (byPercent) {
                if (isVirtualClip) {
                    value = Math.max(0, Math.min(value, 100));
                    second = (value * this.virtualClipDuration / 100);
                    this.mediaElement[0].currentTime = this.startTime + second;
                }
                else {
                    second = value * this.mediaElement[0].duration / 100;
                    this.mediaElement[0].currentTime = second;
                }
            }
            else {
                if (isVirtualClip) {
                    var durationPercent = value/this.mediaElement[0].duration;
                    second = !hasStartTimePlayed ? 0 : this.virtualClipDuration * durationPercent;
                    this.mediaElement[0].currentTime = !hasStartTimePlayed ? this.startTime : this.startTime + second;
                }
                else {
                    second = value;
                    this.mediaElement[0].currentTime = second;
                }
            }

            this.currentTime = 1000 * second;
        };

        this.playPause = function () {
            if (this.mediaElement[0].paused) {
                this.play();
            }
            else {
                this.pause();
            }
        };

        this.setState = function (newState) {
            if (newState && newState != this.currentState) {
                $scope.vgUpdateState({$state: newState});

                this.currentState = newState;
            }

            return this.currentState;
        };

        this.play = function () {
            this.mediaElement[0].play();
            this.setState(VG_STATES.PLAY);
        };

        this.pause = function () {
            this.mediaElement[0].pause();
            this.setState(VG_STATES.PAUSE);
        };

        this.stop = function () {
            try {
                this.mediaElement[0].pause();

                var targetTime = isVirtualClip ? this.startTime : 0;
                this.mediaElement[0].currentTime = targetTime;

                this.currentTime = targetTime;
                this.buffered = [];
                this.bufferEnd = 0;
                this.setState(VG_STATES.STOP);
            }
            catch (e) {
                return e;
            }
        };

        this.toggleFullScreen = function () {
            // There is no native full screen support or we want to play inline
            if (!vgFullscreen.isAvailable || !this.nativeFullscreen) {
                if (this.isFullScreen) {
                    this.videogularElement.removeClass("fullscreen");
                    this.videogularElement.css("z-index", "auto");
                }
                else {
                    this.videogularElement.addClass("fullscreen");
                    this.videogularElement.css("z-index", VG_UTILS.getZIndex());
                }

                this.isFullScreen = !this.isFullScreen;
            }
            // Perform native full screen support
            else {
                if (this.isFullScreen) {
                    if (!VG_UTILS.isMobileDevice()) {
                        vgFullscreen.exit();
                    }
                }
                else {
                    // On mobile devices we should make fullscreen only the video object
                    if (VG_UTILS.isMobileDevice()) {
                        // On iOS we should check if user pressed before fullscreen button
                        // and also if metadata is loaded
                        if (VG_UTILS.isiOSDevice()) {
                            if (isMetaDataLoaded) {
                                this.enterElementInFullScreen(this.mediaElement[0]);
                            }
                            else {
                                isFullScreenPressed = true;
                                this.play();
                            }
                        }
                        else {
                            this.enterElementInFullScreen(this.mediaElement[0]);
                        }
                    }
                    else {
                        this.enterElementInFullScreen(this.videogularElement[0]);
                    }
                }
            }
        };

        this.enterElementInFullScreen = function (element) {
            vgFullscreen.request(element);
        };

        this.changeSource = function (newValue) {
            $scope.vgChangeSource({$source: newValue});
        };

        this.setVolume = function (newVolume) {
            newVolume = Math.max(Math.min(newVolume, 1), 0);
            $scope.vgUpdateVolume({$volume: newVolume});

            this.mediaElement[0].volume = newVolume;
            this.volume = newVolume;

            //Push volume updates to localStorage so that future instances resume volume
            if (VG_UTILS.supportsLocalStorage()) {
                //TODO: Improvement: concat key with current page or "video player id" to create separate stored volumes.
                $window.localStorage.setItem(VG_VOLUME_KEY, newVolume.toString());
            }
        };

        this.setPlayback = function (newPlayback) {
            $scope.vgUpdatePlayback({$playBack: newPlayback});

            this.mediaElement[0].playbackRate = newPlayback;
            this.playback = newPlayback;
        };

        this.updateTheme = function (value) {
            var links = document.getElementsByTagName("link");
            var i;
            var l;

            // Remove previous theme
            if (currentTheme) {
                for (i = 0, l = links.length; i < l; i++) {
                    if (links[i].outerHTML.indexOf(currentTheme) >= 0) {

                        links[i].parentNode.removeChild(links[i]);
                        break;
                    }
                }
            }

            if (value) {
                var headElem = angular.element(document).find("head");
                var exists = false;

                // Look if theme already exists
                for (i = 0, l = links.length; i < l; i++) {
                    exists = (links[i].outerHTML.indexOf(value) >= 0);
                    if (exists) break;
                }

                if (!exists) {
                    headElem.append("<link rel='stylesheet' href='" + value + "'>");
                }

                currentTheme = value;
            }
        };

        this.onStartBuffering = function (event) {
            this.isBuffering = true;
            $scope.$apply();
        };

        this.onStartPlaying = function (event) {
            this.isBuffering = false;
            $scope.$apply();
        };

        this.onComplete = function (event) {
            $scope.vgComplete();

            this.setState(VG_STATES.STOP);
            this.isCompleted = true;

            if (isVirtualClip) {
                this.stop()
            }

            $scope.$apply();
        };

        this.onVideoError = function (event) {
            $scope.vgError({$event: event});
        };

        this.addListeners = function () {
            this.mediaElement[0].addEventListener("canplay", this.onCanPlay.bind(this), false);
            this.mediaElement[0].addEventListener("loadedmetadata", this.onLoadMetaData.bind(this), false);
            this.mediaElement[0].addEventListener("waiting", this.onStartBuffering.bind(this), false);
            this.mediaElement[0].addEventListener("ended", this.onComplete.bind(this), false);
            this.mediaElement[0].addEventListener("playing", this.onStartPlaying.bind(this), false);
            this.mediaElement[0].addEventListener("play", this.onPlay.bind(this), false);
            this.mediaElement[0].addEventListener("pause", this.onPause.bind(this), false);
            this.mediaElement[0].addEventListener("volumechange", this.onVolumeChange.bind(this), false);
            this.mediaElement[0].addEventListener("playbackchange", this.onPlaybackChange.bind(this), false);
            this.mediaElement[0].addEventListener("timeupdate", this.onUpdateTime.bind(this), false);
            this.mediaElement[0].addEventListener("progress", this.onProgress.bind(this), false);
            this.mediaElement[0].addEventListener("seeking", this.onSeeking.bind(this), false);
            this.mediaElement[0].addEventListener("seeked", this.onSeeked.bind(this), false);
            this.mediaElement[0].addEventListener("error", this.onVideoError.bind(this), false);
        };

        this.init = function () {
            this.isReady = false;
            this.isCompleted = false;
            this.buffered = [];
            this.bufferEnd = 0;
            this.currentTime = 0;
            this.totalTime = 0;
            this.timeLeft = 0;
            this.isLive = false;
            this.isFullScreen = false;
            this.playback = 1;
            this.isConfig = ($scope.vgConfig != undefined);

            if (vgFullscreen.isAvailable) {
                this.isFullScreen = vgFullscreen.isFullScreen();
            }

            this.updateTheme($scope.vgTheme);
            this.addBindings();

            if (vgFullscreen.isAvailable) {
                document.addEventListener(vgFullscreen.onchange, this.onFullScreenChange.bind(this));
            }
        };

        this.onUpdateTheme = function onUpdateTheme(newValue) {
            this.updateTheme(newValue);
        };

        this.onUpdateAutoPlay = function onUpdateAutoPlay(newValue) {
            if (newValue && !this.autoPlay) {
                this.autoPlay = newValue;
                this.play(this);
            }
        };

        this.onUpdateStartTime = function onUpdateStartTime(newValue) {
            if (newValue && (newValue != this.startTime)) {
                this.mediaElement[0].currentTime = newValue;
                this.startTime = newValue;
                isVirtualClip = this.startTime >= 0 && this.virtualClipDuration > 0;

                var fakeEvent = {
                    target: this.mediaElement[0]
                };
                this.onUpdateTime(fakeEvent, true);
            }
        };

        this.onUpdateVirtualClipDuration = function onUpdateVirtualClipDuration(newValue) {
            if (newValue && (newValue != this.virtualClipDuration)) {
                this.virtualClipDuration = newValue;
                isVirtualClip = this.startTime >= 0 && this.virtualClipDuration > 0;

                var fakeEvent = {
                    target: this.mediaElement[0]
                };
                this.onUpdateTime(fakeEvent, true);
            }
        };

        this.onUpdatePlaysInline = function onUpdatePlaysInline(newValue) {
            this.playsInline = newValue;
        };

        this.onUpdateNativeFullscreen = function onUpdateNativeFullscreen(newValue) {
            if (newValue == undefined) newValue = true;

            this.nativeFullscreen = newValue;
        };

        this.onUpdateCuePoints = function onUpdateCuePoints(newValue) {
            this.cuePoints = newValue;
            this.checkCuePoints(this.currentTime);
        };

        this.onUpdateClearMediaOnNavigate = function onUpdateClearMediaOnNavigate(newValue) {
            this.clearMediaOnNavigate = newValue;
        };

        this.addBindings = function () {
            $scope.$watch("vgTheme", this.onUpdateTheme.bind(this));

            $scope.$watch("vgAutoPlay", this.onUpdateAutoPlay.bind(this));

            $scope.$watch("vgStartTime", this.onUpdateStartTime.bind(this));

            $scope.$watch("vgVirtualClipDuration", this.onUpdateVirtualClipDuration.bind(this));

            $scope.$watch("vgPlaysInline", this.onUpdatePlaysInline.bind(this));

            $scope.$watch("vgNativeFullscreen", this.onUpdateNativeFullscreen.bind(this));

            $scope.$watch("vgCuePoints", this.onUpdateCuePoints.bind(this));

            $scope.$watch("vgClearMediaOnNavigate", this.onUpdateClearMediaOnNavigate.bind(this));
        };

        this.onFullScreenChange = function (event) {
            this.isFullScreen = vgFullscreen.isFullScreen();
            $scope.$apply();
        };

        // Empty mediaElement on destroy to avoid that Chrome downloads video even when it's not present
        $scope.$on('$destroy', this.clearMedia.bind(this));

        // Empty mediaElement when router changes
        $scope.$on('$routeChangeStart', this.onRouteChange.bind(this));

        this.init();
    }]
);

/**
 * @ngdoc directive
 * @name com.2fdevs.videogular.directive:vgCrossorigin
 * @restrict A
 * @description
 * Optional directive for `vg-media` to add or remove a crossorigin policy to the video object. Possible values are: "anonymous" and "use-credentials".
 * This feature should be enabled if you want to have your subtitles or video files on a different domain than the video player. Additionally you need
 * to add CORS policies to your video and track files to your server to make it work.
 *
 */
"use strict";
angular.module("com.2fdevs.videogular")
    .directive("vgCrossorigin",
    [function () {
        return {
            restrict: "A",
            require: "^videogular",
            link: {
                pre: function (scope, elem, attr, API) {
                    var crossorigin;

                    scope.setCrossorigin = function setCrossorigin(value) {
                        if (value) {
                            API.mediaElement.attr("crossorigin", value);
                        }
                        else {
                            API.mediaElement.removeAttr("crossorigin");
                        }
                    };

                    if (API.isConfig) {
                        scope.$watch(
                            function () {
                                return API.config;
                            },
                            function () {
                                if (API.config) {
                                    scope.setCrossorigin(API.config.crossorigin);
                                }
                            }
                        );
                    }
                    else {
                        scope.$watch(attr.vgCrossorigin, function (newValue, oldValue) {
                            if ((!crossorigin || newValue != oldValue) && newValue) {
                                crossorigin = newValue;
                                scope.setCrossorigin(crossorigin);
                            }
                            else {
                                scope.setCrossorigin();
                            }
                        });
                    }
                }
            }
        }
    }
    ]);

/**
 * @ngdoc directive
 * @name com.2fdevs.videogular.directive:vgLoop
 * @restrict A
 * @description
 * Optional directive for `vg-media` to add or remove loop in media files. Possible values are: "true" and "false"
 *
 */
"use strict";
angular.module("com.2fdevs.videogular")
    .directive("vgLoop",
    [function () {
        return {
            restrict: "A",
            require: "^videogular",
            link: {
                pre: function (scope, elem, attr, API) {
                    var loop;

                    scope.setLoop = function setLoop(value) {
                        if (value) {
                            API.mediaElement.attr("loop", value);
                        }
                        else {
                            API.mediaElement.removeAttr("loop");
                        }
                    };

                    if (API.isConfig) {
                        scope.$watch(
                            function () {
                                return API.config;
                            },
                            function () {
                                if (API.config) {
                                    scope.setLoop(API.config.loop);
                                }
                            }
                        );
                    }
                    else {
                        scope.$watch(attr.vgLoop, function (newValue, oldValue) {
                            if ((!loop || newValue != oldValue) && newValue) {
                                loop = newValue;
                                scope.setLoop(loop);
                            }
                            else {
                                scope.setLoop();
                            }
                        });
                    }
                }
            }
        }
    }
    ]);

/**
 * @ngdoc directive
 * @name com.2fdevs.videogular.direcitve:vgMedia
 * @restrict E
 * @description
 * Directive to add a source of videos or audios. This directive will create a &lt;video&gt; or &lt;audio&gt; tag and usually will be above plugin tags.
 *
 * @param {array} vgSrc Bindable array with a list of media sources. A media source is an object with two properties `src` and `type`. The `src` property must contains a trustful url resource.
 * @param {string} vgType String with "video" or "audio" values to set a <video> or <audio> tag inside <vg-media>.
 * <pre>
 * {
 *    src: $sce.trustAsResourceUrl("path/to/video/videogular.mp4"),
 *    type: "video/mp4"
 * }
 * </pre>
 *
 */
"use strict";
angular.module("com.2fdevs.videogular")
    .directive("vgMedia",
    ["$timeout", "VG_UTILS", "VG_STATES", function ($timeout, VG_UTILS, VG_STATES) {
        return {
            restrict: "E",
            require: "^videogular",
            templateUrl: function (elem, attrs) {
                var vgType = attrs.vgType || "video";
                return attrs.vgTemplate || "vg-templates/vg-media-" + vgType;
            },
            scope: {
                vgSrc: "=?",
                vgType: "=?"
            },
            link: function (scope, elem, attrs, API) {
                var sources;

                // what type of media do we want? defaults to 'video'
                if (!attrs.vgType || attrs.vgType === "video") {
                    attrs.vgType = "video";
                }
                else {
                    attrs.vgType = "audio";
                }

                // FUNCTIONS
                scope.onChangeSource = function onChangeSource(newValue, oldValue) {
                    if ((!sources || newValue != oldValue) && newValue) {
                        sources = newValue;

                        if (API.currentState !== VG_STATES.PLAY) {
                            API.currentState = VG_STATES.STOP;
                        }

                        API.sources = sources;
                        scope.changeSource();
                    }
                };

                scope.changeSource = function changeSource() {
                    var canPlay = "";

                    // It's a cool browser
                    if (API.mediaElement[0].canPlayType) {
                        for (var i = 0, l = sources.length; i < l; i++) {
                            canPlay = API.mediaElement[0].canPlayType(sources[i].type);

                            if (canPlay == "maybe" || canPlay == "probably") {
                                API.mediaElement.attr("src", sources[i].src);
                                API.mediaElement.attr("type", sources[i].type);
                                //Trigger vgChangeSource($source) API callback in vgController
                                API.changeSource(sources[i]);
                                break;
                            }
                        }
                    }
                    // It's a crappy browser and it doesn't deserve any respect
                    else {
                        // Get H264 or the first one
                        API.mediaElement.attr("src", sources[0].src);
                        API.mediaElement.attr("type", sources[0].type);
                        //Trigger vgChangeSource($source) API callback in vgController
                        API.changeSource(sources[0]);
                    }

                    // Android 2.3 support: https://github.com/2fdevs/videogular/issues/187
                    if (VG_UTILS.isMobileDevice()) API.mediaElement[0].load();

                    $timeout(function () {
                        if (API.autoPlay && (VG_UTILS.isCordova() || !VG_UTILS.isMobileDevice())) {
                            API.play();
                        }
                    });

                    if (canPlay == "") {
                        API.onVideoError();
                    }
                };

                // INIT
                API.mediaElement = elem.find(attrs.vgType);
                API.sources = scope.vgSrc;

                API.addListeners();
                API.onVideoReady();

                scope.$watch("vgSrc", scope.onChangeSource);
                scope.$watch(
                    function() {
                        return API.sources;
                    },
                    scope.onChangeSource
                );

                scope.$watch(
                    function() {
                        return API.playsInline;
                    },
                    function (newValue, oldValue) {
                        if (newValue) API.mediaElement.attr("webkit-playsinline", "");
                        else API.mediaElement.removeAttr("webkit-playsinline");
                    }
                );


                if (API.isConfig) {
                    scope.$watch(
                        function () {
                            return API.config;
                        },
                        function () {
                            if (API.config) {
                                scope.vgSrc = API.config.sources;
                            }
                        }
                    );
                }
            }
        }
    }
    ]);

/**
 * @ngdoc directive
 * @name com.2fdevs.videogular.directive:vgNativeControls
 * @restrict A
 * @description
 * Optional directive for `vg-media` to add or remove the native controls. Possible values are: "true" and "false"
 *
 */
"use strict";
angular.module("com.2fdevs.videogular")
    .directive("vgNativeControls",
    [function () {
        return {
            restrict: "A",
            require: "^videogular",
            link: {
                pre: function (scope, elem, attr, API) {
                    var controls;

                    scope.setControls = function setControls(value) {
                        if (value) {
                            API.mediaElement.attr("controls", value);
                        }
                        else {
                            API.mediaElement.removeAttr("controls");
                        }
                    };

                    if (API.isConfig) {
                        scope.$watch(
                            function () {
                                return API.config;
                            },
                            function () {
                                if (API.config) {
                                    scope.setControls(API.config.controls);
                                }
                            }
                        );
                    }
                    else {
                        scope.$watch(attr.vgNativeControls, function (newValue, oldValue) {
                            if ((!controls || newValue != oldValue) && newValue) {
                                controls = newValue;
                                scope.setControls(controls);
                            }
                            else {
                                scope.setControls();
                            }
                        });
                    }
                }
            }
        }
    }
    ]);

/**
 * @ngdoc directive
 * @name com.2fdevs.videogular.directive:vgPreload
 * @restrict A
 * @description
 * Optional directive for `vg-media` to preload media files. Possible values are: "auto", "none" and "preload"
 *
 */
"use strict";
angular.module("com.2fdevs.videogular")
    .directive("vgPreload",
    [function () {
        return {
            restrict: "A",
            require: "^videogular",
            link: {
                pre: function (scope, elem, attr, API) {
                    var preload;

                    scope.setPreload = function setPreload(value) {
                        if (value) {
                            API.mediaElement.attr("preload", value);
                        }
                        else {
                            API.mediaElement.removeAttr("preload");
                        }
                    };

                    if (API.isConfig) {
                        scope.$watch(
                            function () {
                                return API.config;
                            },
                            function () {
                                if (API.config) {
                                    scope.setPreload(API.config.preload);
                                }
                            }
                        );
                    }
                    else {
                        scope.$watch(attr.vgPreload, function (newValue, oldValue) {
                            if ((!preload || newValue != oldValue) && newValue) {
                                preload = newValue;
                                scope.setPreload(preload);
                            }
                            else {
                                scope.setPreload();
                            }
                        });
                    }
                }
            }
        }
    }
    ]);

/**
 * @ngdoc directive
 * @name com.2fdevs.videogular.directive:vgTracks
 * @restrict A
 * @description
 * Optional directive for `vg-media` to add a list of tracks.
 *
 * vgTracks Bindable array with a list of subtitles sources. A track source is an object with five properties: src, kind, srclang, label and default.
 * <pre>
 * {
 *    src: "assets/subs/pale-blue-dot.vtt",
 *    kind: "subtitles",
 *    srclang: "en",
 *    label: "English",
 *    default: "true/false"
 * }
 * </pre>
 */
"use strict";
angular.module("com.2fdevs.videogular")
    .directive("vgTracks",
    [function () {
        return {
            restrict: "A",
            require: "^videogular",
            link: {
                pre: function (scope, elem, attr, API) {
                    var isMetaDataLoaded = false;
                    var tracks;
                    var i;
                    var l;

                    scope.onLoadMetaData = function() {
                        isMetaDataLoaded = true;
                        scope.updateTracks();
                    };

                    scope.updateTracks = function() {
                        // Remove previous tracks
                        var oldTracks = API.mediaElement.children();

                        for (i = 0, l = oldTracks.length; i < l; i++) {
                            if (oldTracks[i].remove) {
                                oldTracks[i].remove();
                            }
                        }

                        // Add new tracks
                        if (tracks) {
                            for (i = 0, l = tracks.length; i < l; i++) {
                                var track = document.createElement('track');
                                for (var prop in tracks[i]) {
                                    track[prop] = tracks[i][prop];
                                }

                                track.addEventListener('load', scope.onLoadTrack.bind(scope, track));

                                API.mediaElement[0].appendChild(track);
                            }
                        }
                    };

                    scope.onLoadTrack = function(track) {
                        if (track.default) track.mode = 'showing';
                        else track.mode = 'hidden';

                        for (var i=0, l=API.mediaElement[0].textTracks.length; i<l; i++) {
                            if (track.label == API.mediaElement[0].textTracks[i].label) {
                                if (track.default) {
                                    API.mediaElement[0].textTracks[i].mode = 'showing';
                                }
                                else {
                                    API.mediaElement[0].textTracks[i].mode = 'disabled';
                                }
                            }

                        }

                        track.removeEventListener('load', scope.onLoadTrack.bind(scope, track));
                    };

                    scope.setTracks = function setTracks(value) {
                        // Add tracks to the API to have it available for other plugins (like controls)
                        tracks = value;
                        API.tracks = value;

                        if (isMetaDataLoaded) {
                            scope.updateTracks();
                        }
                        else {
                            API.mediaElement[0].addEventListener("loadedmetadata", scope.onLoadMetaData.bind(scope), false);
                        }
                    };

                    if (API.isConfig) {
                        scope.$watch(
                            function () {
                                return API.config;
                            },
                            function () {
                                if (API.config) {
                                    scope.setTracks(API.config.tracks);
                                }
                            }
                        );
                    }
                    else {
                        scope.$watch(attr.vgTracks, function (newValue, oldValue) {
                            if ((!tracks || newValue != oldValue)) {
                                scope.setTracks(newValue);
                            }
                        }, true);
                    }
                }
            }
        }
    }
    ]);

/**
 * @ngdoc directive
 * @name com.2fdevs.videogular.directive:videogular
 * @restrict E
 * @description
 * Main directive that must wrap a &lt;vg-media&gt; tag and all plugins.
 *
 * &lt;video&gt; tag usually will be above plugin tags, that's because plugins should be in a layer over the &lt;video&gt;.
 *
 * @param {string} vgTheme String with a scope name variable. This directive will inject a CSS link in the header of your page.
 * **This parameter is required.**
 *
 * @param {boolean} [vgPlaysInline=false] vgPlaysInline Boolean value or a String with a scope name variable to use native fullscreen (default) or set fullscreen inside browser (true).
 *
 * @param {boolean} [vgClearMediaOnNavigate=true] vgClearMediaOnNavigate Boolean value or a String with a scope name variable to reset the video player when user navigates.
 *
 * This is useful to allow continuous playback between different routes.
 *
 * @param {boolean} [vgAutoPlay=false] vgAutoPlay Boolean value or a String with a scope name variable to auto start playing video when it is initialized.
 *
 * **This parameter is disabled in mobile devices** because user must click on content to prevent consuming mobile data plans.
 *
 * @param {boolean} [vgStartTime=-1] vgStartTime Number value or a String with a scope name variable to start playing the video at a certain time.
 *
 * @param {boolean} [vgVirtualClipDuration=-1] vgVirtualClipDuration Number value or a String with a scope name variable for a length to limit the video playback to.
 *
 * @param {object} vgCuePoints Bindable object containing a list of timelines with cue points objects. A timeline is an array of objects with the following properties:
 * - `timeLapse` is an object with two properties `start` and `end` representing in seconds the period for this cue points.
 * - `onEnter` callback called when user enters on a cue point. callback(currentTime, timeLapse, params)
 * - `onLeave` callback called when user seeks backwards and leave the current cue point or a completed cue point. callback(currentTime, timeLapse, params)
 * - `onUpdate` callback called when the current time is between timeLapse.start and timeLapse.end. callback(currentTime, timeLapse, params)
 * - `onComplete` callback called when the user seek forward or the current time passes timeLapse.end property. callback(currentTime, timeLapse, params)
 * - `params` an object with values available to receive in the callback..
 *
 * @param {function} vgConfig String with a url to a config file. Config file's must be a JSON file object with the following structure:
 * <pre>
 {
   "controls": false,
   "loop": false,
   "autoplay": false,
   "startTime": -1,
   "virtualClipDuration": -1,
   "preload": "auto",
   "theme": "path/to/videogular.css",
   "sources": [
     {
       "src": "path/to/videogular.mp4",
       "type": "video/mp4"
     },
     {
       "src": "path/to/videogular.webm",
       "type": "video/webm"
     },
     {
       "src": "path/to/videogular.ogg",
       "type": "video/ogg"
     }
   ],
   "tracks": [
     {
       "src": "path/to/pale-blue-dot.vtt",
       "kind": "subtitles",
       "srclang": "en",
       "label": "English",
       "default": ""
     }
   ],
   "plugins": {
     "controls": {
       "autohide": true,
       "autohideTime": 3000
     },
     "poster": {
       "url": "path/to/earth.png"
     },
     "ima-ads": {
       "companion": "companionAd",
       "companionSize": [728, 90],
       "network": "6062",
       "unitPath": "iab_vast_samples",
       "adTagUrl": "http://pubads.g.doubleclick.net/gampad/ads?sz=640x480&iu=%2F3510761%2FadRulesSampleTags&ciu_szs=160x600%2C300x250%2C728x90&cust_params=adrule%3Dpremidpostpodandbumpers&impl=s&gdfp_req=1&env=vp&ad_rule=1&vid=47570401&cmsid=481&output=xml_vast2&unviewed_position_start=1&url=[referrer_url]&correlator=[timestamp]",
       "skipButton": "<div class='skipButton'>skip ad</div>"
     },
     "analytics": {
       "category": "Videogular",
       "label": "Main",
       "events": {
         "ready": true,
         "play": true,
         "pause": true,
         "stop": true,
         "complete": true,
         "progress": 10
       }
     }
   }
 }
 * </pre>
 * @param {function} vgCanPlay Function name in controller's scope to call when video is able to begin playback
 * @param {function} vgComplete Function name in controller's scope to call when video have been completed.
 * @param {function} vgUpdateVolume Function name in controller's scope to call when volume changes. Receives a param with the new volume.
 * @param {function} vgUpdatePlayback Function name in controller's scope to call when playback changes. Receives a param with the new playback rate.
 * @param {function} vgUpdateTime Function name in controller's scope to call when video playback time is updated. Receives two params with current time and duration in milliseconds.
 * @param {function} vgUpdateState Function name in controller's scope to call when video state changes. Receives a param with the new state. Possible values are "play", "stop" or "pause".
 * @param {function} vgPlayerReady Function name in controller's scope to call when video have been initialized. Receives a param with the videogular API.
 * @param {function} vgChangeSource Function name in controller's scope to change current video source. Receives a param with the new video.
 * @param {function} vgPlaysInline Boolean to play video inline. Generally used in mobile devices.
 * @param {function} vgNativeFullscreen Boolean to disable native fullscreen.
 * @param {function} vgSeeking Function name in controller's scope to call when the video has finished jumping to a new time. Receives a param with the seeked time and duration in seconds.
 * @param {function} vgSeeked Function name in controller's scope to call when the video is jumping to a new time. Receives two params with the seeked time and duration in seconds.
 * @param {function} vgError Function name in controller's scope to receive an error from video object. Receives a param with the error event.
 * This is a free parameter and it could be values like "new.mp4", "320" or "sd". This will allow you to use this to change a video or video quality.
 * This callback will not change the video, you should do that by updating your sources scope variable.
 *
 */
"use strict";
angular.module("com.2fdevs.videogular")
    .directive("videogular",
    [function () {
        return {
            restrict: "EA",
            scope: {
                vgTheme: "=?",
                vgAutoPlay: "=?",
                vgStartTime: "=?",
                vgVirtualClipDuration: "=?",
                vgPlaysInline: "=?",
                vgNativeFullscreen: "=?",
                vgClearMediaOnNavigate: "=?",
                vgCuePoints: "=?",
                vgConfig: "@",
                vgCanPlay: "&",
                vgComplete: "&",
                vgUpdateVolume: "&",
                vgUpdatePlayback: "&",
                vgUpdateTime: "&",
                vgUpdateState: "&",
                vgPlayerReady: "&",
                vgChangeSource: "&",
                vgSeeking: "&",
                vgSeeked: "&",
                vgError: "&"
            },
            controller: "vgController",
            controllerAs: "API",
            link: {
                pre: function (scope, elem, attr, controller) {
                    controller.videogularElement = angular.element(elem);
                }
            }
        }
    }
    ]);

/**
 * @ngdoc service
 * @name com.2fdevs.videogular.service:vgConfigLoader
 *
 * @description
 * Config loader service:
 *
 * vgConfigLoader.loadConfig(url): Param `url` is a url to a config JSON.
 **/
"use strict";
angular.module("com.2fdevs.videogular")
    .service("vgConfigLoader", ["$http", "$q", "$sce", function ($http, $q, $sce) {
        this.loadConfig = function loadConfig(url) {
            var deferred = $q.defer();

            $http({method: 'GET', url: url}).then(
                function success(response) {
                    var result = response.data;

                    for (var i = 0, l = result.sources.length; i < l; i++) {
                        result.sources[i].src = $sce.trustAsResourceUrl(result.sources[i].src);
                    }

                    deferred.resolve(result);
                },
                function reject() {
                    deferred.reject();
                }
            );

            return deferred.promise;
        };
    }]);

/**
 * @ngdoc service
 * @name com.2fdevs.videogular.service:vgFullscreen
 *
 * @description
 * Native fullscreen polyfill service.
 *
 *    * vgFullscreen.onchange: String with the onchange event name.
 *    * vgFullscreen.onerror: String with the onerror event name.
 *    * vgFullscreen.isAvailable: Boolean with fullscreen availability.
 *    * vgFullscreen.isFullScreen: Boolean with current view mode.
 *    * vgFullscreen.exit: Exit fullscreen function.
 *    * vgFullscreen.request: Request for fullscreen access function.
 **/
"use strict";
angular.module("com.2fdevs.videogular")
    .service("vgFullscreen", ["VG_UTILS", function (VG_UTILS) {
        // Native fullscreen polyfill
        var element;
        var polyfill = null;
        var APIs = {
            w3: {
                enabled: "fullscreenEnabled",
                element: "fullscreenElement",
                request: "requestFullscreen",
                exit: "exitFullscreen",
                onchange: "fullscreenchange",
                onerror: "fullscreenerror"
            },
            newWebkit: {
                enabled: "webkitFullscreenEnabled",
                element: "webkitFullscreenElement",
                request: "webkitRequestFullscreen",
                exit: "webkitExitFullscreen",
                onchange: "webkitfullscreenchange",
                onerror: "webkitfullscreenerror"
            },
            oldWebkit: {
                enabled: "webkitIsFullScreen",
                element: "webkitCurrentFullScreenElement",
                request: "webkitRequestFullScreen",
                exit: "webkitCancelFullScreen",
                onchange: "webkitfullscreenchange",
                onerror: "webkitfullscreenerror"
            },
            moz: {
                enabled: "mozFullScreen",
                element: "mozFullScreenElement",
                request: "mozRequestFullScreen",
                exit: "mozCancelFullScreen",
                onchange: "mozfullscreenchange",
                onerror: "mozfullscreenerror"
            },
            ios: {
                enabled: "webkitFullscreenEnabled",
                element: "webkitFullscreenElement",
                request: "webkitEnterFullscreen",
                exit: "webkitExitFullscreen",
                onchange: "webkitfullscreenchange",
                onerror: "webkitfullscreenerror"
            },
            ms: {
                enabled: "msFullscreenEnabled",
                element: "msFullscreenElement",
                request: "msRequestFullscreen",
                exit: "msExitFullscreen",
                onchange: "MSFullscreenChange",
                onerror: "MSFullscreenError"
            }
        };

        for (var browser in APIs) {
            if (APIs[browser].enabled in document) {
                polyfill = APIs[browser];
                break;
            }
        }

        // Override APIs on iOS
        if (VG_UTILS.isiOSDevice()) {
            polyfill = APIs.ios;
        }

        function isFullScreen() {
            var result = false;

            if (element) {
                result = (document[polyfill.element] != null || element.webkitDisplayingFullscreen)
            }
            else {
                result = (document[polyfill.element] != null)
            }

            return result;
        }

        this.isAvailable = (polyfill != null);

        if (polyfill) {
            this.onchange = polyfill.onchange;
            this.onerror = polyfill.onerror;
            this.isFullScreen = isFullScreen;
            this.exit = function () {
                document[polyfill.exit]();
            };
            this.request = function (elem) {
                element = elem;
                element[polyfill.request]();
            };
        }
    }]);

"use strict";
angular.module("com.2fdevs.videogular")
    .service("VG_UTILS", ["$window", function ($window) {
        this.fixEventOffset = function ($event) {
            /**
             * There's no offsetX in Firefox, so we fix that.
             * Solution provided by Jack Moore in this post:
             * http://www.jacklmoore.com/notes/mouse-position/
             * @param $event
             * @returns {*}
             */
            var matchedFF = navigator.userAgent.match(/Firefox\/(\d+)/i)
            if (matchedFF && Number.parseInt(matchedFF.pop()) < 39) {
                var style = $event.currentTarget.currentStyle || window.getComputedStyle($event.target, null);
                var borderLeftWidth = parseInt(style['borderLeftWidth'], 10);
                var borderTopWidth = parseInt(style['borderTopWidth'], 10);
                var rect = $event.currentTarget.getBoundingClientRect();
                var offsetX = $event.clientX - borderLeftWidth - rect.left;
                var offsetY = $event.clientY - borderTopWidth - rect.top;

                $event.offsetX = offsetX;
                $event.offsetY = offsetY;
            }

            return $event;
        };

        /**
         * Inspired by Paul Irish
         * https://gist.github.com/paulirish/211209
         * @returns {number}
         */
        this.getZIndex = function () {
            var zIndex = 1;
            var elementZIndex;

            var tags = document.getElementsByTagName('*');

            for (var i = 0, l = tags.length; i < l; i++) {
                elementZIndex = parseInt(window.getComputedStyle(tags[i])["z-index"]);

                if (elementZIndex > zIndex) {
                    zIndex = elementZIndex + 1;
                }
            }

            return zIndex;
        };

        // Very simple mobile detection, not 100% reliable
        this.isMobileDevice = function () {
            return (typeof window.orientation !== "undefined") || (navigator.userAgent.indexOf("IEMobile") !== -1);
        };

        this.isiOSDevice = function () {
            return (navigator.userAgent.match(/ip(hone|ad|od)/i) && !navigator.userAgent.match(/(iemobile)[\/\s]?([\w\.]*)/i));
        };

        this.isCordova = function () {
            return document.URL.indexOf('http://') === -1 && document.URL.indexOf('https://') === -1;
        };

        /**
         * Test the browser's support for HTML5 localStorage.
         * @returns {boolean}
         */
        this.supportsLocalStorage = function () {
            var testKey = 'videogular-test-key';
            var storage = $window.sessionStorage;

            try {
                storage.setItem(testKey, '1');
                storage.removeItem(testKey);
                return 'localStorage' in $window && $window['localStorage'] !== null;
            } catch (e) {
                return false;
            }
        };
    }]);