all files / lib/ vissense.js

99.31% Statements 432/435
93.55% Branches 203/217
100% Functions 121/121
99.31% Lines 432/435
2 statements, 2 functions, 1 branch Ignored     
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 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443                                                                      23× 12× 12× 10×                                                   10× 10× 10×                                                           288× 288×   288× 283× 221×     62× 165× 84×       62×                                                         43× 24×   43× 22×                                                                                                                                                                                           15× 15×                                                     620× 1451× 1451× 167×                                                                                                                               41×                                                           527×                                               457×                                                         585× 585×                                                                               38×                                                                                                   12× 12×   12× 14× 14× 14×     14× 10× 10×                                                   192× 192×                                                         417×                                               501×                                                               382× 295×     382× 382× 16×     366× 366×                                                 111×     110×     109×   109× 109× 22×     87×                                                                   190× 72×   118×                                               190× 190×   190× 113×     77× 77×   77× 31× 46× 46×           77× 50× 27× 27×             77×             163× 163× 652×   163× 163×             163× 652× 163×   178×     11× 11×             163×                                                                                           139× 173×       28× 28× 28×           162×     160× 173×     160×   160× 160×               160×     159× 76× 76×     159×   159×     140×     140× 140× 134× 134×     140×   140×                                                                                                                                         152×     151×     150× 150×                 150× 150× 177×       150× 150× 177×                                                           181× 184×       181× 177×   177× 107×   70× 35×     35×                                         15×                                                                               17×                                     41×                                     37×                                         90×                                                                                                       210× 26×     210×                                                   129×                               38×                               43×                                   28× 28×     28×         26× 17×                                                                                                                                     23×               23× 23× 23×   23× 23×         23×                       23× 23×   23× 28× 28× 28× 21×       23× 28× 20×       23× 20×       23× 20×       23× 20× 13×       23× 207× 25×                                                                                                                                 17×                                                                   17×   13×       13×     13×     12×         12×   12×   12×   12×                                                                               20×     20× 12× 12×     20×                                                 58×   28×     28×                                                                                                                                                                                                                                                                                                           40×                                                                                                                                                                                                                                                                               29×                             24× 31× 31×                         13× 19× 19×                           13× 19× 19×                                                                                 32×     32×                           12× 11× 11× 37×     11×       11×     12×                     10×                                                                                             32×       32×     32×                           12× 11× 11× 11×   11× 11× 11× 11×   11×         11×     12×                     10×                                                       23×                                                                                                                                  
/**
 * @license MIT
 *
 * Available under MIT license <http://opensource.org/licenses/MIT>
 */
 
'use strict';
 
/**
 * @function
 * @name async
 * @memberof VisSense.Utils
 *
 * @param {function} callback The function that should be proxied.
 * @param {number} [delay=0] The time in milliseconds to delay the invocation.
 *
 * @returns {function} A proxy function when called will defer
 * the actual function call.
 *
 * @description Returns a proxy function for the given callback which
 * will defer the actual invocation until the current call stack has cleared.
 *
 * @example
 *
 * var prefetch = function () { ... };
 *
 * var prefetchAsync = VisSense.Utils.async(prefetch, 2000);
 *
 * var cancelPrefetch = prefetchAsync();
 * if ( someone_changed_his_mind ) {
 *   cancelPrefetch();
 * }
 * // => true
 *
 */
function async(callback, delay) {
  return function () {
    var args = arguments;
    return defer(function () {
      callback.apply(undefined, args);
    }, delay || 0);
  };
}
 
/**
 * @function
 * @name debounce
 * @memberof VisSense.Utils
 *
 * @param {function} callback The function to debounce.
 * @param {number} delay The number of milliseconds to delay.
 *
 * @returns {function} A debounced version of the given function
 *
 * @description Returns a function that delays invoking `callback` until after
 * `delay` milliseconds have elapsed since the last time it was invoked.
 *
 * @example
 *
 * window.addEventListener('resize', VisSense.Utils.debounce(function() {
 *   console.log('resized');
 * }, 200));
 * // => logs 'resized' after receiving resize events stopped for 200ms
 *
 */
function debounce(callback, delay) {
  var cancel = noop;
  return function () {
    var self = this, args = arguments;
    cancel();
    cancel = defer(function () {
      callback.apply(self, args);
    }, delay);
  };
}
 
/**
 * @function
 * @name defaults
 * @memberof VisSense.Utils
 *
 * @param {Object} dest The destination object.
 * @param {Object} source The source object.
 *
 * @returns {Object}
 *
 * @description Assigns all properties of the source object to the destination
 * object if they are not present in the destination object.
 *
 * @example
 *
 * VisSense.Utils.defaults({
 *   name: 'Max',
 *   gender: 'male'
 * }, {
 *   name: 'Bradley',
 *   age: 31
 * });
 * // => { name: 'Max', gender: 'male', age: 31 }
 *
 */
function defaults(dest, source) {
  var sourceIsObject = isObject(source);
  var destIsObject = isObject(dest);
 
  if (!sourceIsObject && !destIsObject) {
    return source;
  } else if (!sourceIsObject || !destIsObject) {
    return !sourceIsObject ? dest : source;
  }
 
  forEach(Object.keys(source), function (property) {
    if (dest[property] === undefined) {
      dest[property] = source[property];
    }
  });
 
  return dest;
}
 
/**
 * @function
 * @name defer
 * @memberof VisSense.Utils
 *
 * @param {function} callback The function to defer.
 * @param {number} [delay=0] The time in milliseconds to delay the invocation.
 *
 * @returns {function} A function when called will cancel the invocation.
 *
 * @description Defers executing the callback function until the current call
 * stack has cleared. The request can be cancelled by calling the returned
 * function.
 *
 * @example
 *
 * var prefetch = function () { ... };
 *
 * var cancelPrefetch = VisSense.Utils.defer(prefetch, 9001);
 *
 * if ( someone_changed_his_mind ) {
 *   cancelPrefetch();
 * }
 * // => true
 *
 */
function defer(callback, delay) {
  var timer = setTimeout(function () {
    callback();
  }, delay || 0);
  return function () {
    clearTimeout(timer);
  };
}
 
/**
 * @function
 * @name fireIf
 * @memberof VisSense.Utils
 *
 * @param {function|*} when A function or any other value.
 * @param {function} callback A callback function to run if `when` evaluates
 * to a truthy value.
 *
 * @returns {function} Returns a function that runs the given callback function
 * only if `when` evaluates to a truthy value.
 *
 * @description Returns a function that when executed runs the given callback
 * function only if `when` evaluates to a truthy value.
 *
 * @example
 *
 * var a = 6;
 * VisSense.Utils.fireIf(function() { return a % 2 === 0; }, function() {
 *   return a % 3 === 0;
 * })();
 * // => true
 *
 */
function fireIf(when, callback) {
  return function () {
    return (isFunction(when) ? when() : when) ? callback() : undefined;
  };
}
 
/**
 * This callback lets you intercept the assignment of
 * individual properties. The return value will be assigned
 * to the `destKey` property of the `dest` object.
 * If this callback is not provided `sourceValue` will be assigned.
 *
 * @callback extendCallback
 * @memberof VisSense.Utils
 *
 * @param {*} destValue The destination value that will be replaced.
 * @param {*} sourceValue The source value than will replace the destination
 * value.
 * @param {*} destKey The destination key.
 * @param {*} sourceKey The source key.
 * @param {*} dest The given destination.
 * @param {*} source The given source.
 */
 
/**
 * @function
 * @name extend
 * @memberof VisSense.Utils
 *
 * @param {Object} dest The destination object.
 * @param {Object} source The source object.
 * @param {VisSense.Utils.extendCallback} [callback] The function to customize assigning
 * values.
 *
 * @returns {Object}
 *
 * @description Overwrites all properties of the destination object with the
 * source object's properties. You can provide an optional callback function
 * to modify the behaviour and/or to manipulate the return value.
 *
 * @example
 *
 * VisSense.Utils.extend({
 *   name: 'Max',
 *   age: 31
*   }, {
 *   name: 'Bradley',
 *   gender: 'male'
 * });
 * // => { name: 'Bradley', age: 31, gender: 'male' }
 *
 *
 * VisSense.Utils.extend({
 *   name: 'Max',
 *   age: 31
 * }, {
 *   name: 'Bradley',
 *   gender: 'male'
 * }, function(destValue, srcValue, key) {
 *   if(key === 'age') return destValue + 42;
 *   return srcValue;
 * });
 * // => { name: 'Bradley', age: 73, gender: 'male' }
 *
 */
function extend(dest, source, callback) {
  var index = -1,
    props = Object.keys(source),
    length = props.length,
    ask = isFunction(callback);
 
  while (++index < length) {
    var key = props[index];
    dest[key] = ask ?
      callback(dest[key], source[key], key, dest, source) : source[key];
  }
 
  return dest;
}
 
/**
 * @function
 * @name forEach
 * @memberof VisSense.Utils
 *
 * @param {Array} array The target array to iterate.
 * @param {function} callback Function that consumes an elements of the array
 * @param {*} [thisArg] Value to use as this when executing callback.
 *
 * @returns {*} the result of the callback or undefined
 *
 * @description Iterates of the provided array
 *
 * @example
 *
 * var myArray = [1,2,3];
 * VisSense.Utils.forEach([1,2,3], function(num, index) {
 *   console.log('myArray[', index, '] = ', num);
 * });
 *
 */
function forEach(array, callback, thisArg) {
  for (var i = 0, n = array.length; i < n; i++) {
    var result = callback.call(thisArg, array[i], i, array);
    if (result !== undefined) {
      return result;
    }
  }
}
 
/**
 * @function
 * @name identity
 * @memberof VisSense.Utils
 *
 * @param {*} value Any value.
 *
 * @returns {*} The given value.
 *
 * @description This function returns the first argument provided to it.
 *
 * @example
 *
 * var object = { 'name': 'Bradley' };
 * VisSense.Utils.identity(object) === object;
 * // => true
 *
 */
function identity(value) {
  return value;
}
 
/**
 * @function
 * @name isDefined
 * @memberof VisSense.Utils
 *
 * @param {*} value Any value.
 * @returns {boolean} `true` if the given value is undefined, otherwise `false`.
 *
 * @description Checks if the given value is undefined
 *
 * @example
 *
 * VisSense.Utils.isDefined(undefined) === false;
 * // => true
 *
 */
function isDefined(value) {
  return value !== undefined;
}
 
/**
 * @function
 * @name isArray
 * @memberof VisSense.Utils
 *
 * @param {*} value The value to check.
 *
 * @returns {boolean} `true` if `value` is an `Array`, otherwise `false`.
 *
 * @description Checks if `value` is classified as an `Array` object
 *
 * @example
 *
 * VisSense.Utils.isArray([1, 2, 3]);
 * // => true
 *
 * (function() { return VisSense.Utils.isArray(arguments); })();
 * // => false
 *
 * From lodash: [isArray](https://lodash.com/docs#isArray)
 */
function isArray(value) {
  return (value &&
    typeof value === 'object' && typeof value.length === 'number' &&
    Object.prototype.toString.call(value) === '[object Array]') || false;
}
 
/**
 * @function
 * @name isElement
 * @memberof VisSense.Utils
 *
 * @param {*} value The value to check.
 *
 * @returns {boolean} `true` if the given value is a DOM Element,
 * otherwise `false`.
 *
 * @description Checks if `value` is a DOM Element.
 *
 * @example
 *
 * var elem = document.getElementById('myElement')
 * VisSense.Utils.isElement(elem);
 * // => true
 *
 * VisSense.Utils.isElement(document);
 * // => false
 *
 * VisSense.Utils.isElement(document.body);
 * // => true
 *
 */
function isElement(value) {
  return value && value.nodeType === 1 || false;
}
 
/**
 * @function
 * @name isFunction
 * @memberof VisSense.Utils
 *
 * @param {*} value The value to check.
 *
 * @returns {boolean} `true` if the value is a function, otherwise `false`.
 *
 * @description Checks if `value` is classified as a `function` object.
 *
 * @example
 *
 * VisSense.Utils.isFunction(VisSense);
 * // => true
 *
 * VisSense.Utils.isFunction(/abc/);
 * // => false
 *
 * From lodash: [isFunction](https://lodash.com/docs#isFunction)
 */
function isFunction(value) {
  return typeof value === 'function' || false;
}
 
/**
 * @function
 * @name isObject
 * @memberof VisSense.Utils
 *
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an object, otherwise `false`.
 *
 * @description Checks if `value` is the language type of `Object`.
 * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and
 * `new String('')`)
 *
 * @example
 *
 * VisSense.Utils.isObject({});
 * // => true
 *
 * VisSense.Utils.isObject([1, 2, 3]);
 * // => true
 *
 * VisSense.Utils.isObject(1);
 * // => false
 *
 *
 * From lodash: [isObject](https://lodash.com/docs#isObject)
 */
function isObject(value) {
  var type = typeof value;
  return (type === 'function' || (value && type === 'object')) || false;
}
 
/**
 * @function
 * @name noop
 * @memberof VisSense.Utils
 *
 * @returns undefined
 *
 * @description A no-operation function.
 *
 * @example
 *
 * var object = { 'name': 'Bradley' };
 * VisSense.Utils.noop(object) === undefined;
 * // => true
 *
 */
function noop() {
}
 
/**
 * @function
 * @name now
 * @memberof VisSense.Utils
 *
 * @returns {number} Returns milliseconds since the Unix epoch.
 *
 * @description Gets the number of milliseconds that have elapsed since the
 * Unix epoch (1 January 1970 00:00:00 UTC).
 *
 * @example
 *
 * var start = VisSense.Utils.now();
 * VisSense.Utils.defer(function() {
 *   console.log(VisSense.Utils.now() - start);
 * });
 * // => logs the time it took for the deferred function to be invoked
 *
 */
function now() {
  return new Date().getTime();
}
 
 
/**
 * @function
 * @name once
 * @memberof VisSense.Utils
 *
 * @param {function} callback The function to proxy.
 *
 * @returns {function} A proxy function that will only be invoked once.
 *
 * @description Returns a function that is restricted to invoking `callback`
 * once. Repeat calls to the function return the value of the first call.
 *
 * @example
 *
 * var calculateExpensiveNumber = function() { ... };
 * var expensiveNumber = once(calculateExpensiveNumber);
 *
 * var a = expensiveNumber() * 3.1415 + expensiveNumber();
 * // => exensiveNumber is actually invocing `calculateExpensiveNumber` only once
 *
 */
function once(callback) {
  var called = false;
  var cache;
  return function () {
    if (!called) {
      cache = callback.apply(undefined, arguments);
      called = true;
    }
    return cache;
  };
}
 
/**
 * @function
 * @name throttle
 * @memberof VisSense.Utils
 *
 * @param {function} callback The function to throttle.
 * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
 *
 * @returns {function} A throttled version of the given function
 *
 * @description Returns a function that only invokes `callback` at most once
 * per every `wait` milliseconds.
 *
 * @example
 *
 * window.addEventListener('resize', VisSense.Utils.throttle(function() {
 *   console.log('resizing..');
 * }, 100));
 * // => logs 'resizing..' at most every 100ms while resizing the browser window
 *
 */
function throttle(callback, wait, thisArg) {
  var cancel = noop;
  var last = false;
 
  return function () {
    var time = now();
    var args = arguments;
    var func = function () {
      last = time;
      callback.apply(thisArg, args);
    };
 
    if (last && time < last + wait) {
      cancel();
      cancel = defer(func, wait);
    } else {
      last = time;
      defer(func, 0);
    }
  };
}
 
/********************************************************** element-position */
 
/**
 * @private
 * @function
 * @name viewport
 * @memberof VisSense.Utils
 *
 * @param {Window} [referenceWindow=window] The window object.
 *
 * @returns {Viewport} The current viewport size.
 *
 * @description Gets the current viewport size of the browser window.
 *
 * @example
 *
 * VisSense.Utils._viewport();
 * // => e.g. { height: 1280, width: 790 }
 *
 */
function viewport(referenceWindow) {
  var win = referenceWindow || window;
  return {
    height: win.innerHeight,
    width: win.innerWidth
  };
}
/****************************************************** element-position end */
 
/*********************************************************** element-styling */
 
/**
 * @private
 * @function
 * @name computedStyle
 * @memberof VisSense.Utils
 *
 * @param {DOMElement} element A DOM element.
 * @param {Window} [referenceWindow=window] The window object.
 *
 * @returns {CSSStyleDeclaration} Returns the elements computed style.
 *
 * @description Returns the elements computed style.
 *
 * @example
 *
 * var element = document.getElementById('myElement');
 * VisSense.Utils._computedStyle(element);
 * // => CSSStyleDeclaration {parentRule: null, length: 0, cssText: "", ... }
 *
 */
function computedStyle(element, referenceWindow) {
  return (referenceWindow || window).getComputedStyle(element, null);
}
 
/**
 * @private
 * @function
 * @name styleProperty
 * @memberof VisSense.Utils
 *
 * @param {CSSStyleDeclaration} style A style of an element.
 * @param {string} property A name of the property to fetch.
 *
 * @returns {*} The value of the property.
 *
 * @description Returns the elements computed style property by name.
 *
 * @example
 *
 * var element = document.getElementById('myElement');
 * var style = VisSense.Utils._computedStyle(element);
 * VisSense.Utils._styleProperty(style, 'display');
 * // => 'block'
 *
 */
function styleProperty(style, property) {
  return style.getPropertyValue(property);
}
 
/**
 * @private
 * @function
 * @name isDisplayed
 * @memberof VisSense.Utils
 *
 * @param {DOMElement} element A DOM element
 * @param {CSSStyleDeclaration} [style] the elements style
 *
 * @returns {boolean} `true` if the element is visible by its
 * style and by the style of its parents, otherwise `false`.
 *
 * @description A recursive function that checks if the element is visible by
 * its and all parent nodes `position` style.
 * There is an optional style parameter which can be provided if you already
 * have computed the style of the element.
 * *NOTE*: This function calls window.getComputedStyle which is rather
 * expensive!
 *
 * @see http://jsperf.com/getcomputedstyle-vs-style-vs-css/2
 *
 * @example
 *
 * var element = document.getElementById('myElement');
 * var style =
 * VisSense.Utils._isDisplayed(element);
 * // => true
 *
 */
function isDisplayed(element, style) {
  if (!style) {
    style = computedStyle(element);
  }
 
  var display = styleProperty(style, 'display');
  if (display === 'none') {
    return false;
  }
 
  var parent = element.parentNode;
  return isElement(parent) ? isDisplayed(parent) : true;
}
 
/**
 * @function
 * @name isVisibleByStyling
 * @memberof VisSense.Utils
 *
 * @param {DOMElement} element A DOM element
 * @param {Window} [referenceWindow=window] The window object.
 *
 * @returns {boolean} `true` if the element is visible by style and the style of
 * its parents, otherwise `false`.
 *
 * @description Checks if the element is visible by its style. If the given
 * element is the `document` then it will always return `true` (even if
 * `document.hidden` is `true` - this does not affect it's styling).
 *
 * @example
 *
 * var element = document.getElementById('myElement');
 * VisSense.Utils.isVisibleByStyling(element);
 * // => true
 *
 */
function isVisibleByStyling(element, referenceWindow) {
  if (element === (referenceWindow || window).document) {
    return true;
  }
 
  if (!element || !element.parentNode) {
    return false;
  }
 
  var style = computedStyle(element, referenceWindow);
 
  var visibility = styleProperty(style, 'visibility');
  if (visibility === 'hidden' || visibility === 'collapse') {
    return false;
  }
 
  return isDisplayed(element, style);
}
/******************************************************* element-styling end */
 
/******************************************************** element visibility */
 
/**
 * @private
 * @function
 * @name isInViewport
 * @memberof VisSense.Utils
 *
 * @param {BoundingClientRect} rect An object representing a rectangle with
 * properties ´bottom´, ´top´, ´left´ and ´right´ relative to the viewport.
 * @param {Viewport} viewport An object representing the viewport with
 * properties ´height´ and ´width´.
 *
 * @returns {boolean} `true` of the provided rectangle is in the given
 * viewport, otherwise `false`.
 *
 * @description Checks if the provided rectangle is in the given
 * viewport. The function solely exists for the fact that "All calls
 * to get any calculated dimension from the DOM should be cached or avoided".
 *
 * @see http://dcousineau.com/blog/2013/09/03/high-performance-js-tip/
 *
 * @example
 *
 * var rect = element.getBoundingClientRect();
 * var view = VisSense.Utils.viewport();
 * VisSense.Utils._isInViewport(rect, viewport);
 * // => true
 *
 */
function isInViewport(rect, viewport) {
  if (!rect || (rect.width <= 0 || rect.height <= 0)) {
    return false;
  }
  return rect.bottom > 0 &&
    rect.right > 0 &&
    rect.top < viewport.height &&
    rect.left < viewport.width;
}
 
/**
 * @function
 * @name percentage
 * @memberof VisSense.Utils
 *
 * @param {DOMElement} element A DOM element.
 * @param {Window} [referenceWindow=window] The window object.
 *
 * @returns {number} the percentage of the elements surface area within the
 * visible area of a viewer's browser window on an in focus web page.
 *
 * @example
 *
 * var element = document.getElementById('myElement');
 * VisSense.Utils.percentage(element);
 * // => e.g. 0.333
 *
 */
function percentage(element, referenceWindow) {
  var rect = element.getBoundingClientRect();
  var view = viewport(referenceWindow);
 
  if (!isInViewport(rect, view) || !isVisibleByStyling(element)) {
    return 0;
  }
 
  var vh = 0; // visible height
  var vw = 0; // visible width
 
  if (rect.top >= 0) {
    vh = Math.min(rect.height, view.height - rect.top);
  } else Eif (rect.bottom > 0) {
    vh = Math.min(view.height, rect.bottom);
  }
  /* otherwise {
   this path cannot be taken otherwise element would not be in viewport
   } */
 
  if (rect.left >= 0) {
    vw = Math.min(rect.width, view.width - rect.left);
  } else Eif (rect.right > 0) {
    vw = Math.min(view.width, rect.right);
  }
  /* otherwise {
   this path cannot be taken otherwise element would not be in viewport
   } */
 
  // rect's height and width are greater than 0 because element is in viewport
  return (vh * vw) / (rect.height * rect.width);
}
 
/*****************************************************element visibility end */
 
/*********************************************************** page visibility */
/* istanbul ignore next */
var createVisibilityApi = function (referenceWindow) {
  return (function (document, undefined) {
    var entry = function (propertyName, eventName) {
      return {property: propertyName, event: eventName};
    };
    var event = 'visibilitychange';
    var dict = [
      entry('webkitHidden', 'webkit' + event),
      entry('msHidden', 'ms' + event),
      entry('mozHidden', 'moz' + event),
      entry('hidden', event)
    ];
 
    var api = forEach(dict, function (entry) {
      if (document[entry.property] !== undefined) {
        return {
          isHidden: function () {
            return !!document[entry.property] || false;
          },
          onVisibilityChange: function (callback) {
            document.addEventListener(entry.event, callback, false);
            return function () {
              document.removeEventListener(entry.event, callback, false);
            };
          }
        };
      }
    });
 
    return api || {
        isHidden: /* istanbul ignore next */ function () {
          return false;
        },
        onVisibilityChange: /* istanbul ignore next */ function () {
          return noop;
        }
      };
  })((referenceWindow || window).document);
};
 
/**
 * @function
 * @name isPageVisible
 * @memberof VisSense.Utils
 *
 * @param {Window} [referenceWindow=window] The window object.
 *
 * @returns {boolean} Returns true if the current tab is in the foreground
 *   otherwise false.
 *
 * @description This method determines the visibility of the current tab and
 * returns true if it is the foreground. If the browser does not communicate
 * the state via ´document.hidden´ (or vendor specific derivatives) it will
 * always return true.
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/Guide/User_experience/Using_the_Page_Visibility_API
 *
 * @example
 *
 * VisSense.Utils.isPageVisible();
 * // => true
 *
 */
function isPageVisible(referenceWindow) {
  return !createVisibilityApi(referenceWindow || window).isHidden();
}
 
/******************************************************************** events */
 
/**
 * @class
 * @name PubSub
 * @memberof VisSense
 */
var PubSub = (function (undefined) {
  /**
   * Invokes all consumers with the given arguments.
   * @param {function[]} consumers An array of functions taking the args array as parameter.
   * @param {*} args An array of arguments to pass to the function
   */
  var syncFireListeners = function (consumers, args) {
    forEach(consumers, function (consumer) {
      consumer(args);
    });
  };
 
  function PubSub(config) {
    this._cache = {};
    this._onAnyCache = [];
    this._config = defaults(config, {
      async: false,
      anyTopicName: '*'
    });
  }
 
  PubSub.prototype.on = function (/*String*/ topic, callback) {
    if (!isFunction(callback)) {
      console.warn('Discarding invalid listener on topic', topic);
      return noop;
    }
 
    var applyCallback = function (args) {
      return callback.apply(undefined, args || []);
    };
 
    var listener = !this._config.async ? applyCallback : async(applyCallback);
 
    var unregister = function (listener, array, topic) {
      return function () {
        var index = array.indexOf(listener);
 
        if (index > -1) {
          console.debug('Unregistering listener from topic', topic);
          array.splice(index, 1);
 
          console.debug('Topic', topic, 'has now', array.length, 'listeners');
          return true;
        }
 
        return false;
      };
    };
 
    if (topic === this._config.anyTopicName) {
      this._onAnyCache.push(listener);
      return unregister(listener, this._onAnyCache, '*');
    }
 
    if (!this._cache[topic]) {
      console.debug('Initializing queue for topic', topic);
      this._cache[topic] = [];
    }
 
    this._cache[topic].push(listener);
 
    return unregister(listener, this._cache[topic], topic);
  };
 
  PubSub.prototype.publish = function (/*String*/ topic, args) {
    var listeners = (this._cache[topic] || [])
      .concat(topic === this._config.anyTopicName ? [] : this._onAnyCache);
 
    var enableAsync = !!this._config.async;
    var syncOrAsyncPublish = (enableAsync ? async(syncFireListeners) : function (listeners, args) {
      syncFireListeners(listeners, args);
      return noop; // cannot be cancelled
    });
 
    console.debug('publishing topic', enableAsync ? '(async)' : '(sync)', topic, 'to', listeners.length, 'listeners');
 
    return syncOrAsyncPublish(listeners, args || []);
  };
 
  return PubSub;
})();
 
/**************************************************************** events end */
/**
 * @typedef VisSense~VisSenseConfig
 * @type {Object}
 * @property {number} [fullyvisible=1] The percentage limit an element is
 * considered fully visible.
 * @property {number} [hidden=0] The percentage an element limit is considered
 * hidden.
 * @property {number} [precision=3] The precision of the default percentage algorithm.
 * Must be not be negative.
 * @property {VisSense~PercentageHook} [percentageHook=VisSense.Utils.percentage]
 * A callback function to determine the visible percentage of the element.
 * If not provided it will fallback to VisSense.Utils.percentage.
 * @property {VisSense~VisibilityHook[]} [percentageHooks=[]]
 * An array of callback functions to intercept the visibility procedure.
 * By default a visibility hook using the VisibilityAPI will be registered.
 *
 * @description A configuration object to configure a VisSense instance.
 */
 
/**
 * @callback VisSense~PercentageHook
 *
 * @param {DOMElement} element The element to get the visible percentage of.
 * @returns {number} The visible percentage of the element (between 0 and 1).
 *
 * @description This callback function that will be called to determine
 * the visible area of the element.
 */
/**
 * @callback VisSense~VisibilityHook
 *
 * @param {DOMElement} element The target element.
 * @returns {boolean} `false` if the element is hidden, `true` otherwise.
 *
 * @description This callback function that will be called to intercept
 * the default visibility process.
 */
 
/**
 * @class
 * @name VisSense
 * @throws {Error} Will throw an error if the first argument is not a DOM
 * Element.
 *
 * @param {DOMElement} element A DOM element.
 * @param {VisSense~VisSenseConfig} [config={fullyvisible: 1, hidden: 0}] A
 * configuration object.
 *
 * @description Creates a `VisSense` object which wraps the given element
 * to enable visibility operations.
 *
 * @example
 *
 * var element = document.getElementById('myElement');
 * var vis = VisSense(element); // or new VisSense(element)
 *
 * vis.isVisible();
 * // => true
 *
 * vis.percentage();
 * // => 0.93
 *
 */
function VisSense(element, config) {
  if (!(this instanceof VisSense)) {
    return new VisSense(element, config);
  }
 
  if (!isElement(element)) {
    throw new Error('not an element node');
  }
 
  this._element = element;
  this._config = defaults(config, {
    fullyvisible: 1,
    hidden: 0,
    referenceWindow: window,
    percentageHook: percentage,
    precision: 3,
    visibilityHooks: []
  });
 
  var roundFactor = this._config.precision <= 0 ? 1 : Math.pow(10, this._config.precision || 3);
  this._round = function (val) {
    return Math.round(val * roundFactor) / roundFactor;
  };
 
  // page must be visible in order for the element to be visible
  var visibilityApi = createVisibilityApi(this._config.referenceWindow);
  this._config.visibilityHooks.push(function () {
    return !visibilityApi.isHidden();
  });
}
 
/**
 * @method
 * @name state
 * @memberof VisSense#
 *
 * @returns {VisSense~VisState} A state object.
 *
 * @description Returns an object representing the current state.
 * This function always invokes the full visibility scan and
 * therefore produces a new object everytime.
 *
 * @example
 *
 * var visElement = VisSense(element);
 * visElement.state();
 * // => {
 *    code: 1,
 *    state: 'visible',
 *    percentage: 0.33,
 *    fullyvisible: false,
 *    visible: true,
 *    hidden: false,
 *    previous: {}
 *  }
 *
 */
VisSense.prototype.state = function () {
  var hiddenByHook = forEach(this._config.visibilityHooks, function (hook) {
    if (!hook(this._element)) {
      console.debug('visibilityHook returned false -> element is not visible.');
      return VisSense.VisState.hidden(0);
    }
  }, this);
 
  return hiddenByHook || (function (visobj, element, config) {
      var perc = visobj._round(config.percentageHook(element, config.referenceWindow));
 
      if (perc <= config.hidden) {
        return VisSense.VisState.hidden(perc);
      }
      else if (perc >= config.fullyvisible) {
        return VisSense.VisState.fullyvisible(perc);
      }
 
      return VisSense.VisState.visible(perc);
    })(this, this._element, this._config);
};
 
/**
 * @method
 * @name percentage
 * @memberof VisSense#
 *
 * @returns {number} The currently visible area of the element.
 *
 * @description Returns the currently visible area of the element in percent (0..1)
 *
 * @example
 *
 * var visElement = VisSense(element);
 *
 * visElement.precentage();
 * // => 0.33
 *
 */
VisSense.prototype.percentage = function () {
  return this.state().percentage;
};
 
/**
 * @method
 * @name element
 * @memberof VisSense#
 *
 * @returns {DOMElement} The element
 *
 * @description Returns the element this instance is bound to
 *
 * @example
 *
 * var visElement = VisSense(element);
 *
 * element === visElement.element();
 * // => true
 *
 */
VisSense.prototype.element = function () {
  return this._element;
};
 
VisSense.prototype.referenceWindow = function () {
  return this._config.referenceWindow;
};
 
/**
 * @method
 * @name isFullyVisible
 * @memberof VisSense#
 *
 * @returns {boolean} `true` if the element is fully visible, otherwise `false`.
 *
 * @description Checks if the element is currently fully visible.
 *
 * @example
 *
 * var visElement = VisSense(element);
 * visElement.isFullyVisible();
 * // => true
 *
 */
VisSense.prototype.isFullyVisible = function () {
  return this.state().fullyvisible;
};
 
/**
 * @method
 * @name isVisible
 * @memberof VisSense#
 *
 * @returns {boolean} `true` if the element is visible, otherwise `false`.
 *
 * @description Checks if the element is currently visible.
 *
 * @example
 *
 * var visElement = VisSense(element);
 * visElement.isVisible();
 * // => true
 *
 */
VisSense.prototype.isVisible = function () {
  return this.state().visible;
};
 
/**
 * @method
 * @name isHidden
 * @memberof VisSense#
 *
 * @returns {boolean} `true` if the element is hidden, otherwise `false`.
 *
 * @description Checks if the element is currently hidden.
 *
 * @example
 *
 * var visElement = VisSense(element);
 * visElement.isHidden();
 * // => false
 *
 */
VisSense.prototype.isHidden = function () {
  return this.state().hidden;
};
 
VisSense.fn = VisSense.prototype;
 
/**
 * @static
 * @method
 * @name of
 * @memberof VisSense
 *
 * @returns {VisSense} An initialized VisSense object.
 *
 * @description Constructs and returns a VisSense object.
 * This is syntactic sugar for `new VisSense(..)`.
 *
 * @example
 *
 * var myElement = document.getElementById('myElement');
 * var visElement = VisSense.of(myElement);
 *
 */
VisSense.of = function (element, config) {
  return new VisSense(element, config);
};
 
var STATES = {
  HIDDEN: [0, 'hidden'],
  VISIBLE: [1, 'visible'],
  FULLY_VISIBLE: [2, 'fullyvisible']
};
 
/**
 * An object representing the visibility state of an element.
 *
 * @typedef  {Object} VisSense~VisState
 *
 * @property {number} code A number representation
 * of an visibility state. This is either 0, 1 or 2.
 * @property {string} state An string representation of an visibility state.
 * This is either 'hidden', 'visible' or 'fullyvisible'.
 * @property {number} percentage The visible percentage of the element.
 * @property {VisSense~VisState|{}} previous The previous state if any,
 * otherwise `{}` will be returned. This value's
 * `previous` property will always be deleted.
 * @property {boolean} fullyvisible `true` if the element is fully visible,
 * otherwise `false`.
 * @property {boolean} visible `true` if the element is visible, otherwise
 * `false`.
 * @property {boolean} hidden `true` if the element is hidden, otherwise
 * `false`.
 */
VisSense.VisState = (function () {
  /**
   * @private
   * @function
   * @name newVisState
   * @memberof VisSense~VisState
   *
   * @param {Array} state A state definition consisting of a code and a
   * string representation.
   * @param {number} percentage A number between 0 and 1 which represents
   * the currently visible area of an element.
   * @param {VisSense~VisState} [previous] The previous state of the element.
   *
   * @returns {VisSense~VisState} A state object.
   *
   * @description Constructs and returns a state object.
   *
   * @example
   *
   * var visElement = VisSense(element);
   *
   * visElement.isHidden();
   * // => false
   *
   */
  function newVisState(state, percentage, previous) {
    if (previous) {
      delete previous.previous;
    }
 
    return {
      code: state[0],
      state: state[1],
      percentage: percentage,
      previous: previous || {},
      fullyvisible: state[0] === STATES.FULLY_VISIBLE[0],
      visible: state[0] === STATES.VISIBLE[0] ||
      state[0] === STATES.FULLY_VISIBLE[0],
      hidden: state[0] === STATES.HIDDEN[0]
    };
  }
 
  return {
    /**
     * @static
     * @function
     * @name hidden
     * @memberof VisSense~VisState
     *
     * @param {number} percentage A number between 0 and 1 which represents
     * the currently visible area of an element.
     * @param {VisSense~VisState} [previous] The previous state of the element.
     *
     * @returns {VisSense~VisState} A state object representing
     * the state "hidden".
     */
    hidden: function (percentage, previous) {
      return newVisState(STATES.HIDDEN, percentage, previous);
    },
    /**
     * @static
     * @function
     * @name visible
     * @memberof VisSense~VisState
     *
     * @param {number} percentage A number between 0 and 1 which represents
     * the currently visible area of an element.
     * @param {VisSense~VisState} [previous] The previous state of the element.
     *
     * @returns {VisSense~VisState} A state object representing
     * the state "visible".
     */
    visible: function (percentage, previous) {
      return newVisState(STATES.VISIBLE, percentage, previous);
    },
    /**
     * @static
     * @function
     * @name fullyvisible
     * @memberof VisSense~VisState
     *
     * @param {number} percentage A number between 0 and 1 which represents
     * the currently visible area of an element.
     * @param {VisSense~VisState} [previous] The previous state of the element.
     *
     * @returns {VisSense~VisState} A state object representing
     * the state "fullyvisible".
     */
    fullyvisible: function (percentage, previous) {
      return newVisState(STATES.FULLY_VISIBLE, percentage, previous);
    }
  };
})();
 
/**
 * @private
 * @function
 * @name nextState
 *
 * @param {VisSense} visobj The VisSense element.
 * @param {VisSense~VisState} [currentState] The current state. Can be omitted
 * if the state of an element is determined the first time.
 *
 * @returns {VisSense~VisState} A visibility state object.
 *
 * This method determines and returns the new visibility state of an element.
 */
function nextState(visobj, currentState) {
  var newState = visobj.state();
  var percentage = newState.percentage;
 
  // check if nothing changed
  if (currentState &&
    percentage === currentState.percentage &&
    currentState.percentage === currentState.previous.percentage) {
    return currentState;
  }
 
  if (newState.hidden) {
    return VisSense.VisState.hidden(percentage, currentState);
  }
  else if (newState.fullyvisible) {
    return VisSense.VisState.fullyvisible(percentage, currentState);
  }
 
  // otherwise the element is visible
  return VisSense.VisState.visible(percentage, currentState);
}
 
/*---------------------------------------------------------------------------*/
 
/**
 * @typedef {Object} VisMonConfig
 * @name VisMonConfig
 * @memberof VisSense.VisMon#
 *
 * @property {VisSense.VisMon.Strategy|VisSense.VisMon.Strategy[]} [strategy=[PollingStrategy,EventStrategy]]
 *   a strategy or array of strategies for observing the element.
 * @property {function} [start] function to run when monitoring the element starts
 * @property {function} [stop] function to run when monitoring the element stops
 * @property {function} [update] function to run when elements update function is called
 * @property {function} [hidden] function to run when element becomes hidden
 * @property {function} [visible] function to run when element becomes visible
 * @property {function} [fullyvisible] function to run when element becomes fully visible
 * @property {function} [percentagechange] function to run when the percentage of the element changes
 * @property {function} [visibilitychange] function to run when the visibility of the element changes
 * @property {boolean} [async=false] a boolean flag indicating whether events are synchronous or asynchronous
 *
 * A configuration object to configure a VisMon instance.
 */
 
/**
 * @class
 * @name VisMon
 * @memberof VisSense
 *
 * @param {VisSense} visobj The VisSense instance to monitor.
 * @param {VisSense.VisMon#VisMonConfig} config A configuration object.
 *
 * @property {VisSense} _visobj The given VisSense instance.
 * @property {VisSense~VisState|{}} _state The current state.
 * @property {VisSense.PubSub} _pubsub A publish/subscribe queue.
 * @property {VisSense.VisMon.Strategy} _strategy the strategy to use for
 *   observing the element.
 *
 * @description Creates a `VisSense` object which wraps the given element
 *   to enable visibility operations.
 *
 * @example
 *
 * var visElement = VisSense(element);
 *
 * var visMon = VisSense.VisMon(visElement, {
 *   update: function() {
 *     console.log('updated.');
 *   }
 * });
 *
 * or
 *
 * @example
 *
 * var visMon = VisSense(element).monitor({
 *   update: function() {
 *     console.log('updated.');
 *   }
 * }).start();
 *
 */
function VisMon(visobj, config) {
  var _config = defaults(config, {
    strategy: [
      new VisMon.Strategy.PollingStrategy(),
      new VisMon.Strategy.EventStrategy()
    ],
    async: false
  });
 
  this._visobj = visobj;
  this._state = {};
  this._started = false;
 
  var anyTopicName = '*#' + now();
  this._pubsub = new PubSub({
    async: _config.async,
    anyTopicName: anyTopicName
  });
 
  this._events = [
    anyTopicName,
    'start',
    'stop',
    'update',
    'hidden',
    'visible',
    'fullyvisible',
    'percentagechange',
    'visibilitychange'
  ];
 
  this._strategy = new VisMon.Strategy.CompositeStrategy(_config.strategy);
  this._strategy.init(this);
 
  this._pubsub.on('update', function (monitor) {
    var newValue = monitor._state.percentage;
    var oldValue = monitor._state.previous.percentage;
    if (newValue !== oldValue) {
      monitor._pubsub.publish('percentagechange', [monitor, newValue, oldValue]);
    }
  });
 
  this._pubsub.on('update', function (monitor) {
    if (monitor._state.code !== monitor._state.previous.code) {
      monitor._pubsub.publish('visibilitychange', [monitor]);
    }
  });
 
  this._pubsub.on('visibilitychange', function (monitor) {
    if (monitor._state.visible && !monitor._state.previous.visible) {
      monitor._pubsub.publish('visible', [monitor]);
    }
  });
 
  this._pubsub.on('visibilitychange', function (monitor) {
    if (monitor._state.fullyvisible) {
      monitor._pubsub.publish('fullyvisible', [monitor]);
    }
  });
 
  this._pubsub.on('visibilitychange', function (monitor) {
    if (monitor._state.hidden) {
      monitor._pubsub.publish('hidden', [monitor]);
    }
  });
 
  forEach(this._events, function (event) {
    if (isFunction(_config[event])) {
      this.on(event, _config[event]);
    }
  }, this);
}
 
VisMon.prototype.visobj = function () {
  return this._visobj;
};
 
/**
 * @method
 * @name publish
 * @memberof VisSense.VisMon#
 *
 * @param {String} eventName The name of the event
 * @param {*} args The arguments to pass to the subscribers of the event
 *
 * @returns Returns a function that cancels the event execution - this can only
 * be done if the monitor has an async queue (option async enabled).
 *
 * @description
 * Invokes all subscribers of the given event with the provided arguments.
 * This method throws an error if an internal event is published.
 *
 * @example
 *
 * var monitor = VisSense(element).monitor();
 *
 * monitor.publish('myEvent', [arg1, arg2]);
 */
VisMon.prototype.publish = function (eventName, args) {
  var isInternalEvent = this._events.indexOf(eventName) >= 0;
  if (isInternalEvent) {
    throw new Error('Cannot publish internal event "' + eventName + '" from external scope.');
  }
 
  return this._pubsub.publish(eventName, args);
};
 
/**
 * @method
 * @name state
 * @memberof VisSense.VisMon#
 *
 * @returns {VisSense~VisState|{}} The current state.
 *
 * @description Returns an object representing the current
 * visibility state.
 *
 * @example
 *
 * var visMon = VisSense.VisMon(...);
 *
 * visElement.state();
 * // => {
 *    code: 1,
 *    state: 'visible',
 *    percentage: 0.33,
 *    fullyvisible: false,
 *    visible: true,
 *    hidden: false,
 *    previous: {
 *      code: 1,
 *      state: 'visible',
 *      percentage: 0.42,
 *      fullyvisible: false,
 *      visible: true,
 *      hidden: false
 *    }
 *  }
 *
 */
VisMon.prototype.state = function () {
  return this._state;
};
 
/**
 * @method
 * @name start
 * @memberof VisSense.VisMon#
 *
 * @returns {VisSense.VisMon} itself.
 *
 * @description Starts monitoring the provided element.
 * This will determine the element visibility once and
 * subequentially execute every strategies `start` method.
 * Call `stop` to stop observing the element.
 *
 * @example
 * var myElement = document.getElementById('myElement');
 * var monitor = VisSense.of(myElement).monitor().start();
 * ...
 * monitor.stop();
 *
 * @example
 *
 * var visobj = new VisSense(myElement);
 * var monitor = VisSense.VisMon(..., {
 *   strategy: [
 *     new ViSense.VisMon.Strategy.EventStrategy(...)
 *     new ViSense.VisMon.Strategy.PollingStrategy(...)
 *   ]
 *});
 *
 * monitor.start();
 *
 */
VisMon.prototype.start = function (config) {
  if (this._started) {
    return this;
  }
  var _config = defaults(config, {
    async: false
  });
 
  if (this._cancelAsyncStart) {
    this._cancelAsyncStart();
  }
 
  if (_config.async) {
    return this.startAsync();
  }
 
  this._started = true;
 
  // the contract for strategies says, that
  // the monitor has been updated at least once
  // when their `start` method is called.
  this.update();
 
  this._pubsub.publish('start', [this]);
 
  this._strategy.start(this);
 
  return this;
};
 
/**
 * @method
 * @name startAsync
 * @memberof VisSense.VisMon#
 *
 * @returns {VisSense.VisMon} itself.
 *
 * @description Asynchronously starts monitoring the provided element.
 */
VisMon.prototype.startAsync = function (config) {
  if (this._cancelAsyncStart) {
    this._cancelAsyncStart();
  }
  var me = this;
  var cancelAsyncStart = defer(function () {
    me.start(extend(defaults(config, {}), {async: false}));
  });
  this._cancelAsyncStart = function () {
    cancelAsyncStart();
    me._cancelAsyncStart = null;
  };
  return this;
};
 
/**
 * @method
 * @name stop
 * @memberof VisSense.VisMon#
 *
 * @returns {*} The return value of the strategies stop function.
 *
 * @description Stops monitoring the provided element.
 *
 * @example
 *
 * var visMon = VisSense.VisMon(..., {
 *   strategy: [
 *     new ViSense.VisMon.Strategy.EventStrategy(...)
 *     new ViSense.VisMon.Strategy.PollingStrategy(...)
 *   ]
 * }).start();
 *
 * ...
 *
 * visElement.stop();
 *
 */
VisMon.prototype.stop = function () {
  if (this._cancelAsyncStart) {
    this._cancelAsyncStart();
  }
 
  if (this._started) {
    this._strategy.stop(this);
    this._pubsub.publish('stop', [this]);
  }
 
  this._started = false;
};
 
/**
 * @method
 * @name update
 * @memberof VisSense.VisMon#
 *
 * @returns {undefined}
 *
 * @description Updates the state of the monitor object. This method invokes
 * a visibility check and fires any registered listener accordingly.
 *
 * @example
 *
 * var vismon = VisSense(...)
 *  .monitor({
 *    update: function() {
 *      console.log('update');
 *    }
 *  });
 *
 * vismon.update();
 * // -> prints 'update' to console
 */
VisMon.prototype.update = function () {
  if (this._started) {
    // update state
    this._state = nextState(this._visobj, this._state);
 
    // notify listeners
    this._pubsub.publish('update', [this]);
  }
};
 
/**
 * This callback function will unregister a previously registered listener.
 * It will be returned from any function registering a listener.
 * Returns `true` if the listener was successfully unregistered, otherwise
 * `false`.
 *
 * @callback RemoveListenerCallback
 * @memberof VisSense.VisMon#
 * @param {boolean} vismon A reference to the monitor.
 */
 
/**
 * This callback function will be called everytime the monitor updates its
 * state.
 *
 * As all listeners, it can be removed with the returned
 * `RemoveListenerCallback` function of the method registering it.
 *
 * @callback OnUpdateCallback
 * @memberof VisSense.VisMon#
 * @param {VisSense.VisMon} vismon A reference to the monitor.
 */
 
/**
 * This callback function will be called everytime the visibility state
 * changes.
 *
 * A visibility change can occur if a state transits from
 * - HIDDEN to VISIBILE or FULLY_VISIBILE
 * - VISIBLE to FULLY_VISIBLE or HIDDEN
 * - FULLY_VISIBLE to HIDDEN or VISIBLE
 *
 * As all listeners, it can be removed with the returned
 * `RemoveListenerCallback` function of the method registering it.
 *
 * @callback VisMon.OnVisibilityChangeCallback
 * @param {VisSense.VisMon} vismon A reference to the monitor.
 */
 
/**
 * This callback function will be called everytime the visibility
 * percentage changes.
 *
 * As all listeners, it can be removed with the returned
 * `RemoveListenerCallback` function of the method registering it.
 *
 * This callback will currently be provided with different
 * parameters than the others. This is likely to change in
 * future versions in favour of a uniform approach.
 *
 * @callback OnPercentageChangeCallback
 * @memberof VisSense.VisMon#
 *
 * @param {number} newValue The new visible percentage.
 * @param {number} oldValue The former visible percentage.
 * @param {VisSense.VisMon} vismon A reference to the monitor.
 */
 
/**
 * This callback function will be called everytime the visibility
 * states changes and the element becomes visible.
 *
 * This can occur if a state changes from
 * - HIDDEN to VISIBLE
 * - HIDDEN to FULLY_VISIBLE
 *
 * *NOTE*: This does not occur when changing from
 * - FULLY_VISIBLE to VISIBLE
 *
 * As all listeners, it can be removed with the returned
 * `RemoveListenerCallback` function of the method registering it.
 *
 * @callback OnVisibleCallback
 * @memberof VisSense.VisMon#
 * @param {VisSense.VisMon} vismon A reference to the monitor.
 */
 
/**
 * This callback function will be called everytime the visibility
 * states changes and the element becomes fully visible.
 *
 * This can occur if a state changes from
 * - HIDDEN to FULLY_VISIBLE
 * - VISIBLE to FULLY_VISIBLE
 *
 * As all listeners, it can be removed with the returned
 * `RemoveListenerCallback` function of the method registering it.
 *
 * @callback OnFullyVisibleCallback
 * @memberof VisSense.VisMon
 * @param {VisSense.VisMon} vismon A reference to the monitor.
 */
 
/**
 * This callback function will be called everytime the visibility
 * states changes and the element becomes hidden.
 *
 * This can occur if a state changes from
 * - FULLY_VISIBLE to HIDDEN
 * - VISIBLE to HIDDEN
 *
 * As all listeners, it can be removed with the returned
 * `RemoveListenerCallback` function of the method registering it.
 *
 * @callback OnHiddenCallback
 * @memberof VisSense.VisMon#
 * @param {VisSense.VisMon} vismon A reference to the monitor.
 */
 
/**
 * @method
 * @name on
 * @memberof VisSense.VisMon#
 *
 * @param {string} topic The name of the topic to bind the callback to.
 * @param {function} callback A callback function.
 *
 * @returns {VisSense.VisMon#RemoveListenerCallback} A function when called will remove the listener.
 *
 * @description Binds a callback function to a specific event.
 * Valid events are:
 *  - ´start´
 *  - ´stop´
 *  - ´update´
 *  - ´hidden´
 *  - ´visible´
 *  - ´fullyvisible´
 *  - ´percentagechange´
 *  - ´visibilitychange´
 *
 * @example
 *
 * var monitor = VisSense(...).monitor(...);
 *  monitor.on('fullyvisible', function() {
 *   Animations.startAnimation();
 * });
 *
 * monitor.on('percentagechange', function(newValue) {
 *   if(newValue < 0.8) {
 *     Animations.stopAnimation();
 *   }
 * });
 *
 * monitor.start();
 *
 */
VisMon.prototype.on = function (topic, callback) {
  return this._pubsub.on(topic, callback);
};
 
 
VisMon.Builder = (function () {
  var combineStrategies = function (config, strategies) {
    var combinedStrategies = null;
    var forceDisableStrategies = config.strategy === false;
    var enableStrategies = !forceDisableStrategies && (config.strategy || strategies.length > 0);
 
    if (!enableStrategies) {
      Eif (forceDisableStrategies) {
        combinedStrategies = [];
      } else {
        combinedStrategies = config.strategy;
      }
    } else {
      var configStrategyIsDefined = !!config.strategy;
      var configStrategyIsArray = isArray(config.strategy);
      var configStrategyAsArray = configStrategyIsDefined ? (!configStrategyIsArray ?
        [config.strategy] : config.strategy) : [];
 
      combinedStrategies = configStrategyAsArray.concat(strategies);
    }
 
    return combinedStrategies;
  };
 
  return function (visobj) {
    var config = {};
    var strategies = [];
    var events = [];
 
    var productBuilt = false;
    var product = null;
 
    return {
      set: function (name, value) {
        config[name] = value;
        return this;
      },
      strategy: function (strategy) {
        strategies.push(strategy);
        return this;
      },
      on: function (event, handler) {
        events.push([event, handler]);
        return this;
      },
      /**
       * Creates the configured monitor.
       *
       * There is a special case in which all strategies
       * are disabled and hence the caller has to take
       * care of the update mechanism - this is especially useful
       * for testing.
       * This happens when the property 'strategy' is set to false
       * or ends up being an empty array.
       *
       * builder.set('strategy', false);
       * or
       * builder.options({
       *   strategy: false
       * });
       *
       * @param [consumer] if given will return this methods result
       * as return parameter. The built monitor is passed as first argument.
       *
       * @returns {*|VisSense.VisMon}
       */
      build: function (consumer) {
        var manufacture = function () {
          var combinedStrategies = combineStrategies(config, strategies);
 
          Iif (combinedStrategies === []) {
            console.debug('No strategies given - update process must be handled by caller. ');
          }
 
          config.strategy = combinedStrategies;
 
          var monitor = visobj.monitor(config);
 
          forEach(events, function (event) {
            monitor.on(event[0], event[1]);
          });
 
          productBuilt = true;
          product = monitor;
 
          return product;
        };
 
        Iif (productBuilt) {
          console.warn('Attempt to build an already built monitor.');
        }
 
        var monitor = productBuilt ? product : manufacture();
 
        if (isFunction(consumer)) {
          return consumer(monitor);
        } else {
          return monitor;
        }
      }
    };
  };
})();
 
/**
 * @abstract
 * @class
 * @name Strategy
 * @memberof VisSense.VisMon
 * @classdesc The base class of all strategies used by VisMon objects.
 */
VisMon.Strategy = function () {
};
 
/**
 * @method
 * @name init
 * @memberof VisSense.VisMon.Strategy#
 *
 * @param {VisSense.VisMon} monitor
 *
 * @description
 * The init method is called when a monitor is created and
 * has not started yet.
 */
VisMon.Strategy.prototype.init = noop;
 
/**
 * @method
 * @name start
 * @memberof VisSense.VisMon.Strategy#
 *
 * @param {VisSense.VisMon} monitor
 *
 * @description
 * The start method is called when monitoring the element starts.
 */
VisMon.Strategy.prototype.start = noop;
 
/**
 * @method
 * @name stop
 * @memberof VisSense.VisMon.Strategy#
 *
 * @param {VisSense.VisMon} monitor
 *
 * @description
 * The stop method is called when monitoring the element stops.
 */
VisMon.Strategy.prototype.stop = noop;
 
/**
 * @class
 * @name CompositeStrategy
 * @extends VisSense.VisMon.Strategy
 * @memberof VisSense.VisMon.Strategy
 *
 * @param {VisSense.VisMon.Strategy[]} strategies
 *
 * @property {VisSense.VisMon.Strategy[]} _strategies A list of strategies
 *
 * @classdesc A composite strategy to combine two or more strategies
 * Its a proxy that will call every strategies start() and stop() methods.
 *
 * @example
 *
 * var visMon = VisSense(...).monitor({
 *   strategy: new VisSense.VisMon.Strategy.CompositeStrategy([
 *      new VisSense.VisMon.Strategy.EventStrategy(...),
 *      new VisSense.VisMon.Strategy.PollingStrategy(...)
 *   ]),
 *   update: function() {
 *     console.log('updated.');
 *   }
 * }).start();
 *
 */
VisMon.Strategy.CompositeStrategy = function (strategies) {
  this._strategies = isArray(strategies) ? strategies : [strategies];
};
 
VisMon.Strategy.CompositeStrategy.prototype = Object.create(
  VisMon.Strategy.prototype
);
 
/**
 * @method
 * @name init
 * @memberof VisSense.VisMon.Strategy.CompositeStrategy#
 *
 * @param {VisSense.VisMon} monitor
 *
 * Calls the init method of all strategies.
 */
VisMon.Strategy.CompositeStrategy.prototype.init = function (monitor) {
  forEach(this._strategies, function (strategy) {
    Eif (isFunction(strategy.init)) {
      strategy.init(monitor);
    }
  });
};
/**
 * @method
 * @name start
 * @memberof VisSense.VisMon.Strategy.CompositeStrategy#
 *
 * @param {VisSense.VisMon} monitor
 *
 * Calls the start method of all strategies.
 */
VisMon.Strategy.CompositeStrategy.prototype.start = function (monitor) {
  forEach(this._strategies, function (strategy) {
    Eif (isFunction(strategy.start)) {
      strategy.start(monitor);
    }
  });
};
 
/**
 * @method
 * @name stop
 * @memberof VisSense.VisMon.Strategy.CompositeStrategy#
 *
 * @param {VisSense.VisMon} monitor
 *
 * Calls the stop method of all strategies.
 */
VisMon.Strategy.CompositeStrategy.prototype.stop = function (monitor) {
  forEach(this._strategies, function (strategy) {
    Eif (isFunction(strategy.stop)) {
      strategy.stop(monitor);
    }
  });
};
 
/**
 * @typedef {Object} PollingStrategyConfig
 * @name PollingStrategyConfig
 * @memberof VisSense.VisMon.Strategy.PollingStrategy#
 *
 * @property {number} [interval=5000] The interval between state updates
 * in milliseconds.
 *
 * @description A configuration object to configure a PollingStrategy instance.
 */
 
/**
 * @class
 * @name PollingStrategy
 * @extends VisSense.VisMon.Strategy
 * @memberof VisSense.VisMon.Strategy
 *
 * @param {VisSense.VisMon.Strategy.PollingStrategy#PollingStrategyConfig} [config={interval:1000}] The config object
 *
 * @property {VisSense.VisMon.Strategy.PollingStrategy#PollingStrategyConfig} _config The internal config object
 *
 * @classdesc A strategy that will periodically update the objects
 * visibility state.
 *
 * @example
 *
 * var visMon = VisSense(...).monitor({
 *   strategy: new VisSense.VisMon.Strategy.PollingStrategy({
 *     interval: 5000
 *   }),
 *   update: function() {
 *     console.log('updated.');
 *   }
 * }).start();
 *
 */
VisMon.Strategy.PollingStrategy = function (config) {
  this._config = defaults(config, {
    interval: 1000
  });
  this._started = false;
};
 
VisMon.Strategy.PollingStrategy.prototype = Object.create(
  VisMon.Strategy.prototype
);
 
/**
 * @method
 * @name start
 *
 * @param {VisSense.VisMon} monitor
 *
 * @memberof VisSense.VisMon.Strategy.PollingStrategy#
 */
VisMon.Strategy.PollingStrategy.prototype.start = function (monitor) {
  if (!this._started) {
    this._clearInterval = (function update(interval) {
      var intervalId = setInterval(function () {
        monitor.update();
      }, interval);
 
      return function () {
        clearInterval(intervalId);
      };
    }(this._config.interval));
 
    this._started = true;
  }
 
  return this._started;
};
 
/**
 * @method
 * @name stop
 *
 * @param {VisSense.VisMon} monitor
 *
 * @memberof VisSense.VisMon.Strategy.PollingStrategy#
 */
VisMon.Strategy.PollingStrategy.prototype.stop = function () {
  if (!this._started) {
    return false;
  }
 
  this._clearInterval();
 
  this._started = false;
 
  return true;
};
 
/**
 * @typedef {Object} EventStrategyConfig
 * @name EventStrategyConfig
 * @memberof VisSense.VisMon.Strategy.EventStrategy#
 *
 * @property {number} [throttle=50] The time in milliseconds to debounce
 * the state update. Event might fire multiple times in a short period
 * of time. If you want this feature to be disabled set debounce to 0.
 * in milliseconds.
 *
 * @description A configuration object to configure a EventStrategy instance.
 */
 
/**
 * @class
 * @name EventStrategy
 * @extends VisSense.VisMon.Strategy
 * @memberof VisSense.VisMon.Strategy
 *
 * @classdesc A strategy that registers listeners for events
 * that may change the percentage of the elements surface area within the
 * visible area of a viewer's browser window.
 *
 * Following events are listened to:
 * - scroll
 * - resize
 * - visibilitychange
 *
 * @example
 *
 * var visMon = VisSense(...).monitor({
 *   strategy: new VisSense.VisMon.Strategy.EventStrategy({
 *      throttle: 100
 *   }),
 *   update: function() {
 *     console.log('updated.');
 *   }
 * }).start();
 *
 */
VisMon.Strategy.EventStrategy = function (config) {
  this._config = defaults(config, {
    throttle: 50
  });
 
  if (this._config.debounce > 0) {
    this._config.throttle = +this._config.debounce;
  }
 
  this._started = false;
};
 
VisMon.Strategy.EventStrategy.prototype = Object.create(
  VisMon.Strategy.prototype
);
 
/**
 * @method
 * @name start
 *
 * @param {VisSense.VisMon} monitor
 *
 * @memberof VisSense.VisMon.Strategy.EventStrategy#
 */
VisMon.Strategy.EventStrategy.prototype.start = function (monitor) {
  if (!this._started) {
    this._removeEventListeners = (function (update) {
      var referenceWindow = monitor.visobj().referenceWindow();
      var visibilityApi = createVisibilityApi(referenceWindow);
 
      var removeOnVisibilityChangeEvent = visibilityApi.onVisibilityChange(update);
      referenceWindow.addEventListener('scroll', update, false);
      referenceWindow.addEventListener('resize', update, false);
      referenceWindow.addEventListener('touchmove', update, false);
 
      return function () {
        referenceWindow.removeEventListener('touchmove', update, false);
        referenceWindow.removeEventListener('resize', update, false);
        referenceWindow.removeEventListener('scroll', update, false);
        removeOnVisibilityChangeEvent();
      };
    })(throttle(function () {
      monitor.update();
    }, this._config.throttle));
 
    this._started = true;
  }
 
  return this._started;
};
 
/**
 * @method
 * @name stop
 *
 * @param {VisSense.VisMon} monitor
 *
 * @memberof VisSense.VisMon.Strategy.EventStrategy#
 */
VisMon.Strategy.EventStrategy.prototype.stop = function () {
  if (!this._started) {
    return false;
  }
 
  this._removeEventListeners();
 
  this._started = false;
 
  return true;
};
 
VisSense.VisMon = VisMon;
 
VisSense.PubSub = PubSub;
 
/**
 * @method
 * @name monitor
 * @memberof VisSense#
 *
 * @param {VisSense.VisMon#VisMonConfig} config A config object
 *
 * @returns {VisSense.VisMon} A VisMon object observing the element.
 *
 * @example
 *
 * var visMon = VisSense(...).monitor({
 *   strategy: [new VisSense.VisMon.Strategy.EventStrategy(...)]
 *   update: function() {
 *     console.log('updated.');
 *   }
 * });
 *
 */
VisSense.fn.monitor = function (config) {
  return new VisMon(this, config);
};
 
/**
 * @static
 * @namespace Utils
 * @name Utils
 * @memberof VisSense
 */
VisSense.Utils = {
  async: async,
  debounce: debounce,
  defaults: defaults,
  defer: defer,
  extend: extend,
  forEach: forEach,
  fireIf: fireIf,
  identity: identity,
  isArray: isArray,
  isDefined: isDefined,
  isElement: isElement,
  isFunction: isFunction,
  isObject: isObject,
  isPageVisible: isPageVisible,
  isVisibleByStyling: isVisibleByStyling,
  noop: noop,
  now: now,
  once: once,
 
  throttle: throttle,
 
  percentage: percentage,
 
  VisibilityApi: createVisibilityApi(),
  createVisibilityApi: createVisibilityApi,
 
  _viewport: viewport,
  _isInViewport: isInViewport,
 
  _isDisplayed: isDisplayed,
 
  _computedStyle: computedStyle,
  _styleProperty: styleProperty
};
 
 
/**
 * An object representing the current browser viewport.
 *
 * @typedef Viewport
 * @type {Object}
 * @property {number} width - width of the viewport.
 * @property {number} height - height of the viewport.
 */
 
/**
 * An object representing a rectangle with properties
 * ´top´, ´right´, ´bottom´ and ´left´ relative to the viewport.
 *
 * @typedef BoundingClientRect
 * @type {Object}
 * @property {number} top - The distance to the browsers top border.
 * @property {number} right - The distance to the browsers right border.
 * @property {number} bottom - The distance to the browsers bottom border.
 * @property {number} left - The distance to the browsers left border.
 */