• Ozzieisaacs's avatar
    Merge branch 'Develop' · 4708347c
    Ozzieisaacs authored
    # Conflicts:
    #	MANIFEST.in
    #	README.md
    #	cps/helper.py
    #	cps/static/js/archive/archive.js
    #	cps/translations/nl/LC_MESSAGES/messages.mo
    #	cps/translations/nl/LC_MESSAGES/messages.po
    #	cps/ub.py
    #	cps/updater.py
    #	cps/web.py
    #	cps/worker.py
    #	optional-requirements.txt
    4708347c
bar-ui.js 41.8 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 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
(function (window) {

  /**
   * SoundManager 2: "Bar UI" player
   * Copyright (c) 2014, Scott Schiller. All rights reserved.
   * http://www.schillmania.com/projects/soundmanager2/
   * Code provided under BSD license.
   * http://schillmania.com/projects/soundmanager2/license.txt
   */

  /* global console, document, navigator, soundManager, window */

  'use strict';

  var Player,
    players = [],
    // CSS selector that will get us the top-level DOM node for the player UI.
    playerSelector = '.sm2-bar-ui',
    playerOptions,
    utils;

  /**
   * The following are player object event callback examples.
   * Override globally by setting window.sm2BarPlayers.on = {}, or individually by window.sm2BarPlayers[0].on = {} etc.
   * soundObject is provided for whileplaying() etc., but playback control should be done via the player object.
   */
  players.on = {
    /*
    play: function(player, soundObject) {
      console.log('playing', player);
    },
    whileplaying: function(player, soundObject) {
      console.log('whileplaying', player, soundObject);
    },
    finish: function(player, soundObject) {
      // each sound
      console.log('finish', player);
    },
    pause: function(player, soundObject) {
      console.log('pause', player);
    },
    error: function(player, soundObject) {
      console.log('error', player);
    },
    end: function(player, soundObject) {
      // end of playlist
      console.log('end', player);
    }
    */
  };

  playerOptions = {
    // useful when multiple players are in use, or other SM2 sounds are active etc.
    stopOtherSounds: true,
    // CSS class to let the browser load the URL directly e.g., <a href="foo.mp3" class="sm2-exclude">download foo.mp3</a>
    excludeClass: 'sm2-exclude'
  };

  soundManager.setup({
    // trade-off: higher UI responsiveness (play/progress bar), but may use more CPU.
    html5PollingInterval: 50,
    flashVersion: 9
  });

  soundManager.onready(function () {

    var nodes, i, j;

    nodes = utils.dom.getAll(playerSelector);

    if (nodes && nodes.length) {
      for (i = 0, j = nodes.length; i < j; i++) {
        players.push(new Player(nodes[i]));
      }
    }

  });

  /**
   * player bits
   */

  Player = function (playerNode) {

    var css, dom, extras, playlistController, soundObject, actions, actionData, defaultItem, defaultVolume, firstOpen, exports;

    css = {
      disabled: 'disabled',
      selected: 'selected',
      active: 'active',
      legacy: 'legacy',
      noVolume: 'no-volume',
      playlistOpen: 'playlist-open'
    };

    dom = {
      o: null,
      playlist: null,
      playlistTarget: null,
      playlistContainer: null,
      time: null,
      player: null,
      progress: null,
      progressTrack: null,
      progressBar: null,
      duration: null,
      volume: null
    };

    // prepended to tracks when a sound fails to load/play
    extras = {
      loadFailedCharacter: '<span title="Failed to load/play." class="load-error">✖</span>'
    };

    function stopOtherSounds() {

      if (playerOptions.stopOtherSounds) {
        soundManager.stopAll();
      }

    }

    function callback(method, oSound) {
      if (method) {
        // fire callback, passing current player and sound objects
        if (exports.on && exports.on[method]) {
          exports.on[method](exports, oSound);
        } else if (players.on[method]) {
          players.on[method](exports, oSound);
        }
      }
    }

    function getTime(msec, useString) {

      // convert milliseconds to hh:mm:ss, return as object literal or string

      var nSec = Math.floor(msec / 1000),
        hh = Math.floor(nSec / 3600),
        min = Math.floor(nSec / 60) - Math.floor(hh * 60),
        sec = Math.floor(nSec - (hh * 3600) - (min * 60));

      // if (min === 0 && sec === 0) return null; // return 0:00 as null

      return (useString ? ((hh ? hh + ':' : '') + (hh && min < 10 ? '0' + min : min) + ':' + (sec < 10 ? '0' + sec : sec)) : { min: min, sec: sec });

    }

    function setTitle(item) {

      // given a link, update the "now playing" UI.

      // if this is an <li> with an inner link, grab and use the text from that.
      var links = item.getElementsByTagName('a');

      if (links.length) {
        item = links[0];
      }

      // remove any failed character sequence, also
      dom.playlistTarget.innerHTML = '<ul class="sm2-playlist-bd"><li>' + item.innerHTML.replace(extras.loadFailedCharacter, '') + '</li></ul>';

      if (dom.playlistTarget.getElementsByTagName('li')[0].scrollWidth > dom.playlistTarget.offsetWidth) {
        // this item can use <marquee>, in fact.
        dom.playlistTarget.innerHTML = '<ul class="sm2-playlist-bd"><li><marquee>' + item.innerHTML + '</marquee></li></ul>';
      }

    }

    function makeSound(url) {

      var sound = soundManager.createSound({

        url: url,

        volume: defaultVolume,

        whileplaying: function () {


          //This sends a bookmark update to calibreweb every 30 seconds.
          if (this.progressBuffer == undefined) {
            this.progressBuffer = 0;
          }

          if (this.progressBuffer <= this.position) {

            $.ajax(calibre.bookmarkUrl, {
              method: "post",
              data: { bookmark: this.position }
            }).fail(function (xhr, status, error) {
              console.error(error);
            });

            this.progressBuffer = this.progressBuffer + 30000;
          }

          var progressMaxLeft = 100,
            left,
            width;

          left = Math.min(progressMaxLeft, Math.max(0, (progressMaxLeft * (this.position / this.durationEstimate)))) + '%';
          width = Math.min(100, Math.max(0, (100 * (this.position / this.durationEstimate)))) + '%';

          if (this.duration) {

            dom.progress.style.left = left;
            dom.progressBar.style.width = width;

            // TODO: only write changes
            dom.time.innerHTML = getTime(this.position, true);

          }

          callback('whileplaying', this);

        },

        onbufferchange: function (isBuffering) {

          if (isBuffering) {
            utils.css.add(dom.o, 'buffering');
          } else {
            utils.css.remove(dom.o, 'buffering');
          }

        },

        onplay: function () {
          utils.css.swap(dom.o, 'paused', 'playing');
          callback('play', this);
        },

        onpause: function () {

          $.ajax(calibre.bookmarkUrl, {
            method: "post",
            data: { bookmark: this.position }
          }).fail(function (xhr, status, error) {
            console.error(error);
          });

          utils.css.swap(dom.o, 'playing', 'paused');
          callback('pause', this);
        },

        onresume: function () {
          utils.css.swap(dom.o, 'paused', 'playing');
        },

        whileloading: function () {

          if (!this.isHTML5) {
            dom.duration.innerHTML = getTime(this.durationEstimate, true);
          }

        },

        onload: function (ok) {

          sound.setPosition(calibre.bookmark);

          if (ok) {
            dom.duration.innerHTML = getTime(this.duration, true);

          } else if (this._iO && this._iO.onerror) {

            this._iO.onerror();

          }

        },

        onerror: function () {

          // sound failed to load.
          var item, element, html;

          item = playlistController.getItem();

          if (item) {

            // note error, delay 2 seconds and advance?
            // playlistTarget.innerHTML = '<ul class="sm2-playlist-bd"><li>' + item.innerHTML + '</li></ul>';

            if (extras.loadFailedCharacter) {
              dom.playlistTarget.innerHTML = dom.playlistTarget.innerHTML.replace('<li>', '<li>' + extras.loadFailedCharacter + ' ');
              if (playlistController.data.playlist && playlistController.data.playlist[playlistController.data.selectedIndex]) {
                element = playlistController.data.playlist[playlistController.data.selectedIndex].getElementsByTagName('a')[0];
                html = element.innerHTML;
                if (html.indexOf(extras.loadFailedCharacter) === -1) {
                  element.innerHTML = extras.loadFailedCharacter + ' ' + html;
                }
              }
            }

          }

          callback('error', this);

          // load next, possibly with delay.

          if (navigator.userAgent.match(/mobile/i)) {
            // mobile will likely block the next play() call if there is a setTimeout() - so don't use one here.
            actions.next();
          } else {
            if (playlistController.data.timer) {
              window.clearTimeout(playlistController.data.timer);
            }
            playlistController.data.timer = window.setTimeout(actions.next, 2000);
          }

        },

        onstop: function () {
          
          $.ajax(calibre.bookmarkUrl, {
            method: "post",
            data: { bookmark: this.position }
          }).fail(function (xhr, status, error) {
            console.error(error);
          });
        
          utils.css.remove(dom.o, 'playing');

        },

        onfinish: function () {

          $.ajax(calibre.bookmarkUrl, {
            method: "post",
            data: { bookmark: this.position }
          }).fail(function (xhr, status, error) {
            console.error(error);
          });

          var lastIndex, item;

          utils.css.remove(dom.o, 'playing');

          dom.progress.style.left = '0%';

          lastIndex = playlistController.data.selectedIndex;

          callback('finish', this);

          // next track?
          item = playlistController.getNext();

          // don't play the same item over and over again, if at end of playlist (excluding single item case.)
          if (item && (playlistController.data.selectedIndex !== lastIndex || (playlistController.data.playlist.length === 1 && playlistController.data.loopMode))) {

            playlistController.select(item);

            setTitle(item);

            stopOtherSounds();

            // play next
            this.play({
              url: playlistController.getURL()
            });

          } else {

            // end of playlist case

            // explicitly stop?
            // this.stop();

            callback('end', this);

          }

        }

      });

      return sound;

    }

    function playLink(link) {

      // if a link is OK, play it.

      if (soundManager.canPlayURL(link.href)) {

        // if there's a timer due to failure to play one track, cancel it.
        // catches case when user may use previous/next after an error.
        if (playlistController.data.timer) {
          window.clearTimeout(playlistController.data.timer);
          playlistController.data.timer = null;
        }

        if (!soundObject) {
          soundObject = makeSound(link.href);
        }

        // required to reset pause/play state on iOS so whileplaying() works? odd.
        soundObject.stop();

        playlistController.select(link.parentNode);

        setTitle(link.parentNode);

        // reset the UI
        // TODO: function that also resets/hides timing info.
        dom.progress.style.left = '0px';
        dom.progressBar.style.width = '0px';

        stopOtherSounds();

        soundObject.play({
          url: link.href,
          position: 0
        });

      }

    }

    function PlaylistController() {

      var data;

      data = {

        // list of nodes?
        playlist: [],

        // NOTE: not implemented yet.
        // shuffledIndex: [],
        // shuffleMode: false,

        // selection
        selectedIndex: 0,

        loopMode: false,

        timer: null

      };

      function getPlaylist() {

        return data.playlist;

      }

      function getItem(offset) {

        var list,
          item;

        // given the current selection (or an offset), return the current item.

        // if currently null, may be end of list case. bail.
        if (data.selectedIndex === null) {
          return offset;
        }

        list = getPlaylist();

        // use offset if provided, otherwise take default selected.
        offset = (offset !== undefined ? offset : data.selectedIndex);

        // safety check - limit to between 0 and list length
        offset = Math.max(0, Math.min(offset, list.length));

        item = list[offset];

        return item;

      }

      function findOffsetFromItem(item) {

        // given an <li> item, find it in the playlist array and return the index.
        var list,
          i,
          j,
          offset;

        offset = -1;

        list = getPlaylist();

        if (list) {

          for (i = 0, j = list.length; i < j; i++) {
            if (list[i] === item) {
              offset = i;
              break;
            }
          }

        }

        return offset;

      }

      function getNext() {

        // don't increment if null.
        if (data.selectedIndex !== null) {
          data.selectedIndex++;
        }

        if (data.playlist.length > 1) {

          if (data.selectedIndex >= data.playlist.length) {

            if (data.loopMode) {

              // loop to beginning
              data.selectedIndex = 0;

            } else {

              // no change
              data.selectedIndex--;

              // end playback
              // data.selectedIndex = null;

            }

          }

        } else {

          data.selectedIndex = null;

        }

        return getItem();

      }

      function getPrevious() {

        data.selectedIndex--;

        if (data.selectedIndex < 0) {
          // wrapping around beginning of list? loop or exit.
          if (data.loopMode) {
            data.selectedIndex = data.playlist.length - 1;
          } else {
            // undo
            data.selectedIndex++;
          }
        }

        return getItem();

      }

      function resetLastSelected() {

        // remove UI highlight(s) on selected items.
        var items,
          i, j;

        items = utils.dom.getAll(dom.playlist, '.' + css.selected);

        for (i = 0, j = items.length; i < j; i++) {
          utils.css.remove(items[i], css.selected);
        }

      }

      function select(item) {

        var offset,
          itemTop,
          itemBottom,
          containerHeight,
          scrollTop,
          itemPadding,
          liElement;

        // remove last selected, if any
        resetLastSelected();

        if (item) {

          liElement = utils.dom.ancestor('li', item);

          utils.css.add(liElement, css.selected);

          itemTop = item.offsetTop;
          itemBottom = itemTop + item.offsetHeight;
          containerHeight = dom.playlistContainer.offsetHeight;
          scrollTop = dom.playlist.scrollTop;
          itemPadding = 8;

          if (itemBottom > containerHeight + scrollTop) {
            // bottom-align
            dom.playlist.scrollTop = (itemBottom - containerHeight) + itemPadding;
          } else if (itemTop < scrollTop) {
            // top-align
            dom.playlist.scrollTop = item.offsetTop - itemPadding;
          }

        }

        // update selected offset, too.
        offset = findOffsetFromItem(liElement);

        data.selectedIndex = offset;

      }

      function playItemByOffset(offset) {

        var item;

        offset = (offset || 0);

        item = getItem(offset);

        if (item) {
          playLink(item.getElementsByTagName('a')[0]);
        }

      }

      function getURL() {

        // return URL of currently-selected item
        var item, url;

        item = getItem();

        if (item) {
          url = item.getElementsByTagName('a')[0].href;
        }

        return url;

      }

      function refreshDOM() {

        // get / update playlist from DOM

        if (!dom.playlist) {
          if (window.console && console.warn) {
            console.warn('refreshDOM(): playlist node not found?');
          }
          return;
        }

        data.playlist = dom.playlist.getElementsByTagName('li');

      }

      function initDOM() {

        dom.playlistTarget = utils.dom.get(dom.o, '.sm2-playlist-target');
        dom.playlistContainer = utils.dom.get(dom.o, '.sm2-playlist-drawer');
        dom.playlist = utils.dom.get(dom.o, '.sm2-playlist-bd');

      }

      function initPlaylistController() {

        // inherit the default SM2 volume
        defaultVolume = soundManager.defaultOptions.volume;

        initDOM();
        refreshDOM();

        // animate playlist open, if HTML classname indicates so.
        if (utils.css.has(dom.o, css.playlistOpen)) {
          // hackish: run this after API has returned
          window.setTimeout(function () {
            actions.menu(true);
          }, 1);
        }

      }

      initPlaylistController();

      return {
        data: data,
        refresh: refreshDOM,
        getNext: getNext,
        getPrevious: getPrevious,
        getItem: getItem,
        getURL: getURL,
        playItemByOffset: playItemByOffset,
        select: select
      };

    }

    function isRightClick(e) {

      // only pay attention to left clicks. old IE differs where there's no e.which, but e.button is 1 on left click.
      if (e && ((e.which && e.which === 2) || (e.which === undefined && e.button !== 1))) {
        // http://www.quirksmode.org/js/events_properties.html#button
        return true;
      }

      return false;

    }

    function getActionData(target) {

      // DOM measurements for volume slider

      if (!target) {
        return;
      }

      actionData.volume.x = utils.position.getOffX(target);
      actionData.volume.y = utils.position.getOffY(target);

      actionData.volume.width = target.offsetWidth;
      actionData.volume.height = target.offsetHeight;

      // potentially dangerous: this should, but may not be a percentage-based value.
      actionData.volume.backgroundSize = parseInt(utils.style.get(target, 'background-size'), 10);

      // IE gives pixels even if background-size specified as % in CSS. Boourns.
      if (window.navigator.userAgent.match(/msie|trident/i)) {
        actionData.volume.backgroundSize = (actionData.volume.backgroundSize / actionData.volume.width) * 100;
      }

    }

    function handleMouseDown(e) {

      var links,
        target;

      target = e.target || e.srcElement;

      if (isRightClick(e)) {
        return;
      }

      // normalize to <a>, if applicable.
      if (target.nodeName.toLowerCase() !== 'a') {

        links = target.getElementsByTagName('a');
        if (links && links.length) {
          target = target.getElementsByTagName('a')[0];
        }

      }

      if (utils.css.has(target, 'sm2-volume-control')) {

        // drag case for volume

        getActionData(target);

        utils.events.add(document, 'mousemove', actions.adjustVolume);
        utils.events.add(document, 'touchmove', actions.adjustVolume);
        utils.events.add(document, 'mouseup', actions.releaseVolume);
        utils.events.add(document, 'touchend', actions.releaseVolume);

        // and apply right away
        actions.adjustVolume(e);

      }

    }

    function handleMouse(e) {

      var target, barX, barWidth, x, clientX, newPosition, sound;

      target = dom.progressTrack;

      barX = utils.position.getOffX(target);
      barWidth = target.offsetWidth;
      clientX = utils.events.getClientX(e);

      x = (clientX - barX);

      newPosition = (x / barWidth);

      sound = soundObject;

      if (sound && sound.duration) {

        sound.setPosition(sound.duration * newPosition);

        // a little hackish: ensure UI updates immediately with current position, even if audio is buffering and hasn't moved there yet.
        if (sound._iO && sound._iO.whileplaying) {
          sound._iO.whileplaying.apply(sound);
        }

      }

      if (e.preventDefault) {
        e.preventDefault();
      }

      return false;

    }

    function releaseMouse(e) {

      utils.events.remove(document, 'mousemove', handleMouse);
      utils.events.remove(document, 'touchmove', handleMouse);

      utils.css.remove(dom.o, 'grabbing');

      utils.events.remove(document, 'mouseup', releaseMouse);
      utils.events.remove(document, 'touchend', releaseMouse);

      utils.events.preventDefault(e);

      return false;

    }

    function handleProgressMouseDown(e) {

      if (isRightClick(e)) {
        return;
      }

      utils.css.add(dom.o, 'grabbing');

      utils.events.add(document, 'mousemove', handleMouse);
      utils.events.add(document, 'touchmove', handleMouse);
      utils.events.add(document, 'mouseup', releaseMouse);
      utils.events.add(document, 'touchend', releaseMouse);

      handleMouse(e);

    }

    function handleClick(e) {

      var evt,
        target,
        offset,
        targetNodeName,
        methodName,
        href,
        handled;

      evt = (e || window.event);

      target = evt.target || evt.srcElement;

      if (target && target.nodeName) {

        targetNodeName = target.nodeName.toLowerCase();

        if (targetNodeName !== 'a') {

          // old IE (IE 8) might return nested elements inside the <a>, eg., <b> etc. Try to find the parent <a>.

          if (target.parentNode) {

            do {
              target = target.parentNode;
              targetNodeName = target.nodeName.toLowerCase();
            } while (targetNodeName !== 'a' && target.parentNode);

            if (!target) {
              // something went wrong. bail.
              return false;
            }

          }

        }

        if (targetNodeName === 'a') {

          // yep, it's a link.

          href = target.href;

          if (soundManager.canPlayURL(href)) {

            // not excluded
            if (!utils.css.has(target, playerOptions.excludeClass)) {

              // find this in the playlist

              playLink(target);

              handled = true;

            }

          } else {

            // is this one of the action buttons, eg., play/pause, volume, etc.?
            offset = target.href.lastIndexOf('#');

            if (offset !== -1) {

              methodName = target.href.substr(offset + 1);

              if (methodName && actions[methodName]) {
                handled = true;
                actions[methodName](e);
              }

            }

          }

          // fall-through case

          if (handled) {
            // prevent browser fall-through
            return utils.events.preventDefault(evt);
          }

        }

      }

      return true;

    }

    function init() {

      // init DOM?

      if (!playerNode && window.console && console.warn) {
        console.warn('init(): No playerNode element?');
      }

      dom.o = playerNode;

      // are we dealing with a crap browser? apply legacy CSS if so.
      if (window.navigator.userAgent.match(/msie [678]/i)) {
        utils.css.add(dom.o, css.legacy);
      }

      if (window.navigator.userAgent.match(/mobile/i)) {
        // majority of mobile devices don't let HTML5 audio set volume.
        utils.css.add(dom.o, css.noVolume);
      }

      dom.progress = utils.dom.get(dom.o, '.sm2-progress-ball');

      dom.progressTrack = utils.dom.get(dom.o, '.sm2-progress-track');

      dom.progressBar = utils.dom.get(dom.o, '.sm2-progress-bar');

      dom.volume = utils.dom.get(dom.o, 'a.sm2-volume-control');

      // measure volume control dimensions
      if (dom.volume) {
        getActionData(dom.volume);
      }

      dom.duration = utils.dom.get(dom.o, '.sm2-inline-duration');

      dom.time = utils.dom.get(dom.o, '.sm2-inline-time');

      playlistController = new PlaylistController();

      defaultItem = playlistController.getItem(0);

      playlistController.select(defaultItem);

      if (defaultItem) {
        setTitle(defaultItem);
      }

      utils.events.add(dom.o, 'mousedown', handleMouseDown);
      utils.events.add(dom.o, 'touchstart', handleMouseDown);
      utils.events.add(dom.o, 'click', handleClick);
      utils.events.add(dom.progressTrack, 'mousedown', handleProgressMouseDown);
      utils.events.add(dom.progressTrack, 'touchstart', handleProgressMouseDown);

    }

    // ---

    actionData = {

      volume: {
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        backgroundSize: 0
      }

    };

    actions = {

      play: function (offsetOrEvent) {

        /**
         * This is an overloaded function that takes mouse/touch events or offset-based item indices.
         * Remember, "auto-play" will not work on mobile devices unless this function is called immediately from a touch or click event.
         * If you have the link but not the offset, you can also pass a fake event object with a target of an <a> inside the playlist - e.g. { target: someMP3Link }
         */

        var target,
          href,
          e;

        if (offsetOrEvent !== undefined && !isNaN(offsetOrEvent)) {
          // smells like a number.
          playlistController.playItemByOffset(offsetOrEvent);
          return;
        }

        // DRY things a bit
        e = offsetOrEvent;

        if (e && e.target) {

          target = e.target || e.srcElement;

          href = target.href;

        }

        // haaaack - if null due to no event, OR '#' due to play/pause link, get first link from playlist
        if (!href || href.indexOf('#') !== -1) {
          href = dom.playlist.getElementsByTagName('a')[0].href;
        }

        if (!soundObject) {
          soundObject = makeSound(href);
        }

        // edge case: if the current sound is not playing, stop all others.
        if (!soundObject.playState) {
          stopOtherSounds();
        }

        // TODO: if user pauses + unpauses a sound that had an error, try to play next?
        soundObject.togglePause();

        // special case: clear "play next" timeout, if one exists.
        // edge case: user pauses after a song failed to load.
        if (soundObject.paused && playlistController.data.timer) {
          window.clearTimeout(playlistController.data.timer);
          playlistController.data.timer = null;
        }

      },

      pause: function () {

        if (soundObject && soundObject.readyState) {
          soundObject.pause();
        }

      },

      resume: function () {

        if (soundObject && soundObject.readyState) {
          soundObject.resume();
        }

      },

      stop: function () {

        // just an alias for pause, really.
        // don't actually stop because that will mess up some UI state, i.e., dragging the slider.
        return actions.pause();

      },

      next: function (/* e */) {

        var item, lastIndex;

        // special case: clear "play next" timeout, if one exists.
        if (playlistController.data.timer) {
          window.clearTimeout(playlistController.data.timer);
          playlistController.data.timer = null;
        }

        lastIndex = playlistController.data.selectedIndex;

        item = playlistController.getNext(true);

        // don't play the same item again
        if (item && playlistController.data.selectedIndex !== lastIndex) {
          playLink(item.getElementsByTagName('a')[0]);
        }

      },

      prev: function (/* e */) {

        var item, lastIndex;

        lastIndex = playlistController.data.selectedIndex;

        item = playlistController.getPrevious();

        // don't play the same item again
        if (item && playlistController.data.selectedIndex !== lastIndex) {
          playLink(item.getElementsByTagName('a')[0]);
        }

      },

      shuffle: function (e) {

        // NOTE: not implemented yet.

        var target = (e ? e.target || e.srcElement : utils.dom.get(dom.o, '.shuffle'));

        if (target && !utils.css.has(target, css.disabled)) {
          utils.css.toggle(target.parentNode, css.active);
          playlistController.data.shuffleMode = !playlistController.data.shuffleMode;
        }

      },

      repeat: function (e) {

        var target = (e ? e.target || e.srcElement : utils.dom.get(dom.o, '.repeat'));

        if (target && !utils.css.has(target, css.disabled)) {
          utils.css.toggle(target.parentNode, css.active);
          playlistController.data.loopMode = !playlistController.data.loopMode;
        }

      },

      menu: function (ignoreToggle) {

        var isOpen;

        isOpen = utils.css.has(dom.o, css.playlistOpen);

        // hackish: reset scrollTop in default first open case. odd, but some browsers have a non-zero scroll offset the first time the playlist opens.
        if (playlistController && !playlistController.data.selectedIndex && !firstOpen) {
          dom.playlist.scrollTop = 0;
          firstOpen = true;
        }

        // sniff out booleans from mouse events, as this is referenced directly by event handlers.
        if (typeof ignoreToggle !== 'boolean' || !ignoreToggle) {

          if (!isOpen) {
            // explicitly set height:0, so the first closed -> open animation runs properly
            dom.playlistContainer.style.height = '0px';
          }

          isOpen = utils.css.toggle(dom.o, css.playlistOpen);

        }

        // playlist
        dom.playlistContainer.style.height = (isOpen ? dom.playlistContainer.scrollHeight : 0) + 'px';

      },

      adjustVolume: function (e) {

        /**
         * NOTE: this is the mousemove() event handler version.
         * Use setVolume(50), etc., to assign volume directly.
         */

        var backgroundMargin,
          pixelMargin,
          target,
          value,
          volume;

        value = 0;

        target = dom.volume;

        // safety net
        if (e === undefined) {
          return false;
        }

        // normalize between mouse and touch events
        var clientX = utils.events.getClientX(e);

        if (!e || clientX === undefined) {
          // called directly or with a non-mouseEvent object, etc.
          // proxy to the proper method.
          if (arguments.length && window.console && window.console.warn) {
            console.warn('Bar UI: call setVolume(' + e + ') instead of adjustVolume(' + e + ').');
          }
          return actions.setVolume.apply(this, arguments);
        }

        // based on getStyle() result
        // figure out spacing around background image based on background size, eg. 60% background size.
        // 60% wide means 20% margin on each side.
        backgroundMargin = (100 - actionData.volume.backgroundSize) / 2;

        // relative position of mouse over element
        value = Math.max(0, Math.min(1, (clientX - actionData.volume.x) / actionData.volume.width));

        target.style.clip = 'rect(0px, ' + (actionData.volume.width * value) + 'px, ' + actionData.volume.height + 'px, ' + (actionData.volume.width * (backgroundMargin / 100)) + 'px)';

        // determine logical volume, including background margin
        pixelMargin = ((backgroundMargin / 100) * actionData.volume.width);

        volume = Math.max(0, Math.min(1, ((clientX - actionData.volume.x) - pixelMargin) / (actionData.volume.width - (pixelMargin * 2)))) * 100;

        // set volume
        if (soundObject) {
          soundObject.setVolume(volume);
        }

        defaultVolume = volume;

        return utils.events.preventDefault(e);

      },

      releaseVolume: function (/* e */) {

        utils.events.remove(document, 'mousemove', actions.adjustVolume);
        utils.events.remove(document, 'touchmove', actions.adjustVolume);
        utils.events.remove(document, 'mouseup', actions.releaseVolume);
        utils.events.remove(document, 'touchend', actions.releaseVolume);

      },

      setVolume: function (volume) {

        // set volume (0-100) and update volume slider UI.

        var backgroundSize,
          backgroundMargin,
          backgroundOffset,
          target,
          from,
          to;

        if (volume === undefined || isNaN(volume)) {
          return;
        }

        if (dom.volume) {

          target = dom.volume;

          // based on getStyle() result
          backgroundSize = actionData.volume.backgroundSize;

          // figure out spacing around background image based on background size, eg. 60% background size.
          // 60% wide means 20% margin on each side.
          backgroundMargin = (100 - backgroundSize) / 2;

          // margin as pixel value relative to width
          backgroundOffset = actionData.volume.width * (backgroundMargin / 100);

          from = backgroundOffset;
          to = from + ((actionData.volume.width - (backgroundOffset * 2)) * (volume / 100));

          target.style.clip = 'rect(0px, ' + to + 'px, ' + actionData.volume.height + 'px, ' + from + 'px)';

        }

        // apply volume to sound, as applicable
        if (soundObject) {
          soundObject.setVolume(volume);
        }

        defaultVolume = volume;

      }

    };

    init();

    // TODO: mixin actions -> exports

    exports = {
      // Per-instance events: window.sm2BarPlayers[0].on = { ... } etc. See global players.on example above for reference.
      on: null,
      actions: actions,
      dom: dom,
      playlistController: playlistController
    };

    return exports;

  };

  // barebones utilities for logic, CSS, DOM, events etc.

  utils = {

    array: (function () {

      function compare(property) {

        var result;

        return function (a, b) {

          if (a[property] < b[property]) {
            result = -1;
          } else if (a[property] > b[property]) {
            result = 1;
          } else {
            result = 0;
          }
          return result;
        };

      }

      function shuffle(array) {

        // Fisher-Yates shuffle algo

        var i, j, temp;

        for (i = array.length - 1; i > 0; i--) {
          j = Math.floor(Math.random() * (i + 1));
          temp = array[i];
          array[i] = array[j];
          array[j] = temp;
        }

        return array;

      }

      return {
        compare: compare,
        shuffle: shuffle
      };

    }()),

    css: (function () {

      function hasClass(o, cStr) {

        return (o.className !== undefined ? new RegExp('(^|\\s)' + cStr + '(\\s|$)').test(o.className) : false);

      }

      function addClass(o, cStr) {

        if (!o || !cStr || hasClass(o, cStr)) {
          return; // safety net
        }
        o.className = (o.className ? o.className + ' ' : '') + cStr;

      }

      function removeClass(o, cStr) {

        if (!o || !cStr || !hasClass(o, cStr)) {
          return;
        }
        o.className = o.className.replace(new RegExp('( ' + cStr + ')|(' + cStr + ')', 'g'), '');

      }

      function swapClass(o, cStr1, cStr2) {

        var tmpClass = {
          className: o.className
        };

        removeClass(tmpClass, cStr1);
        addClass(tmpClass, cStr2);

        o.className = tmpClass.className;

      }

      function toggleClass(o, cStr) {

        var found,
          method;

        found = hasClass(o, cStr);

        method = (found ? removeClass : addClass);

        method(o, cStr);

        // indicate the new state...
        return !found;

      }

      return {
        has: hasClass,
        add: addClass,
        remove: removeClass,
        swap: swapClass,
        toggle: toggleClass
      };

    }()),

    dom: (function () {

      function getAll(param1, param2) {

        var node,
          selector,
          results;

        if (arguments.length === 1) {

          // .selector case
          node = document.documentElement;
          // first param is actually the selector
          selector = param1;

        } else {

          // node, .selector
          node = param1;
          selector = param2;

        }

        // sorry, IE 7 users; IE 8+ required.
        if (node && node.querySelectorAll) {

          results = node.querySelectorAll(selector);

        }

        return results;

      }

      function get(/* parentNode, selector */) {

        var results = getAll.apply(this, arguments);

        // hackish: if an array, return the last item.
        if (results && results.length) {
          return results[results.length - 1];
        }

        // handle "not found" case
        return results && results.length === 0 ? null : results;

      }

      function ancestor(nodeName, element, checkCurrent) {

        if (!element || !nodeName) {
          return element;
        }

        nodeName = nodeName.toUpperCase();

        // return if current node matches.
        if (checkCurrent && element && element.nodeName === nodeName) {
          return element;
        }

        while (element && element.nodeName !== nodeName && element.parentNode) {
          element = element.parentNode;
        }

        return (element && element.nodeName === nodeName ? element : null);

      }

      return {
        ancestor: ancestor,
        get: get,
        getAll: getAll
      };

    }()),

    position: (function () {

      function getOffX(o) {

        // http://www.xs4all.nl/~ppk/js/findpos.html
        var curleft = 0;

        if (o.offsetParent) {

          while (o.offsetParent) {

            curleft += o.offsetLeft;

            o = o.offsetParent;

          }

        } else if (o.x) {

          curleft += o.x;

        }

        return curleft;

      }

      function getOffY(o) {

        // http://www.xs4all.nl/~ppk/js/findpos.html
        var curtop = 0;

        if (o.offsetParent) {

          while (o.offsetParent) {

            curtop += o.offsetTop;

            o = o.offsetParent;

          }

        } else if (o.y) {

          curtop += o.y;

        }

        return curtop;

      }

      return {
        getOffX: getOffX,
        getOffY: getOffY
      };

    }()),

    style: (function () {

      function get(node, styleProp) {

        // http://www.quirksmode.org/dom/getstyles.html
        var value;

        if (node.currentStyle) {

          value = node.currentStyle[styleProp];

        } else if (window.getComputedStyle) {

          value = document.defaultView.getComputedStyle(node, null).getPropertyValue(styleProp);

        }

        return value;

      }

      return {
        get: get
      };

    }()),

    events: (function () {

      var add, remove, preventDefault, getClientX;

      add = function (o, evtName, evtHandler) {
        // return an object with a convenient detach method.
        var eventObject = {
          detach: function () {
            return remove(o, evtName, evtHandler);
          }
        };
        if (window.addEventListener) {
          o.addEventListener(evtName, evtHandler, false);
        } else {
          o.attachEvent('on' + evtName, evtHandler);
        }
        return eventObject;
      };

      remove = (window.removeEventListener !== undefined ? function (o, evtName, evtHandler) {
        return o.removeEventListener(evtName, evtHandler, false);
      } : function (o, evtName, evtHandler) {
        return o.detachEvent('on' + evtName, evtHandler);
      });

      preventDefault = function (e) {
        if (e.preventDefault) {
          e.preventDefault();
        } else {
          e.returnValue = false;
          e.cancelBubble = true;
        }
        return false;
      };

      getClientX = function (e) {
        // normalize between desktop (mouse) and touch (mobile/tablet/?) events.
        // note pageX for touch, which normalizes zoom/scroll/pan vs. clientX.
        return (e && (e.clientX || (e.touches && e.touches[0] && e.touches[0].pageX)));
      };

      return {
        add: add,
        preventDefault: preventDefault,
        remove: remove,
        getClientX: getClientX
      };

    }()),

    features: (function () {

      var getAnimationFrame,
        localAnimationFrame,
        localFeatures,
        prop,
        styles,
        testDiv,
        transform;

      testDiv = document.createElement('div');

      /**
       * hat tip: paul irish
       * http://paulirish.com/2011/requestanimationframe-for-smart-animating/
       * https://gist.github.com/838785
       */

      localAnimationFrame = (window.requestAnimationFrame
        || window.webkitRequestAnimationFrame
        || window.mozRequestAnimationFrame
        || window.oRequestAnimationFrame
        || window.msRequestAnimationFrame
        || null);

      // apply to window, avoid "illegal invocation" errors in Chrome
      getAnimationFrame = localAnimationFrame ? function () {
        return localAnimationFrame.apply(window, arguments);
      } : null;

      function has(propName) {

        // test for feature support
        return (testDiv.style[propName] !== undefined ? propName : null);

      }

      // note local scope.
      localFeatures = {

        transform: {
          ie: has('-ms-transform'),
          moz: has('MozTransform'),
          opera: has('OTransform'),
          webkit: has('webkitTransform'),
          w3: has('transform'),
          prop: null // the normalized property value
        },

        rotate: {
          has3D: false,
          prop: null
        },

        getAnimationFrame: getAnimationFrame

      };

      localFeatures.transform.prop = (
        localFeatures.transform.w3 ||
        localFeatures.transform.moz ||
        localFeatures.transform.webkit ||
        localFeatures.transform.ie ||
        localFeatures.transform.opera
      );

      function attempt(style) {

        try {
          testDiv.style[transform] = style;
        } catch (e) {
          // that *definitely* didn't work.
          return false;
        }
        // if we can read back the style, it should be cool.
        return !!testDiv.style[transform];

      }

      if (localFeatures.transform.prop) {

        // try to derive the rotate/3D support.
        transform = localFeatures.transform.prop;
        styles = {
          css_2d: 'rotate(0deg)',
          css_3d: 'rotate3d(0,0,0,0deg)'
        };

        if (attempt(styles.css_3d)) {
          localFeatures.rotate.has3D = true;
          prop = 'rotate3d';
        } else if (attempt(styles.css_2d)) {
          prop = 'rotate';
        }

        localFeatures.rotate.prop = prop;

      }

      testDiv = null;

      return localFeatures;

    }())

  };

  // ---

  // expose to global
  window.sm2BarPlayers = players;
  window.sm2BarPlayerOptions = playerOptions;
  window.SM2BarPlayer = Player;

}(window));